如何从Spring Boot ldap处理和自定义错误401?

时间:2018-10-23 20:20:18

标签: java spring-security spring-ldap

我正在使用使用Spring secutiry LDAP对其用户进行身份验证的应用程序,身份验证工作正常,我的问题是,如果有人尝试使用未经授权的凭据登录,则该应用程序会立即发送错误401,而我不想那样,我想自定义一些友好的消息来显示该用户,但是即使在调试中,我也找不到应用程序在哪里执行取消身份验证,甚至似乎没有调用我的后端,我如何自定义此例外?

这是我在“安全性”配置类上的配置:

@Configuration
@Order(2147483640)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

protected void configure(HttpSecurity http) throws Exception {
    http.httpBasic().and()
            .cors().and()
            .csrf().disable()
            .authorizeRequests()
            .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
            .antMatchers(HttpMethod.GET, "/**").permitAll()
            .antMatchers(HttpMethod.POST, "/**").permitAll()
            .antMatchers(HttpMethod.PUT, "/**").permitAll()
            .antMatchers(HttpMethod.DELETE, "/**").permitAll()
            .antMatchers("/**").permitAll();
}

@Configuration
protected static class AuthenticationConfiguration extends GlobalAuthenticationConfigurerAdapter {

    @Autowired
    private UsrPessoaService usrPessoaService;

    @Override
    public void init(AuthenticationManagerBuilder auth) throws Exception {
        auth.ldapAuthentication().userDetailsContextMapper(usrPessoaService)
                .userDnPatterns("secret")
                .groupSearchBase("secret")
                .contextSource()
                .root("secret")
                .url("secret").port(000);

        System.out.println(auth.toString());
    }
}

}

在此先感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

您是否考虑过WhiteLabel Page

例如:

https://www.baeldung.com/spring-boot-custom-error-page

@RequestMapping("/error")
public String handleError(HttpServletRequest request) {
    Object status = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);

    if (status != null) {
        Integer statusCode = Integer.valueOf(status.toString());

        if(statusCode == HttpStatus.NOT_FOUND.value()) {
            return "error-404";
        }
        else if(statusCode == HttpStatus.INTERNAL_SERVER_ERROR.value()) {
            return "error-500";
        }
    }
    return "error";
}

还有一个示例“ error.html”模板:

<!DOCTYPE html>
<html>
<body>
<h1>Page not found</h1>
<h2>Sorry, we couldn't find the page you were looking for</h2>
<a href="/">Go Home</a>
</body>
</html>

附录:

由于OP具有Angular前端,因此这些链接也可能适用:

  

Tutorial: Spring Security and Angular

     

在本教程中,我们展示了Spring Security,Spring的一些不错的功能   Boot和Angular共同提供舒适安全的环境   用户体验。

     

Spring和Angular的初学者应该可以使用它,但是   还有很多细节将对   要么。

另请参阅:

https://github.com/spring-projects/spring-security/blob/master/web/src/main/java/org/springframework/security/web/AuthenticationEntryPoint.java