Spring身份验证,如何为不良凭据自定义responeText

时间:2018-12-04 10:57:33

标签: java spring authentication

Mu身份验证服务是

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    UserRepository userRepository;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException, ResourceNotFoundException {

        Optional<User> optionalUser = userRepository.findByUsername(s);

        if (optionalUser.isPresent()) {

            User user = optionalUser.get();
            if (!user.isActive()) {
                throw new UsernameNotFoundException("User is not active.");
            }

            List<SimpleGrantedAuthority> grantedAuthorities = new ArrayList<>();
            grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_USER"));

            if (user.isKeyUser()) grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_KEYUSER"));
            if (user.isAdmin()) grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));

            UserDetails userDetails = new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), grantedAuthorities);
            return userDetails;
        }
        else {
            throw new UsernameNotFoundException("User not found");
        }

    }
}

但是,当我尝试使用错误的凭据登录或用户未激活时,会收到此通用错误(我正在使用React + Axios):

data: {error: "invalid_grant", error_description: "Bad credentials"}

相反,我希望收到特定错误:“ 用户未处于活动状态。 ”或“ 未找到用户 < / strong>”

如何获得此结果?

2 个答案:

答案 0 :(得分:1)

如本博文所述,您必须配置MessageSource Bean。您可以配置该bean以根据需要提供Messages。常见的方法是拥有一个包含消息的属性文件。

 @Bean
public MessageSource messageSource() {
    ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
    messageSource.addBasenames("classpath:org/springframework/security/messages");
    return messageSource;
}

请关注博客文章Configure Error Message,以更深入地了解该主题

答案 1 :(得分:0)

您可以覆盖spring-security-core.jar的message属性。为此, 创建消息属性文件,并为此添加键和值对,

AbstractUserDetailsAuthenticationProvider.badCredentials =无效的用户名或密码

和 然后

只需将以下代码添加到xml配置中

<bean id="messageSource"
    class="org.springframework.context.support.ResourceBundleMessageSource">
    <property name="basenames">
        <list>
        <value>mymessages</value>
        </list>
    </property>
  </bean>

这样,您可以覆盖spring-framework的多个默认属性

您可以参考以下站点以获取详细信息,

https://www.mkyong.com/spring-security/display-custom-error-message-in-spring-security/

Spring security custom AuthenticationException message