最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

springSecurity實(shí)現(xiàn)簡(jiǎn)單的登錄功能

 更新時(shí)間:2022年09月06日 14:58:33   作者:_Kc  
這篇文章主要為大家詳細(xì)介紹了springSecurity實(shí)現(xiàn)簡(jiǎn)單的登錄功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下

前言

1、不使用數(shù)據(jù)庫(kù),實(shí)現(xiàn)一個(gè)簡(jiǎn)單的登錄功能,只有在登錄后才能訪問我們的接口
2、springSecurity提供了一種基于內(nèi)存的驗(yàn)證方法(使用自己定義的用戶,不使用默認(rèn)的)

一、實(shí)現(xiàn)用戶創(chuàng)建,登陸后才能訪問接口(注重用戶認(rèn)證)

1.定義一個(gè)內(nèi)存用戶,不使用默認(rèn)用戶

重寫configure(AuthenticationManagerBuilder auth)方法,實(shí)現(xiàn)在內(nèi)存中定義一個(gè) (用戶名/密碼/權(quán)限:admin/123456/admin) 的用戶

package com.example.springsecurity;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.stereotype.Component;

@Configuration
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
? ? @Override
? ? protected void configure(AuthenticationManagerBuilder auth) throws Exception {
? ? ? ? //基于內(nèi)存的驗(yàn)證方法
? ? ? ? auth.inMemoryAuthentication().withUser("admin").password("123456").roles("admin");
? ? }

? ? @Override
? ? public void configure(WebSecurity web) throws Exception { ? ? ? ? ? ? //批處理靜態(tài)資源,都不攔截處理
? ? ? ? web.ignoring().mvcMatchers("/js/**","/css/**","/images/**");
? ? }

? ? @Override
? ? protected void configure(HttpSecurity http) throws Exception { ? ? ? // 這是一個(gè)重要的方法,這個(gè)方法決定了我們哪些請(qǐng)求會(huì)被攔截以及一些請(qǐng)求該怎么處理
? ? ? ? http.authorizeRequests() ?//安全過濾策略
? ? ? ? ? ? ? ? .antMatchers("/").permitAll()
? ? ? ? ? ? ? ? .anyRequest().authenticated()
? ? ? ? ? ? ? ? .and() //and添加允許別的操作
? ? ? ? ? ? ? ? .logout().permitAll() //允許支持注銷,支持隨意訪問
? ? ? ? ? ? ? ? .and()
? ? ? ? ? ? ? ? .formLogin(); ? //允許表單登錄
? ? ? ? http.csrf().disable(); ?//關(guān)閉csrf認(rèn)證
? ? }
}

2.效果

根目錄可以直接通過驗(yàn)證,其他接口需要經(jīng)過springSecurity,輸入admin 123456后登陸系統(tǒng)

3.退出登陸

地址欄輸入:http://localhost:8080/login?logout,執(zhí)行退出登陸

4.再創(chuàng)建一個(gè)張三用戶,同時(shí)支持多用戶登陸

package com.example.springsecurity;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.stereotype.Component;

@Configuration
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
? ? @Override
? ? protected void configure(AuthenticationManagerBuilder auth) throws Exception {
? ? ? ? //基于內(nèi)存的驗(yàn)證方法
? ? ? ? auth.inMemoryAuthentication().withUser("admin").password("123456").roles("admin");
? ? ? ? auth.inMemoryAuthentication().withUser("zhangsan").password("123456").roles("admin");
? ? }

? ? @Override
? ? public void configure(WebSecurity web) throws Exception { ? ? ? ? ? ? //批處理靜態(tài)資源,都不攔截處理
? ? ? ? web.ignoring().mvcMatchers("/js/**","/css/**","/images/**");
? ? }

? ? @Override
? ? protected void configure(HttpSecurity http) throws Exception { ? ? ? // 這是一個(gè)重要的方法,這個(gè)方法決定了我們哪些請(qǐng)求會(huì)被攔截以及一些請(qǐng)求該怎么處理
? ? ? ? http.authorizeRequests() ?//安全過濾策略
? ? ? ? ? ? ? ? .antMatchers("/").permitAll()
? ? ? ? ? ? ? ? .anyRequest().authenticated()
? ? ? ? ? ? ? ? .and() //and添加允許別的操作
? ? ? ? ? ? ? ? .logout().permitAll() //允許支持注銷,支持隨意訪問
? ? ? ? ? ? ? ? .and()
? ? ? ? ? ? ? ? .formLogin(); ? //允許表單登錄
? ? ? ? http.csrf().disable(); ?//關(guān)閉csrf認(rèn)證
? ? }
}

