gpt4 book ai didi

java - Spring Security - @PreAuthorize 返回 404

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:47:27 25 4
gpt4 key购买 nike

我在使用 Spring Method Security 时遇到了一个奇怪的问题,@PreAuthorize("hasRole('MODERATOR')")

如果用户尝试访问需要“MODERATOR”角色的 Controller ,则资源将返回,一切正常(如果用户实际上具有该角色)。但是,如果用户没有这个角色,服务器返回 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;
}

}

和我的 Controller :

@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;
}
}

谢谢!

最佳答案

全局方法安全性可以在注解 @EnableGlobalMethodSecurity(prePostEnabled=true) 的帮助下启用。这个和 @Preauthorize 的组合将为您的 Controller 创建一个新的代理,它将松开请求映射(在您的情况下为 GetMapping),这将导致 404 异常。

要处理此问题,您可以使用 @EnableGlobalMethodSecurity(prePostEnabled = true, proxyTargetClass = true)

Annotated Controllers in Spring documentation

A related Github Issue

关于java - Spring Security - @PreAuthorize 返回 404,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50429124/

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