正确处理基本身份验证中拒绝的访问

时间:2017-03-26 16:32:26

标签: spring spring-boot spring-security

我有一个非常正常的弹簧安全设置(使用spring boot),其中所有表单登录都使用基于ajax的方法(没有重定向等),这适用于表单登录。

对于基本身份验证,我现在也想正确处理失败的登录尝试,这里似乎存在一些问题:我不能再依赖ControllerAdvice来捕获异常,这很好,我试过了自定义BasicAuthenticationEntryPoint进行一些更改...但我可以做的就是更改实际抛出的异常..它仍然没有被我的控制器建议捕获。

所以我想知道,我知道spring spring在spring mvc / advice world之外工作,那么如何捕获并更改发送给用户的默认消息呢? (对于基本身份验证,对于表单/会话,这已经正常工作..)

1 个答案:

答案 0 :(得分:1)

您可以通过实现接口AuthenticationEntryPoint来创建处理身份验证例外的自定义身份验证入口点

@Component
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint, Serializable {

    public void commence(HttpServletRequest request,
                     HttpServletResponse response,
                     AuthenticationException e) throws IOException {

        // handle the authentication exception
        // you can return json with Jackson and 
        // write it to the HttpServletResponse.
    }
}

然后,您可以将其自动装入您的安全配置类,并使用.exceptionHandling()

将异常处理添加到HttpSecurity
@Autowired
private CustomAuthenticationEntryPoint unauthorizedHandler;

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .exceptionHandling() 
            .authenticationEntryPoint(unauthorizedHandler);
            // ... the rest of your configuration.
}

您也可以在这篇文章中找到我的详细信息。

Customize authentication failure response in Spring Security using AuthenticationFailureHandler

HttpSecurity doc

http://docs.spring.io/spring-security/site/docs/current/apidocs/org/springframework/security/config/annotation/web/builders/HttpSecurity.html

编辑:

处理AuthenticationException将处理无效凭证。

处理AccessDeniedException可处理方法级安全性,例如为特定角色或权限保护方法。