spring security登录自定义错误信息

首先,spring security的authentication-provider默认加载的是DaoAuthenticationProvider类。然后找到DaoAuthenticationProvider的父类AbstractUserDetailsAuthenticationProvider的authenticate方法,发现了这段代码。

try {
user = retrieveUser(username, (UsernamePasswordAuthenticationToken) authentication);
} catch (UsernameNotFoundException notFound) {
logger.debug("User '" + username + "' not found");

if (hideUserNotFoundExceptions) {
throw new BadCredentialsException(messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
} else {
throw notFound;
}
}


然后可以通过新建一个properties来覆盖spring security默认的错误信息,security.properties内容如下:
AbstractUserDetailsAuthenticationProvider.badCredentials=用户名或密码错误

再在bean里注入:
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basenames">
<list>
<value>security</value>
</list>
</property>
<property name="defaultEncoding" value="utf8" />
</bean>

最后在页面上就可以通过${SPRING_SECURITY_LAST_EXCEPTION.message}来获取错误信息
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 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、付费专栏及课程。

余额充值