LoginSignup
0
2

Spring boot3 Security(JWT)にハマったところ

Last updated at Posted at 2023-08-04

■認証アルゴリズムが変わった

今までは「SignatureAlgorithm.HS512」を使っていたのですが、
Spring boot3 Spring Security6だと動かないので「SignatureAlgorithm.HS256」に変更しました。
デフォルトのアルゴリズムもHS256のようで、切り替えは早めにやったほうがいいですね。

import io.jsonwebtoken.security.Keys;
import io.jsonwebtoken.io.Decoders;

  private Key getSignInKey() {
    byte[] keyBytes = Decoders.BASE64.decode(secretKey);
    return Keys.hmacShaKeyFor(keyBytes);
  }

signWithは以下のように書きます。
Jwts.builder().signWith(getSignInKey(), SignatureAlgorithm.HS256)

■WebSecurityConfigurerAdapterは非推奨で継承してはいけない
→変わりにfilterChainを使用してください。

・変更前

@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests((authz) -> authz
                .anyRequest().authenticated()
            )
            .httpBasic(withDefaults());
    }

}

・変更後

@Configuration
public class SecurityConfiguration {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests((authz) -> authz
                .anyRequest().authenticated()
            )
            .httpBasic(withDefaults());
        return http.build();
    }

}

引用サイト:
https://spring.io/blog/2022/02/21/spring-security-without-the-websecurityconfigureradapter

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2