gpt4 book ai didi

java - OAuth2 WebSecurityConfigurerAdapter 规则的意义是什么,因为它没有比 ResourceServerConfigurerAdapter 更高的优先级

转载 作者:行者123 更新时间:2023-12-02 00:57:28 35 4
gpt4 key购买 nike

我使用 OAuth2 进行授权,但在 WebSecurityConfigurerAdapter 中没有找到 configure(HttpSecurity http) 重写的用法,因为它根本没有执行,因为 ResourceServerConfigurerAdapter 的优先级高于它。

执行顺序为:AuthorizationServerConfigurerAdapter -> ResourceServerConfigurerAdapter -> WebSecurityConfigurerAdapter。它可以通过 @Order 手动更改,但它会以某种方式破坏 token ,所以我宁愿不这样做。

假设我注释了 ResourceServerConfigurerAdapter 中的所有内容,然后尝试访问 /api/topics。在这种情况下,我将收到以下消息:

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

这意味着我在 WebSecurityConfigurerAdapter 中的规则根本不会执行,即使我有 .antMatchers("/api/topics/**").permitAll() 。重点是什么?允许 /api/** 并授权其他任何内容的正确方法是什么?

顺便说一下,我正在使用spring-security-oauth2-autoconfigure@2.2.6.RELEASE

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
@Qualifier("userDetailsService")
private UserDetailsServiceImpl userDetailsService;

@Autowired
private BCryptPasswordEncoder bCryptPasswordEncoder;

@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.userDetailsService(userDetailsService)
.passwordEncoder(bCryptPasswordEncoder);
}

@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/api/topics/**").permitAll()
.antMatchers("/api/users/**").permitAll()
.antMatchers("/oauth/token**", "/oauth/authorize**").permitAll()
.anyRequest().authenticated()
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}

}
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

@Override
public void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/api/**").permitAll()
.anyRequest().authenticated();
}

}
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

@Value("${oauth.clientId}")
private String clientId;

@Value("${oauth.clientSecret}")
private String clientSecret;

@Value("${oauth.accessTokenValidity}")
private int accessTokenValidity;

@Value("${oauth.refreshTokenValidity}")
private int refreshTokenValidity;

@Autowired
private TokenStore tokenStore;

@Autowired
@Qualifier("userDetailsService")
private UserDetailsServiceImpl userDetailsService;

@Autowired
private AuthenticationManager authenticationManager;

@Autowired
private BCryptPasswordEncoder bCryptPasswordEncoder;

@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients
.inMemory()
.withClient(clientId)
.secret(bCryptPasswordEncoder.encode(clientSecret))
.authorizedGrantTypes("password", "authorization_code", "refresh_token")
.autoApprove(true)
.scopes("read", "write", "trust")
.accessTokenValiditySeconds(accessTokenValidity)
.refreshTokenValiditySeconds(refreshTokenValidity);
}

@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints
.tokenStore(tokenStore)
.userDetailsService(userDetailsService)
.authenticationManager(authenticationManager);
}

@Override
public void configure(AuthorizationServerSecurityConfigurer auth) throws Exception {
auth
.tokenKeyAccess("permitAll()")
.checkTokenAccess("isAuthenticated()");
}

@Bean
public TokenStore tokenStore() {
return new InMemoryTokenStore();
}

}

最佳答案

我自己找到了答案。 WebSecurityConfigurerAdapter.configure 应该具有登录页面、错误页面等身份验证配置。至于 ResourceServerConfigurerAdapter.configure,它应用有关 REST API 的规则。

WebSecurityConfigurerAdapter 对我不起作用的原因是因为 WebSecurityConfigurerAdapter 和 ResourceServerConfigurerAdapter 配置是链接的。还记得他们的订单吗?身份验证服务器 -> 资源服务器 -> 网络安全。就我而言,我在 ResourceServerConfigurerAdapter.configure 中有 .anyRequest().authenticated() ,它基本上对之后的所有请求进行了身份验证,因此它根本无法到达 WebSecurityConfigurerAdapter。

我还在 ResourceServerConfigurerAdapter.configure 中添加了 .antMatcher("/api/users**") ,以将该规则限制为仅适用于 /api/users

这是“损坏的代码”:

// WebSecurityConfigurerAdapter
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/api/topics/**").permitAll()
.antMatchers("/api/users/**").permitAll()
.antMatchers("/oauth/token**", "/oauth/authorize**").permitAll()
.anyRequest().authenticated()
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}

// ResourceServerConfigurerAdapter
@Override
public void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/api/**").permitAll()
.anyRequest().authenticated();
}

这是一个工作示例:

// WebSecurityConfigurerAdapter
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/oauth2/keys").permitAll()
.anyRequest().authenticated();
}

// ResourceServerConfigurerAdapter
@Override
public void configure(HttpSecurity http) throws Exception {
http
.antMatcher("/api/users**") // that particular line applies the rule only for /api/users
.authorizeRequests()
.antMatchers("/api/users**").permitAll();
}

关于java - OAuth2 WebSecurityConfigurerAdapter 规则的意义是什么,因为它没有比 ResourceServerConfigurerAdapter 更高的优先级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61154266/

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