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

SpringSecurity6.0 如何通過JWTtoken進(jìn)行認(rèn)證授權(quán)

 更新時間:2025年04月09日 16:30:01   作者:nyzzht123  
這篇文章主要介紹了SpringSecurity6.0 通過JWTtoken進(jìn)行認(rèn)證授權(quán)的過程,本文給大家介紹的非常詳細(xì),感興趣的朋友一起看看吧

之前寫過一個文章,從SpringSecurity 5.x升級到6.0,當(dāng)時是為了配合公司的大版本升級做的,里面的各項配置都是前人留下來的,其實沒有花時間進(jìn)行研究SpringSecurity的工作機制?,F(xiàn)在新東家有一個簡單的系統(tǒng)要搭建,用戶的認(rèn)證授權(quán)流程也比較簡單,通過用戶/密碼進(jìn)行登錄,登錄后生成JWT token返回給前端,后續(xù)認(rèn)證通過token進(jìn)行,就把SpringSecurity重新?lián)炝似饋?,搭建整個系統(tǒng)的安全認(rèn)證框架。

項目依賴

<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>3.4.4</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-security</artifactId>
		</dependency>
		<!-- jwt token相關(guān)依賴-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
		</dependency>
	<dependencies>

項目后端整體還是通過Springboot來搭建,Springboot3.0中把JWT相關(guān)的依賴都整合到了spring-boot-starter-oauth2-resource-server中,無需再單獨指定

認(rèn)證

首先我們先完成通過賬號密碼進(jìn)行登錄相關(guān)代碼

@Configuration
@EnableWebSecurity
public class SecurityConfig {
  @Value("${jwt.public.key}")
  RSAPublicKey key;
  @Value("${jwt.private.key}")
  RSAPrivateKey priv;
  @Bean
  public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    // @formatter:off
    http
        .authorizeHttpRequests((authorize) -> authorize
            .anyRequest().authenticated()
        )
        .csrf((csrf) -> csrf.ignoringRequestMatchers("/token"))
        .httpBasic(Customizer.withDefaults())
        .oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt)
        .sessionManagement((session) -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
        .exceptionHandling((exceptions) -> exceptions
            .authenticationEntryPoint(new BearerTokenAuthenticationEntryPoint())
            .accessDeniedHandler(new BearerTokenAccessDeniedHandler())
        );
    // @formatter:on
    return http.build();
  }
  @Bean
  UserDetailsService users() {
    // @formatter:off
    return new InMemoryUserDetailsManager(
        User.withUsername("user")
            .password("{noop}password")
            .authorities("app")
            .build()
    );
    // @formatter:on
  }
  @Bean
  JwtDecoder jwtDecoder() {
    return NimbusJwtDecoder.withPublicKey(this.key).build();
  }
  @Bean
  JwtEncoder jwtEncoder() {
    JWK jwk = new RSAKey.Builder(this.key).privateKey(this.priv).build();
    JWKSource<SecurityContext> jwks = new ImmutableJWKSet<>(new JWKSet(jwk));
    return new NimbusJwtEncoder(jwks);
  }
}

這里關(guān)注幾個重點:

  • HttpSecurity#httpBasic,這個方法表明通過基于HTTP Basic認(rèn)證協(xié)議
  • anyRequest().authenticated()表明所有請求都需要經(jīng)過認(rèn)證
  • UserDetailsService,這里創(chuàng)建了一個僅存在于內(nèi)存中的用戶,用戶名和密碼是user/password,密碼中添加的前綴{noop}和userDetailService的作用我們稍后再說oauth2ResourceServer設(shè)置jwt token相關(guān)的配置,Spring推薦情況是配置一個第三方的校驗服務(wù),我們這里為了簡化將相關(guān)的生成和校驗都在本地進(jìn)行。

UserDetailService

public interface UserDetailsService {
	/**
	 * Locates the user based on the username. In the actual implementation, the search
	 * may possibly be case sensitive, or case insensitive depending on how the
	 * implementation instance is configured. In this case, the <code>UserDetails</code>
	 * object that comes back may have a username that is of a different case than what
	 * was actually requested..
	 * @param username the username identifying the user whose data is required.
	 * @return a fully populated user record (never <code>null</code>)
	 * @throws UsernameNotFoundException if the user could not be found or the user has no
	 * GrantedAuthority
	 */
	UserDetails loadUserByUsername(String username) throws UsernameNotFoundException;
}

這個接口里只定義了一個方法,loadUserByUsername在通過用戶名/密碼進(jìn)行認(rèn)證時,需要通過來判斷用戶是否存在,在生產(chǎn)中,我們可以根據(jù)自己的需要通過數(shù)據(jù)庫等獲取用戶信息。
拿到用戶信息之后,要怎么校驗密碼呢?SpringSecurity提供了另外一個接口PasswordEncoder進(jìn)行密碼的編碼和校驗,

