Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/395.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Spring Security-@PreAuthorize返回404_Java_Spring_Security - Fatal编程技术网

Java Spring Security-@PreAuthorize返回404

Java Spring Security-@PreAuthorize返回404,java,spring,security,Java,Spring,Security,我目前在使用Spring方法安全性时遇到了一个奇怪的问题,@PreAuthorize(“hasRole('MODERATOR')”) 如果用户试图访问需要“主持人”角色的控制器,则返回资源,一切正常(如果用户实际上具有该角色)。但是,如果用户没有此角色,服务器将返回404-未找到。这很奇怪,因为我希望服务器会返回其他内容,可能是403禁止?知道为什么会发生这种情况吗?这是我的安全配置: @EnableWebSecurity @Order(2) public class WebSecurity e

我目前在使用Spring方法安全性时遇到了一个奇怪的问题,
@PreAuthorize(“hasRole('MODERATOR')”)

如果用户试图访问需要“主持人”角色的控制器,则返回资源,一切正常(如果用户实际上具有该角色)。但是,如果用户没有此角色,服务器将返回404-未找到。这很奇怪,因为我希望服务器会返回其他内容,可能是403禁止?知道为什么会发生这种情况吗?这是我的安全配置:

@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;
    }
}
@GetMapping
@预授权(“hasRole(‘主持人’)”)
公共列表getAllUsers(HttpServletRequest请求){
try(final ConnectionResource ConnectionResource=connectionFactory.create();final UserDAO=new UserDAO()){
setEm(connectionResource.em);
返回dao.getAllUsers();
}捕获(例外情况除外){
Logger.getLogger(UserController.class.getName()).log(Level.SEVERE,“无法获取所有用户”,例如);
返回null;
}
}

谢谢!下面是我的代码:-

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

}我们需要为使用@PreAuthorize注释启用全局方法安全性


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

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


您是否验证了它不是“真正的404”?(例如,通过删除安全性和“浏览”相同的资源/url)是的。没有预授权,资源端点被找到…我发现..并假设一些错误配置:1.supsect:
cors()
未被记录为与
antMatcher()一起使用。
(而是使用
registerCorsConfiguration
函数的参数)…实际上:如何进行身份验证?
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled=true)
@Order(2)
public class WebSecurity extends WebSecurityConfigurerAdapter {
..............
}