二、實(shí)現(xiàn)管理員功能(注重權(quán)限控制)

實(shí)現(xiàn)角色功能,不同角色擁有不同功能:管理員擁有管理功能,而普通組員只能擁有最普通的功能

1.創(chuàng)建一個(gè)普通用戶demo

auth.inMemoryAuthentication().withUser("demo").password("demo").roles("user");

創(chuàng)建demo用戶,角色為demo,詳細(xì)代碼如下

package com.example.springsecurity;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.stereotype.Component;

@Configuration
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
? ? @Override
? ? protected void configure(AuthenticationManagerBuilder auth) throws Exception {
? ? ? ? //基于內(nèi)存的驗(yàn)證方法
? ? ? ? auth.inMemoryAuthentication().withUser("admin").password("123456").roles("admin");
? ? ? ? auth.inMemoryAuthentication().withUser("zhangsan").password("123456").roles("admin");
? ? ? ? auth.inMemoryAuthentication().withUser("demo").password("demo").roles("user");
? ? }

? ? @Override
? ? public void configure(WebSecurity web) throws Exception { ? ? ? ? ? ? //批處理靜態(tài)資源,都不攔截處理
? ? ? ? web.ignoring().mvcMatchers("/js/**","/css/**","/images/**");
? ? }

? ? @Override
? ? protected void configure(HttpSecurity http) throws Exception { ? ? ? // 這是一個(gè)重要的方法,這個(gè)方法決定了我們哪些請(qǐng)求會(huì)被攔截以及一些請(qǐng)求該怎么處理
? ? ? ? http.authorizeRequests() ?//安全過濾策略
? ? ? ? ? ? ? ? .antMatchers("/").permitAll()
? ? ? ? ? ? ? ? .anyRequest().authenticated()
? ? ? ? ? ? ? ? .and() //and添加允許別的操作
? ? ? ? ? ? ? ? .logout().permitAll() //允許支持注銷,支持隨意訪問
? ? ? ? ? ? ? ? .and()
? ? ? ? ? ? ? ? .formLogin(); ? //允許表單登錄
? ? ? ? http.csrf().disable(); ?//關(guān)閉csrf認(rèn)證
? ? }
}

2.創(chuàng)建/roleAuth接口

此接口只能admin角色才能登陸

1)、@EnableGlobalMethodSecurity注解使role驗(yàn)證注解生效
2)、@PreAuthorize(“hasRole(‘ROLE_admin’)”)注解聲明哪個(gè)角色能訪問此接口

package com.example.springsecurity;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.config.annotation.authentication.configuration.EnableGlobalAuthentication;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@SpringBootApplication
@EnableGlobalMethodSecurity(prePostEnabled = true) ?//必須加這行,不然role驗(yàn)證無效
public class SpringsecurityApplication {

? ? public static void main(String[] args) {
? ? ? ? SpringApplication.run(SpringsecurityApplication.class, args);
? ? }

? ? @RequestMapping("/")
? ? public String home(){
? ? ? ? return "hello spring boot";
? ? }

? ? @RequestMapping("/hello")
? ? public String hello(){
? ? ? ? return "hello word";
? ? }

? ? @PreAuthorize("hasRole('ROLE_admin')") ?//當(dāng)我們期望這個(gè)方法經(jīng)過role驗(yàn)證的時(shí)候,需要加這個(gè)注解;ROLE必須大寫
? ? @RequestMapping("/roleAuth")
? ? public String role(){
? ? ? ? return "admin ?Auth";
? ? }

}

3.效果

demo用戶登陸成功可以訪問/接口,但是不能訪問/roleAuth接口

admin管理員既能訪問/接口,也能訪問/roleAuth接口

三、實(shí)現(xiàn)數(shù)據(jù)庫(kù)管理用戶(注重?cái)?shù)據(jù)庫(kù)認(rèn)證用戶)

1.我們需要把之前創(chuàng)建的admin zhangsan demo三個(gè)用戶放到數(shù)據(jù)庫(kù)中 2.我們需要使用MyUserService來管理這些用戶
1.創(chuàng)建一個(gè)MyUserService類
1.此類實(shí)現(xiàn)UserDetailsService(這邊不真實(shí)查詢數(shù)據(jù)庫(kù))

package com.example.springsecurity;

import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

@Component
public class MyUserService implements UserDetailsService {
? ? @Override
? ? public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
? ? ? ? return null;//數(shù)據(jù)庫(kù)操作邏輯
? ? }
}