這里提供了非常多的實現(xiàn)方式,默認(rèn)情況下Spring會加載DelegatingPasswordEncoder,同時將其他的實現(xiàn)都包含進(jìn)去,那在進(jìn)行密碼校驗的時候要匹配哪一個Encoder呢,這里{noop}password中的前綴就發(fā)揮作用了,{noop}表明使用NoOpPasswordEncoder進(jìn)行處理,即不僅限任何編碼處理,直接通過明文進(jìn)行對比,這里當(dāng)然不符合安全要求,在實際工作中我們根據(jù)需要直接指定一個Encoder即可

  @Bean
  PasswordEncoder passwordEncoder(){
    return new BCryptPasswordEncoder();
  }

生成JWT token

@RestController
public class TokenController {
  @Autowired
  JwtEncoder encoder;
  @PostMapping("/token")
  public String token(Authentication authentication) {
    Instant now = Instant.now();
    long expiry = 36000L;
    // @formatter:off
    String scope = authentication.getAuthorities().stream()
        .map(GrantedAuthority::getAuthority)
        .collect(Collectors.joining(" "));
    JwtClaimsSet claims = JwtClaimsSet.builder()
        .issuer("self")
        .issuedAt(now)
        .expiresAt(now.plusSeconds(expiry))
        .subject(authentication.getName())
        .claim("scope", scope)
        .build();
    // @formatter:on
    return this.encoder.encode(JwtEncoderParameters.from(claims)).getTokenValue();
  }
}

這里有一個小提示,我們在創(chuàng)建UserDetail的時候可以設(shè)置#authorities()#roles(),但是最終都會設(shè)置到authorities中,這兩個在當(dāng)今的SpringSecurity中實際上是一個東西,所以我們在Authentication中也只有getAuthorities()這一個方法
進(jìn)行測試

curl -XPOST user:password@localhost:8080/token

然后能夠得到類似的返回

eyJhbGciOiJSUzI1NiJ9.eyJpc3MiOiJzZWxmIiwic3ViIjoidXNlciIsImV4cCI6MTYwNDA0MzA1MSwiaWF0IjoxNjA0MDA3MDUxfQ.yDF_JgSwl5sk21CF7AE1AYbYzRd5YYqe3MIgSWpgN0t2UqsjaaEDhmmICKizt-_0iZy8nkEpNnvgqv5bOHDhs7AXlYS1pg8dgPKuyfkhyVIKa3DhuGyb7tFjwJxHpr128BXf1Dbq-p7Njy46tbKsZhP5zGTjdXlqlAhR4Bl5Fxaxr7D0gdTVBVTlUp9DCy6l-pTBpsvHxShkjXJ0GHVpIZdB-c2e_K9PfTW5MDPcHekG9djnWPSEy-fRvKzTsyVFhdy-X3NXQWWkjFv9bNarV-bhxMlzqhujuaeXJGEqUZlkhBxTsqFr1N7XVcmhs3ECdjEyun2fUSge4BoC7budsQ

然后我們把token配置到環(huán)境變量中

export TOKEN=`curl -XPOST user:password@localhost:8080/token`

請求另外一個接口

curl -H "Authorization: Bearer $TOKEN" localhost:8080 && echo
Hello, user!

權(quán)限控制

在完成認(rèn)證后,后續(xù)我們可以繼續(xù)進(jìn)行授權(quán)相關(guān)的校驗工作,SpringSecurity提供兩種授權(quán)校驗的方式

  • 基于http請求的方式,包括路徑匹配、請求方法匹配等,
  • 基于方法的控制,通過@PreAuthorize等注解,在方法上進(jìn)行更細(xì)粒度的控制,我采用了這一種方式
  @PreAuthorize("hasAuthority('SCOPE_ADMIN')")//JWT token解析后會加一個前綴'scope'
  @GetMapping("/admin")
  public String admin(Authentication authentication){
    return authentication.getAuthorities().toString();
  }

默認(rèn)情況下,Authority中的內(nèi)容會比你生成token時多加一個前綴SCOPE_,當(dāng)然你也可以通過配置進(jìn)行更改。

小結(jié)

這里簡單介紹了一下認(rèn)證和授權(quán)的配置,實際上SpringSecurity要遠(yuǎn)比這些要復(fù)雜的多,有更深入的需求可以參考官方文檔或者源碼

這里推薦一下自己的項目地址,已經(jīng)把用戶配置到h2數(shù)據(jù)庫中
https://gitee.com/xiiiao/hello-spring-security

