我可以使用自动配置来获取 JwtDecoder bean 吗?

时间:2021-03-22 00:17:24

标签: java spring-boot spring-security jwt

目前我在 application.yml 中有这个:

spring:
  security:
    oauth2:
      keycloak:
        jwt:
          issuer-uri: http://localhost:8180/auth/realms/dev
          jwk-set-uri: http://localhost:8180/auth/realms/dev/protocol/openid-connect/certs

然后是我的安全配置:

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true, jsr250Enabled = true)
@RequiredArgsConstructor
public class MethodSecurityConfig extends WebSecurityConfigurerAdapter {

    private final RoleConverter converter;

    @Value("${spring.security.oauth2.keycloak.jwt.issuer-uri}")
    private String issuerUri;

    // @formatter:off
    @Override
    public void configure(final HttpSecurity http) throws Exception {
        http
        .headers().frameOptions().disable()
            .and()
        .csrf().disable()
        .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
        .oauth2ResourceServer(
                oauth2ResourceServer -> oauth2ResourceServer.jwt(
                        jwt -> jwt.jwtAuthenticationConverter(jwtAuthenticationConverter())));
    }
    
    // @formatter:on

    private Converter<Jwt, ? extends AbstractAuthenticationToken> jwtAuthenticationConverter() {
        JwtAuthenticationConverter jwtConverter = new JwtAuthenticationConverter();
        jwtConverter.setJwtGrantedAuthoritiesConverter(converter);
        return jwtConverter;
    }

    @Bean
    public JwtDecoder jwtDecoder() {
        return JwtDecoders.fromOidcIssuerLocation(issuerUri);
    }

}

如果我删除 @Bean public JwtDecoder jwtDecoder()... bean,则会收到此错误:

Method springSecurityFilterChain in org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration required a bean of type 'org.springframework.security.oauth2.jwt.JwtDecoder' that could not be found.

是否可以在不创建那个 bean 的情况下解决这个问题?某种自动配置?

0 个答案:

没有答案