java - 如何处理和自定义来自 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());
}
}
}
提前感谢您的帮助!
解决方案
您是否考虑过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、Spring Boot 和 Angular 的一些不错的特性,它们协同工作以提供愉快和安全的用户体验。
Spring 和 Angular 的初学者应该可以使用它,但也有很多细节可供这两种方法的专家使用。
也可以看看:
推荐阅读
- java - Lombok @Builder 与 Java 8 Lambda Builder 模式
- javascript - 如何做到这一点:每次按下空格键后,创建一个新的 span 元素并将插入符号放在那里?
- sql - 更新行组以从行的总和中删除特定的总量 SQL
- c# - XML 批量更改类型十六进制
- model-view-controller - 在查找方法通用存储库中按全名或电子邮件查找?
- matlab - Reading rows of data till its end
- c - 线性搜索函数编译但没有输出
- python - 尝试对 PANDA 数据帧进行平均时出错
- azure-devops - 如何使用绝对路径引用文件夹构建 VSTS 项目?
- python - 无法在python中将字母数字转换为字符串