2.密碼自定義驗(yàn)證類
1.此類實(shí)現(xiàn)自定義密碼驗(yàn)證

package com.example.springsecurity;

import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

public class MyPasswdEncoder implements PasswordEncoder {
? ? private final static String SALT = "123456";
? ? @Override
? ? public String encode(CharSequence rawPassword) {
? ? ? ? //加密:堆原始的密碼進(jìn)行加密,這邊使用md5進(jìn)行加密
? ? ? ? Md5PasswordEncoder encoder = new Md5PasswordEncoder();
? ? ? ? return encoder.encodePassword(rawPassword.toString(), SALT);
? ? }

? ? @Override
? ? public boolean matches(CharSequence rawPassword, String encodedPassword) {
? ? ? ? //拿原始的密碼和加密后的密碼進(jìn)行匹配
? ? ? ? Md5PasswordEncoder encoder = new Md5PasswordEncoder();
? ? ? ? return encoder.isPasswordValid(encodedPassword,rawPassword.toString(),SALT);
? ? }
}

3.自定義數(shù)據(jù)庫(kù)查詢&默認(rèn)數(shù)據(jù)庫(kù)查詢、自定義密碼驗(yàn)證配置
1.支持自定義數(shù)據(jù)庫(kù)查詢 2.支持默認(rèn)數(shù)據(jù)庫(kù)查詢(數(shù)據(jù)庫(kù)結(jié)構(gòu)必須和默認(rèn)的一致) 兩者選擇其中一個(gè)

package com.example.springsecurity;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.stereotype.Component;

@Configuration
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

? ? @Autowired
? ? MyUserService myUserService;

? ? @Override
? ? protected void configure(AuthenticationManagerBuilder auth) throws Exception {
? ? ? ? //基于內(nèi)存的驗(yàn)證方法
// ? ? ? ?auth.inMemoryAuthentication().withUser("admin").password("123456").roles("admin");
// ? ? ? ?auth.inMemoryAuthentication().withUser("zhangsan").password("123456").roles("admin");
// ? ? ? ?auth.inMemoryAuthentication().withUser("demo").password("demo").roles("user");


? ? ? ? //1、自己實(shí)現(xiàn)數(shù)據(jù)庫(kù)的查詢,指定我們要使用的UserService和自定義的密碼驗(yàn)證器
? ? ? ? auth.userDetailsService(myUserService).passwordEncoder(new MyPasswdEncoder());
? ? ? ? //2、sprinSecurity在數(shù)據(jù)庫(kù)管理方面支持一套默認(rèn)的處理,可以指定根據(jù)用戶查詢,權(quán)限查詢,這情況下用戶表必須和默認(rèn)的表結(jié)構(gòu)相同,具體查看user.ddl文件

? ? ? ? auth.jdbcAuthentication().usersByUsernameQuery("").authoritiesByUsernameQuery("").passwordEncoder(new MyPasswdEncoder());
? ? }

? ? @Override
? ? public void configure(WebSecurity web) throws Exception { ? ? ? ? ? ? //批處理靜態(tài)資源,都不攔截處理
? ? ? ? web.ignoring().mvcMatchers("/js/**","/css/**","/images/**");
? ? }

? ? @Override
? ? protected void configure(HttpSecurity http) throws Exception { ? ? ? // 這是一個(gè)重要的方法,這個(gè)方法決定了我們哪些請(qǐng)求會(huì)被攔截以及一些請(qǐng)求該怎么處理
? ? ? ? http.authorizeRequests() ?//安全過濾策略
? ? ? ? ? ? ? ? .antMatchers("/").permitAll()
? ? ? ? ? ? ? ? .anyRequest().authenticated()
? ? ? ? ? ? ? ? .and() //and添加允許別的操作
? ? ? ? ? ? ? ? .logout().permitAll() //允許支持注銷,支持隨意訪問
? ? ? ? ? ? ? ? .and()
? ? ? ? ? ? ? ? .formLogin(); ? //允許表單登錄
? ? ? ? http.csrf().disable(); ?//關(guān)閉csrf認(rèn)證
? ? }
}

四、sprinSecurity支持的4種使用表達(dá)式的權(quán)限注解

1.支持的4種注解

