如何修改Spring Security登录中的Bad credentials错误提示信息?
问题描述
使用Spring Boot 3.0.6版本,已配置如下SecurityFilterChain:
public SecurityFilterChain applicationSecurityFilterChain(HttpSecurity http) throws Exception { http.anonymous().disable(); http.cors().and().authorizeHttpRequests().permitAll(); http .authorizeHttpRequests(authorize -> authorize // .requestMatchers(HttpMethod.POST, "/user/**").permitAll() .anyRequest().authenticated()) // Form login handles the redirect to the login page from the // authorization server filter chain .formLogin(Customizer.withDefaults()); http.csrf().disable(); return http.build(); }
同时在src/main/resource目录下添加了messages_en.properties文件:
message.badCredentials=Invalid user name and password
但登录时仍收到原"Bad credentials"错误提示,请问该如何解决?
解决方法
- 修正消息键名称
Spring Security的默认身份验证错误消息使用自身定义的键,而非你自定义的message.badCredentials。针对"Bad credentials"错误,对应的默认键是AbstractUserDetailsAuthenticationProvider.badCredentials。修改messages_en.properties内容为:
AbstractUserDetailsAuthenticationProvider.badCredentials=Invalid user name and password
- 确保消息源被Spring Security正确加载
Spring Boot默认自动加载classpath下的messages_*.properties作为全局消息源,但如果项目中自定义了MessageSourceBean,需要确保它被Spring Security引用。可通过以下配置显式指定:
@Bean public MessageSource messageSource() { ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); messageSource.setBasename("messages"); messageSource.setDefaultEncoding("UTF-8"); return messageSource; } @Bean public LocaleResolver localeResolver() { SessionLocaleResolver localeResolver = new SessionLocaleResolver(); localeResolver.setDefaultLocale(Locale.ENGLISH); return localeResolver; }
- 自定义登录失败处理器(可选,更灵活)
如果需要完全控制错误消息的返回逻辑,可以自定义AuthenticationFailureHandler,在登录失败时直接返回自定义消息:
http.formLogin(form -> form .failureHandler((request, response, exception) -> { response.setContentType("application/json;charset=UTF-8"); String message = "Invalid user name and password"; if (exception instanceof BadCredentialsException) { message = "Invalid user name and password"; } response.getWriter().write(message); }) );
内容的提问来源于stack exchange,提问作者Thirumal
相关产品推荐
相关产品推荐

