简体   繁体   English

Spring Boot:accessDeniedHandler 不起作用

[英]Spring Boot: accessDeniedHandler does not work

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 .我期望以下逻辑:未通过身份验证的用户将被重定向到/403 Instead of that Spring displays a default Tomcat 403 page.而不是 Spring 显示默认的 Tomcat 403 页面。 I also tried custom accessDeniedHandler withough any success.我也尝试过自定义accessDeniedHandler但没有成功。

How can I implement custom logic on access failure?如何在访问失败时实现自定义逻辑?

The AccessDeniedHandler only applies to authenticated users. AccessDeniedHandler 仅适用于经过身份验证的用户。 The default behaviour for unauthenticated users is to redirect to the login page (or whatever is appropriate for the authentication mechanism in use).未经身份验证的用户的默认行为是重定向到登录页面(或任何适用于正在使用的身份验证机制的页面)。

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.如果你想改变你需要配置一个AuthenticationEntryPoint ,当未经AuthenticationEntryPoint验证的用户尝试访问受保护的资源时调用它。 You should be able to use你应该可以使用

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

instead of what you have.而不是你所拥有的。 For more details, check the API docs .有关更多详细信息,请查看API 文档

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.希望这可以帮助。

The normal Spring Security behavior is to redirect unauthenticated users to your login page as configured below.正常的 Spring Security 行为是将未经身份验证的用户重定向到您的登录页面,如下所示。 Authenticates users who are not authorized (dont have the ADMIN role) will be directed to the access denied page:验证未经授权(没有 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");

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 页面

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM