Spring Security 已过时问题

18

我正在尝试配置JWT设置。似乎JWT已经过时了。那么现在我该如何使用OAuth2ResourceServerConfigurer::jwt呢?

我的代码:

@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    http.authorizeHttpRequests((requests) -> requests.anyRequest().authenticated());
    http.sessionManagement((session) -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
    //http.formLogin(withDefaults());
    http.httpBasic(Customizer.withDefaults());
    http.csrf(csrf -> csrf.disable());
    http.headers(headers -> headers.frameOptions(frameOptionsConfig -> frameOptionsConfig.sameOrigin()));
    http.oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt);
    return http.build();
}

此外,在Spring Security 6.0中,antMatchers()以及其他用于保护请求的配置方法(即mvcMatchers()regexMatchers())已从API中删除。

看一下这里的Danvega示例https://github.com/danvega/jwt 它帮助我很多地理解了新的变化。 - Nikolay Hristov
5个回答

26
除了@schrom的答案之外,更与OAuth2ResourceServerConfigurer#jwt的弃用相关的是,Spring Security已经弃用了返回自己配置器的方法,而是采用返回HttpSecurity的方法,并且弃用了HttpSecurity中的.and()方法。
例如,httpBasic()已被弃用,改为使用httpBasic(Customizer)。这些弃用是为了只有一种方式来配置安全DSL,即使用lambda表达式。请查看文档
因此,对于JWT配置,您需要执行以下操作:
oauth2ResourceServer((oauth2) -> oauth2
    .jwt(Customizer.withDefaults())
)

6

Spring的一般建议是先迁移到Spring 5.8版本,然后再迁移到6.0版本,以更顺利地过渡到新功能。

正如Spring Security 5.8文档所述:

在Spring Security 5.8中,已弃用antMatchers、mvcMatchers和regexMatchers方法,改用新的requestMatchers方法

据我所知,http.oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt)仍应该可以使用,甚至在有关JWT的Spring Security 6.0文档中提到:

通常,Spring类有很好的有关弃用方法的文档,即JavaDoc经常会提示使用哪个类或方法代替。


'jwt()'已被弃用并标记为将被移除 - undefined

1
只为在这里查看的Kotlin开发人员
fun filterChain(http: HttpSecurity): SecurityFilterChain {
        http.authorizeHttpRequests { auth ->
            auth.requestMatchers("/myendpoint/**").authenticated()
        }
        .oauth2ResourceServer { oauth2 -> oauth2.jwt(Customizer.withDefaults()) }

        return http.build()
    }

0

尝试这样做:

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
            http
                    // Other stuff
                    .oauth2ResourceServer((rs) ->
                            rs.jwt((jwt) ->jwt.decoder(jwtDecoder()))
                    );
            return http.build();
    }

    @Bean
    public JwtDecoder jwtDecoder() {
            // return your JWTdecoder
    }

0

我猜你正在寻找配置自定义程序的各种HTTP安全设置,你可以参考以下:

    @Value("${jwksUri}")
    private String jwksUri;

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {

        http.oauth2ResourceServer( server -> server.jwt(jwtConfigurer -> jwtConfigurer.jwkSetUri(jwksUri)));

        http.oauth2ResourceServer( server -> server.jwt(jwtConfigurer -> jwtConfigurer.decoder( myDecoder )));

        http.authorizeHttpRequests(auth -> auth.anyRequest().authenticated());

        return http.build();

    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接