gpt4 book ai didi

java - 尽管authorizeRequests().anyRequest().permitAll(),spring-security仍返回401

转载 作者:行者123 更新时间:2023-11-30 06:44:13 25 4
gpt4 key购买 nike

我使用 spring-securityspring-security-oauth2 (JWT 访问 token )进行身份验证和授权。其想法是让所有请求通过,但能够区分经过身份验证的用户和未经身份验证的用户。一旦我启用 @EnableResourceServer,我配置的 HttpSecurity 似乎就会被忽略。并且请求返回401:

{
"error": "unauthorized",
"error_description": "Full authentication is required to access this resource"
}

这是配置:

@SpringBootApplication
@EnableJpaRepositories
@ComponentScan
@EntityScan
@EnableWebSecurity
public class Application {

public static void main(final String[] args) {
new SpringApplicationBuilder(Application.class).bannerMode(Banner.Mode.OFF).run(args);
}

@EnableResourceServer
public static class SecurityConfig extends WebSecurityConfigurerAdapter implements JwtAccessTokenConverterConfigurer {

@Override
protected void configure(final HttpSecurity http) throws Exception {
http.csrf().disable();
http.authorizeRequests().anyRequest().permitAll();
}

@Override
public void configure(final JwtAccessTokenConverter converter) {
final DefaultAccessTokenConverter conv = new DefaultAccessTokenConverter();
conv.setUserTokenConverter(userAuthenticationConverter());
converter.setAccessTokenConverter(conv);

}

@Bean
public UserAuthenticationConverter userAuthenticationConverter() {
return new ResourceAuthenticationConverter();
}
}

最佳答案

你就快到了。这是一个简单的修复 - javadoc of @EnableResourceServer给出了答案:

Users should add this annotation and provide a @Bean of type ResourceServerConfigurer (e.g. via ResourceServerConfigurerAdapter) that specifies the details of the resource (URL paths and resource id).

但是,您正在使用 WebSecurityConfigurerAdapter。只需将其更改为 ResourceServerConfigurerAdapter 并增强 configure 的可见性即可:

@EnableResourceServer
public static class SecurityConfig extends ResourceServerConfigurerAdapter implements JwtAccessTokenConverterConfigurer {
// snip
@Override
public void configure(final HttpSecurity http) throws Exception {
http.csrf().disable();
http.authorizeRequests().anyRequest().permitAll();
}
// snip

关于java - 尽管authorizeRequests().anyRequest().permitAll(),spring-security仍返回401,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43931255/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com