在 spring security 中使用自定义的错误消息

51 篇文章 0 订阅
在使用 spring security 的过程中, 当认证失败的时候,会提示这样的错误: "Bad credentials", 但实际上我们需要显示这样的消息:"错误的用户名或密码", 有什么办法解决呢, 我知道的至少有两种方法.

第一种方法, 直接替换 spring security 自身的message properties.
spirng security 会将默认的消息存在 spring-security-core.jar 包中。如下图所示:


到这里,应该知道怎么解决了吧,这种方式比较暴力,就是找到错误消息的key, 用自己需要显示的消息重新定义它。

第二种方法, 自定义properties 方式 覆盖 spring security 的 key 和消息
在classpath 下 创建一个新的properties 文件,用自己需要显示的消息,重写 spirng security的key. 比如:
AbstractUserDetailsAuthenticationProvider.badCredentials=Invalid username or password


定义的properties文件之后,  当然需要注册到spring 容器之中, 所以还需要配置:
    
        
        mymessages
        
    
  


通过这种方式,就能用自定义的消息取代 spring security 默认的消息了,其实还是非常方便的。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Security 可以通过实现 AuthenticationFailureHandler 接口来自定义认证错误处理。具体步骤如下: 1. 创建一个类,实现 AuthenticationFailureHandler 接口。 2. 在类实现 onAuthenticationFailure 方法,该方法接收三个参数:HttpServletRequest、HttpServletResponse 和 AuthenticationException。 3. 在 onAuthenticationFailure 方法,可以根据 AuthenticationException 的类型来判断认证失败的原因,并根据需要进行处理。 4. 最后,将自定义的认证错误处理器配置到 Spring Security 。 示例代码如下: ``` public class CustomAuthenticationFailureHandler implements AuthenticationFailureHandler { @Override public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException { if (exception instanceof BadCredentialsException) { // 处理用户名或密码错误的情况 response.sendRedirect("/login?error=bad_credentials"); } else if (exception instanceof DisabledException) { // 处理账号被禁用的情况 response.sendRedirect("/login?error=disabled"); } else { // 处理其他认证失败的情况 response.sendRedirect("/login?error=unknown"); } } } ``` 配置自定义认证错误处理器的代码如下: ``` @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private CustomAuthenticationFailureHandler customAuthenticationFailureHandler; @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/login").permitAll() .anyRequest().authenticated() .and() .formLogin() .loginPage("/login") .failureHandler(customAuthenticationFailureHandler) .and() .logout() .logoutUrl("/logout") .logoutSuccessUrl("/login?logout") .and() .csrf().disable(); } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值