亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

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

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

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

項(xiàng)目依賴

<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>

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

認(rèn)證

首先我們先完成通過賬號(hào)密碼進(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)注幾個(gè)重點(diǎn):

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

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

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

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

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`

請(qǐng)求另外一個(gè)接口

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

權(quán)限控制

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

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

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

小結(jié)

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

這里推薦一下自己的項(xiàng)目地址,已經(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)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論