到此這篇關(guān)于SpringSecurity6.0 通過JWTtoken進(jìn)行認(rèn)證授權(quán)的文章就介紹到這了,更多相關(guān)SpringSecurity認(rèn)證授權(quán)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • SpringBoot實戰(zhàn)記錄之?dāng)?shù)據(jù)訪問

    SpringBoot實戰(zhàn)記錄之?dāng)?shù)據(jù)訪問

    對于數(shù)據(jù)訪問層,無論是SQL還是NOSQL,Spring Boot默認(rèn)采用整合Spring Data的方式進(jìn)行統(tǒng)一處理,添加大量自動配置,屏蔽了很多設(shè)置,下面這篇文章主要介紹了SpringBoot實戰(zhàn)記錄之?dāng)?shù)據(jù)訪問,需要的朋友可以參考下
    2022-04-04
  • 利用java和sqlserver建立簡易圖書管理系統(tǒng)的完整步驟

    利用java和sqlserver建立簡易圖書管理系統(tǒng)的完整步驟

    圖書館管理系統(tǒng)是圖書館管理工作中不可缺少的部分,它對于圖書館的管理者和使用者都非常重要,下面這篇文章主要給大家介紹了關(guān)于利用java和sqlserver建立簡易圖書管理系統(tǒng)的完整步驟,需要的朋友可以參考下
    2022-06-06
  • Spring boot集成Go-FastDFS實現(xiàn)圖片上傳刪除等功能實現(xiàn)

    Spring boot集成Go-FastDFS實現(xiàn)圖片上傳刪除等功能實現(xiàn)

    這篇文章主要介紹了Spring boot集成Go-FastDFS實現(xiàn)圖片上傳刪除等功能實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-04-04
  • spring集成redis cluster詳解

    spring集成redis cluster詳解

    這篇文章主要介紹了spring集成redis cluster詳解,分享了maven依賴,Spring配置,增加connect-redis.properties 配置文件等相關(guān)內(nèi)容,具有一定參考價值,需要的朋友可以了解下。
    2017-11-11
  • MyBatis saveBatch 性能調(diào)優(yōu)的實現(xiàn)

    MyBatis saveBatch 性能調(diào)優(yōu)的實現(xiàn)

    本文主要介紹了MyBatis saveBatch 性能調(diào)優(yōu)的實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2023-07-07
  • java中排序報:Comparison method violates its general contract異常的解決

    java中排序報:Comparison method violates its general contract異常的解

    這篇文章主要給大家介紹了關(guān)于java中排序報:Comparison method violates its general contract異常的解決方法,文中介紹的非常詳細(xì),對大家具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起看看吧。
    2017-06-06
  • 詳解mybatis-plus配置找不到Mapper接口路徑的坑

    詳解mybatis-plus配置找不到Mapper接口路徑的坑

    這篇文章主要介紹了詳解mybatis-plus配置找不到Mapper接口路徑的坑,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-10-10
  • Spring Cloud 配置中心內(nèi)容加密的配置方法

    Spring Cloud 配置中心內(nèi)容加密的配置方法

    這篇文章主要介紹了Spring Cloud 配置中心內(nèi)容加密的配置方法,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下
    2018-06-06
  • MyBatis-Plus 動態(tài)表名SQL解析器的實現(xiàn)

    MyBatis-Plus 動態(tài)表名SQL解析器的實現(xiàn)

    這篇文章主要介紹了MyBatis-Plus 動態(tài)表名SQL解析器的實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-08-08
  • Java中有什么工具可以進(jìn)行代碼反編譯詳解

    Java中有什么工具可以進(jìn)行代碼反編譯詳解

    這篇文章主要介紹了Java中有什么工具可以進(jìn)行代碼反編譯的相關(guān)資,料,包括JD-GUI、CFR、Procyon、Fernflower、Javap、BytecodeViewer、Krakatau和JAD,每種工具都有其特點和適用場景,需要的朋友可以參考下
    2025-03-03

最新評論

故城县| 荔波县| 石河子市| 内江市| 卓尼县| 共和县| 霸州市| 桂东县| 五家渠市| 仁布县| 上饶市| 武定县| 常熟市| 修武县| 新丰县| 江达县| 丰宁| 铜鼓县| 周至县| 越西县| 阿合奇县| 旅游| 阳原县| 阿克苏市| 彭水| 辛集市| 洛浦县| 青海省| 普格县| 沾化县| 望都县| 杂多县| 罗田县| 濮阳县| 邢台县| 横山县| 洛阳市| 怀仁县| 平江县| 屏边| 太康县|