java Spring Boot:accessDeniedHandler 不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28057592/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 12:56:56  来源:igfitidea点击:

Spring Boot: accessDeniedHandler does not work

javaspringspring-securityspring-boot

提问by fedor.belov

I've got the following Spring Security configuration:

我有以下 Spring Security 配置:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/api/private/**", "/app/**").authenticated();
        http.csrf().disable();
        http.logout().logoutSuccessUrl("/");
        http.exceptionHandling().accessDeniedPage("/403"); //.accessDeniedHandler(accessDeniedHandler);
    }
}

I expect the following logic: not authenticated users will be redirected to /403. Instead of that Spring displays a default Tomcat 403 page. I also tried custom accessDeniedHandlerwithough any success.

我期望以下逻辑:未通过身份验证的用户将被重定向到/403. 而不是 Spring 显示默认的 Tomcat 403 页面。我也尝试过自定义,accessDeniedHandler但没有成功。

How can I implement custom logic on access failure?

如何在访问失败时实现自定义逻辑?

回答by Shaun the Sheep

The AccessDeniedHandler only applies to authenticated users. The default behaviour for unauthenticated users is to redirect to the login page (or whatever is appropriate for the authentication mechanism in use).

AccessDeniedHandler 仅适用于经过身份验证的用户。未经身份验证的用户的默认行为是重定向到登录页面(或任何适用于正在使用的身份验证机制的页面)。

If you want to change that you need to configure an AuthenticationEntryPoint, which is invoked when an unauthenticated user attempts to access a protected resource. You should be able to use

如果您想更改它,您需要配置一个AuthenticationEntryPoint,当未经身份验证的用户尝试访问受保护资源时会调用它。你应该可以使用

http.exceptionHandling().authenticationEntryPoint(...)

instead of what you have. For more details, check the API docs.

而不是你所拥有的。有关更多详细信息,请查看API 文档

回答by GMsoF

Come across this question, it helped me solve my problem, below is my code:

遇到这个问题,它帮助我解决了我的问题,下面是我的代码:

public class CustomHttp403ForbiddenEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
            AuthenticationException authException) throws IOException, ServletException {
        response.getWriter().print("You need to login first in order to perform this action.");
    }

}


public class CustomAccessDeniedHandler implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException arg2)
            throws IOException, ServletException {
        response.getWriter().print("You don't have required role to perform this action.");
    }

}


@Override
protected void configure(HttpSecurity http) throws Exception {

    http.exceptionHandling().accessDeniedHandler(new CustomAccessDeniedHandler()).and()
        .exceptionHandling().authenticationEntryPoint(new CustomHttp403ForbiddenEntryPoint());
}

Hope this helps.

希望这可以帮助。

回答by Jaffadog

The normal Spring Security behavior is to redirect unauthenticated users to your login page as configured below. Authenticates users who are not authorized (dont have the ADMIN role) will be directed to the access denied page:

正常的 Spring Security 行为是将未经身份验证的用户重定向到您的登录页面,如下配置。验证未经授权(没有 ADMIN 角色)的用户将被定向到访问被拒绝页面:

http.authorizeRequests().antMatchers("/admin/**")
    .access("hasRole('ADMIN')")
    .and().formLogin().loginPage("/login")
    .and().exceptionHandling().accessDeniedPage("/403");

If you have implemented your own authentication mechanism and you are not counting on the Spring Security configuration to deliver unauthenticated users to your login page, you can game the Spring Security configuration as follows - to serve your custom 403 page instead of a real login page:

如果您已经实现了自己的身份验证机制,并且不指望 Spring Security 配置将未经身份验证的用户传送到您的登录页面,则可以按如下方式使用 Spring Security 配置 - 为您的自定义 403 页面提供服务,而不是真正的登录页面:

http.authorizeRequests().antMatchers("/admin/**")
    .access("hasRole('ADMIN')")
    .and().formLogin().loginPage("/403")
    .and().exceptionHandling().accessDeniedPage("/403");

回答by Sachin Kumar

Use this:-

用这个:-

@Configuration
public class ViewRegistryConfig implements WebMvcConfigurer {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/403").setViewName("notAuth");
    }

}

and create notAuth.html page in your template folder

并在您的模板文件夹中创建 notAuth.html 页面