首页 > 解决方案 > 如何处理和自定义来自 Spring Boot ldap 的错误 401?

问题描述

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

这是我的安全配置类的配置:

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

}

提前感谢您的帮助!

标签: javaspring-securityspring-ldap

解决方案


您是否考虑过WhiteLabel 页面

例如:

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 前端,这些链接也可能适用:

教程:Spring Security 和 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


推荐阅读