【发布时间】:2020-08-23 23:53:54
【问题描述】:
我目前在使用 Spring Method Security 时遇到了一个奇怪的问题,@PreAuthorize("hasRole('MODERATOR')")
如果用户尝试访问需要“MODERATOR”角色的控制器,则返回资源,一切正常(如果用户实际上具有该角色)。但是,如果用户没有这个角色,服务器会返回 404 - Not Found。这很奇怪,因为我预计服务器会返回其他内容,也许是 403 Forbidden?知道为什么会发生这种情况吗?这是我的安全配置:
@EnableWebSecurity
@Order(2)
public class WebSecurity extends WebSecurityConfigurerAdapter {
private final UserDetailsService userDetailsService;
private final BCryptPasswordEncoder bCryptPasswordEncoder;
public WebSecurity(UserDetailsService userDetailsService, BCryptPasswordEncoder bCryptPasswordEncoder) {
super();
this.userDetailsService = userDetailsService;
this.bCryptPasswordEncoder = bCryptPasswordEncoder;
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.antMatcher("/api/**")
.cors()
.and()
.csrf().disable()
.authorizeRequests()
.antMatchers("/**").permitAll()
.anyRequest().authenticated()
.and()
.addFilter(new JWTAuthenticationFilter(authenticationManager()))
.addFilter(new JWTAuthorizationFilter(authenticationManager()))
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder);
}
@Bean
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.applyPermitDefaultValues();
configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
}
和我的控制器:
@GetMapping
@PreAuthorize("hasRole('MODERATOR')")
public List<ApplicationUser> getAllUsers(HttpServletRequest request) {
try (final ConnectionResource connectionResource = connectionFactory.create(); final UserDAO dao = new UserDAO()) {
dao.setEm(connectionResource.em);
return dao.getAllUsers();
} catch (Exception ex) {
Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, "unable to get all users", ex);
return null;
}
}
谢谢!
【问题讨论】:
-
您确认它不是“真正的 404”吗? (例如,通过放弃安全性并“浏览”same 资源/url)
-
是的。如果没有 PreAuthorize,则会找到资源端点。
-
..我发现this ..并假设一些错误配置: 1. 怀疑:
cors()没有记录与antMatcher()一起使用(而是使用registerCorsConfiguration的参数功能)..实际上:您如何进行身份验证?