【问题标题】:Spring Authentication, how to customize responeText for bad credentialSpring Authentication,如何为坏凭证自定义responeText
【发布时间】:2019-05-05 18:55:07
【问题描述】:

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"}

相反,我想要具体的错误:“用户未激活。”或“找不到用户"

我怎样才能达到这个结果?

【问题讨论】:

  • 只是一个意见:您应该返回“错误的凭据”或更好的“用户和密码的错误组合”。不要暴露用户未找到或未激活的信息。您可以将其用于日志记录,但最终用户应该不知道他是否尝试为现有用户进行组合...

标签: java spring authentication


【解决方案1】:

正如在这篇博文中看到的,您必须配置一个 MessageSource Bean。您可以配置此 bean 以根据需要提供消息。常见的方法是拥有一个包含消息的属性文件。

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

请关注博文Configure Error Message 深入了解该主题

【讨论】:

    【解决方案2】:

    您可以覆盖 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

    【讨论】:

      猜你喜欢
      • 2016-09-12
      • 1970-01-01
      • 2022-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-02
      • 2020-03-31
      • 2012-07-15
      相关资源
      最近更新 更多