spring-security Spring 安全:从jwt生成身份验证

sqserrrh  于 2022-11-11  发布在  Spring
关注(0)|答案(1)|浏览(194)

这里我的配置:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfiguration {

    @Bean
    public JwtDecoder reactiveJwtDecoder() throws Exception {
        Mac mac = Mac.getInstance("HmacSHA256");
        SecretKeySpec secretKey = new SecretKeySpec("JAC1O17W1F3QB9E8B4B1MT6QKYOQB36V".getBytes(), mac.getAlgorithm());

        return NimbusJwtDecoder.withSecretKey(secretKey)
            .macAlgorithm(MacAlgorithm.HS256)
            .build();
    }

    @Bean
    public SecurityFilterChain securityFilterChain(
        HttpSecurity http
    ) throws Exception {
        Customizer<OAuth2ResourceServerConfigurer<HttpSecurity>> oauth2Customizer = (config) -> config.jwt();
        return http
        .httpBasic().disable()
        .csrf().disable()
        .formLogin().disable()
        .anonymous().disable()
        .logout().disable()
        .authorizeHttpRequests((authorize) -> authorize
        .antMatchers("/actuator/**").permitAll()
        .antMatchers("/gicar/**").permitAll()
        .anyRequest().authenticated()
        )
        .oauth2ResourceServer(oauth2Customizer)
        .build();
    }

}

一切正常。
我需要根据jwt标记信息允许方法执行。
我知道,为了得到这个结果,我需要将jwt标记转换为Authentication对象。
从我的配置开始,为了生成一个Authentication对象并将声明转换为授权,我应该向它添加什么?
我需要做的事情是这样的:

@RestController
@RequestMapping(value = "/qdcf")
@RequiredArgsConstructor
@Timed
public class QdCFController {

    private final UsuariRepository usuariRepository;

    @GetMapping("/user")
    @PreAuthorize("hasRole(ADMIN)")
    public Optional<Usuari> user() {
        return this.usuariRepository.findOne(UsuariSpecs.hasCodi("11111111A"));
    }

}
ig9co6j1

ig9co6j11#

您的配置已经足以让Spring创建一个Authentication对象,问题是它将如何从您的JWT中获取角色。
要“引导”Spring和您的JwtDecoder,您应该创建并配置JwtAuthenticationConverter类型的bean,例如:

@Bean
public JwtAuthenticationConverter jwtAuthenticationConverter() {
    final JwtGrantedAuthoritiesConverter grantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter();
    // choose a JWT claim name where authorities are stored on login
    // authorities claim name defaults to "scope" and "scp" if this method is not used
    grantedAuthoritiesConverter.setAuthoritiesClaimName("roles");
    // here choose a scope prefix that was used
    // prefix defaults to "SCOPE_" if this method is not used
    grantedAuthoritiesConverter.setAuthorityPrefix("");

    final JwtAuthenticationConverter jwtAuthenticationConverter = new JwtAuthenticationConverter();
    jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(grantedAuthoritiesConverter);
    return jwtAuthenticationConverter;
}

此配置将帮助JwtDecoder将JWT的 “roles” 声明中的任何权限转换为不带前缀的GrantedAuthority

相关问题