Spring Security - @PreAuthorize 返回 404

Dav*_*sta 6 java security spring

当我使用 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;
    }      

}
Run Code Online (Sandbox Code Playgroud)

和我的控制器:

@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;
    }
}
Run Code Online (Sandbox Code Playgroud)

谢谢你!

Jaz*_*eer 5

可以借助注释来启用全局方法安全性@EnableGlobalMethodSecurity(prePostEnabled=true)。这两者的结合@Preauthorize将为您的控制器创建一个新的代理,并且它将丢失请求映射(在您的情况下为 GetMapping),这将导致 404 异常。

要处理这个问题,你可以使用@EnableGlobalMethodSecurity(prePostEnabled = true, proxyTargetClass = true)

Spring 文档中带注释的控制器

相关的 Github 问题


Art*_*Art 0

下面是我执行此操作的代码:-

 @Override
protected void configure(HttpSecurity http) throws Exception{
    http.authorizeRequests()
    .antMatchers(HttpMethod.POST,"/api/2.0/login/**").permitAll()
    .anyRequest().authenticated()
    .and().exceptionHandling().authenticationEntryPoint(unauthorizedEntryPoint())
    .and()  
    .addFilterBefore()
}


@Bean
public AuthenticationEntryPoint unauthorizedEntryPoint() {
    return new RestAuthenticationEntryPoint();
}


public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint{
private static Logger logger = Logger.getLogger(RestAuthenticationEntryPoint.class);

public RestAuthenticationEntryPoint() {
    super();
}

@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
        AuthenticationException authException) throws IOException, ServletException {
    logger.info("Inside Rest Authentication entry Points");
    String error="{ \"status\":\"FAILURE\",\"error\":{\"code\":\"401\",\"message\":\""+authException.getMessage()+"\"} }";
    HttpServletResponse httpResponse = (HttpServletResponse) response;
    httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    httpResponse.setContentType("application/json");

    if(authException instanceof BadCredentialsException){
        httpResponse.getOutputStream().println("{ \"Bad credential\": \"" + authException.getMessage() + "\" }");
    }
    if(authException instanceof AuthenticationCredentialsNotFoundException){
        logger.info("Inside AuthenticationCredentialsNotFoundException");
        error="{ \"status\":\"FAILURE\",\"error\":{\"code\":\""+SecurityExceptions.TOKEN_EXPIRED+"\",\"message\":\""+SecurityExceptions.TOKEN_EXPIRED_MESSAGE+"\"} }";
    }
    httpResponse.getOutputStream().println(error);
}
Run Code Online (Sandbox Code Playgroud)

}