【发布时间】:2021-02-24 17:47:34
【问题描述】:
我遇到了这个项目,以解决服务器响应 401 未授权 OPTIONS 请求的问题。
我查看了项目(这是一个捆绑为耳朵而不是引导的 Spring 5 项目)发现有一个 CORS 过滤器。然后我查看了安全配置,发现有两个。
//@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private CustomUserDetailsService customUserDetailsService;
@Bean
public CustomDaoAuthenticationProvider authenticationProvier() {
CustomDaoAuthenticationProvider customProvider = new CustomDaoAuthenticationProvider();
customProvider.setUserDetailsService(customUserDetailsService);
customProvider.setPasswordEncoder(passwordEncoder());
return customProvider;
}
@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authenticationProvier());
}
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Override
protected void configure(final HttpSecurity http) throws Exception {
http
.cors()
.and()
.csrf().disable()
.anonymous().disable()
.authorizeRequests()
.antMatchers("/**").permitAll();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder(10);
}
}
第二个是
@Configuration
@EnableResourceServer
@EnableWebSecurity
public class OAuth2ResourceServerConfig extends ResourceServerConfigurerAdapter {
@Override
public void configure(final HttpSecurity http) throws Exception {
http.anonymous().disable().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.csrf().disable().authorizeRequests()
.antMatchers(HttpMethod.GET, "/somepath/**").access("#oauth2.hasScope('some_scope') "
+ "and hasAnyRole('role_1','r')")
....
.anyRequest().authenticated();
}
@Override
public void configure(final ResourceServerSecurityConfigurer config) {
config.tokenServices(tokenServices());
}
@Bean
public TokenStore tokenStore() {
return new JwtTokenStore(accessTokenConverter());
}
@Bean
public JwtAccessTokenConverter accessTokenConverter() {
final JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
ClassPathResource resource = new ClassPathResource("id_rsa.pub");
String publicKey = null;
try {
publicKey = new String(FileCopyUtils.copyToByteArray(resource.getInputStream()));
} catch (IOException e) {
throw new RuntimeException(e);
}
converter.setVerifierKey(publicKey);
return converter;
}
@Bean
@Primary
public DefaultTokenServices tokenServices() {
final DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
defaultTokenServices.setTokenStore(tokenStore());
return defaultTokenServices;
}
}
在阅读了与此相关的问题后,我认为 OAuth2ResourceServerConfig 优先于 WebSecurityConfig(问题 here)。
那么在当前集合中是否同时检查令牌和密码? 如果我增加 WebSecurityConfig 的优先级,它将解决问题。如果我在这里误解了任何内容,请为我解决。
【问题讨论】:
标签: spring rest spring-security spring-oauth2