@PreAuthorize("hasRole('ROLE_admin')") ?//1.方法調(diào)用前:當(dāng)我們期望這個(gè)方法經(jīng)過role驗(yàn)證的時(shí)候,需要加這個(gè)注解;ROLE必須大寫
? ? @PostAuthorize("hasRole('ROLE_admin')")//2.方法調(diào)用后
? ? @PreFilter("")//2.對(duì)集合類的參數(shù)或返回值進(jìn)行過濾
? ? @PostFilter("")//2.對(duì)集合類的參數(shù)或返回值進(jìn)行過濾
? ? @RequestMapping("/roleAuth")
? ? public String role(){
? ? ? ? return "admin ?Auth";
? ? }

2.注解的參數(shù)該怎么傳

or用法:

參數(shù)的值判斷

and運(yùn)算

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • java代碼執(zhí)行字符串中的邏輯運(yùn)算方法

    java代碼執(zhí)行字符串中的邏輯運(yùn)算方法

    今天小編就為大家分享一篇java代碼執(zhí)行字符串中的邏輯運(yùn)算方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2018-07-07
  • java如何在應(yīng)用代碼里捕獲線程堆棧

    java如何在應(yīng)用代碼里捕獲線程堆棧

    這篇文章主要為大家介紹了java如何在應(yīng)用代碼里捕獲線程堆棧實(shí)現(xiàn)示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-12-12
  • java實(shí)現(xiàn)ftp文件上傳下載功能

    java實(shí)現(xiàn)ftp文件上傳下載功能

    這篇文章主要為大家詳細(xì)介紹了java實(shí)現(xiàn)ftp文件上傳下載功能的相關(guān)資料,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2017-04-04
  • 深入了解MyBatis二級(jí)緩存

    深入了解MyBatis二級(jí)緩存

    今天小編就為大家分享一篇關(guān)于深入了解MyBatis二級(jí)緩存,小編覺得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來看看吧
    2018-12-12
  • Java利用opencv實(shí)現(xiàn)用字符展示視頻或圖片的方法

    Java利用opencv實(shí)現(xiàn)用字符展示視頻或圖片的方法

    這篇文章主要介紹了Java利用opencv實(shí)現(xiàn)用字符展示視頻或圖片的方法,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2020-12-12
  • 淺談十個(gè)常見的Java異常出現(xiàn)原因

    淺談十個(gè)常見的Java異常出現(xiàn)原因

    這篇文章主要介紹了十個(gè)常見的Java異常出現(xiàn)原因,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-03-03
  • java 可重啟線程及線程池類的設(shè)計(jì)(詳解)

    java 可重啟線程及線程池類的設(shè)計(jì)(詳解)

    下面小編就為大家?guī)硪黄猨ava 可重啟線程及線程池類的設(shè)計(jì)(詳解)。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2017-01-01
  • java UUID&雪花算法生成和使用場(chǎng)景詳解

    java UUID&雪花算法生成和使用場(chǎng)景詳解

    UUID和雪花算法都是用于生成唯一標(biāo)識(shí)符的有效工具,它們各有優(yōu)勢(shì):UUID簡(jiǎn)單易用,但長(zhǎng)度較長(zhǎng),適用于分布式系統(tǒng);雪花算法生成的ID較短且有序,適用于需要保證順序的場(chǎng)景,在選擇算法時(shí),需要考慮系統(tǒng)架構(gòu)、性能需求和順序需求等因素
    2025-01-01
  • Java中使用正則表達(dá)式的一個(gè)簡(jiǎn)單例子及常用正則分享

    Java中使用正則表達(dá)式的一個(gè)簡(jiǎn)單例子及常用正則分享

    這篇文章主要介紹了Java中使用正則表達(dá)式的一個(gè)簡(jiǎn)單例子及常用正則分享,本文用一個(gè)驗(yàn)證Email的例子講解JAVA中如何使用正則,并羅列了一些常用的正則表達(dá)式,需要的朋友可以參考下
    2015-06-06
  • 解決JDK異常處理No appropriate protocol問題

    解決JDK異常處理No appropriate protocol問題

    這篇文章主要介紹了解決JDK異常處理No appropriate protocol問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-06-06

最新評(píng)論

沐川县| 泰兴市| 电白县| 阿坝县| 镇远县| 苏尼特左旗| 金湖县| 辽宁省| 河北省| 交口县| 宜兰市| 康平县| 西畴县| 济阳县| 万宁市| 晴隆县| 临邑县| 丹江口市| 疏附县| 西盟| 集安市| 酉阳| 定州市| 伊金霍洛旗| 图片| 金寨县| 永善县| 五台县| 乐陵市| 淮安市| 恩平市| 夏津县| 合江县| 胶南市| 华蓥市| 贵溪市| 金阳县| 江源县| 南丰县| 内江市| 绥德县|