java - 验证方法应该返回 null 还是 AuthentificationException?

标签 java spring authentication spring-security

我有自己的 spring srcurity auth 提供程序:

public class MyLdapAuthProvider implements AuthenticationProvider

   @Override
   public Authentication authenticate(Authentication authentication) throws AuthenticationException {
          if(goodCredetials()){
             return authenticateUserPassword((UsernamePasswordAuthenticationToken) authentication);
           } else {
              throw new BadCredentialsException("bad credentials");
          }
    }

如果我知道凭据错误,我不明白应该返回什么
1 - 抛出AuthenticationException
2 - 返回 null

我已经测试过了,没有发现差异

附注

Spring 安全配置:

<security:authentication-manager>
    <security:authentication-provider ref="provider1"/>
    <security:authentication-provider user-service-ref="provider2"/>
</security:authentication-manager>

附注

文档:

Authentication authenticate(Authentication authentication) throws AuthenticationException Performs authentication with the same contract as AuthenticationManager.authenticate(Authentication). Parameters: authentication - the authentication request object. Returns: a fully authenticated object including credentials. May return null if the AuthenticationProvider is unable to support authentication of the passed Authentication object. In such a case, the next AuthenticationProvider that supports the presented Authentication class will be tried. Throws: AuthenticationException - if authentication fails.

最佳答案

阅读doc 。如果返回 null,则告诉 spring 您不能支持此身份验证方法,它应该尝试下一个提供程序(如果有)。

我的猜测是,如果你抛出,你就会打破尝试不同提供商的链条。只要您有一个 authProvider 而不是它们的集合,就不会有太大区别。

此外,在身份验证失败时,您应该抛出 AuthenticationException,而不是 BadCredentials?

关于java - 验证方法应该返回 null 还是 AuthentificationException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36156059/

相关文章:

c# - 网站登录和抓取 HTML

java - 在java中读取unicode txt

Java多线程在不工作的输出文件锁定中混合文本

java - 有一个通用的 Spring ApplicationContextProvider 供所有 spring 管理的 bean 和其他 bean 使用

java - 在Jetty服务器中如何获取需要客户端认证时使用的客户端证书?

objective-c - iOS 应用程序和持久登录(显然是特定于手机和特定于应用程序的问题)

java - 检查一个列表的元素是否存在于另一个列表中

java - 如何在 Vaadin 14 Web 应用程序中发生 View 类实例化之前拦截检查授权的请求?

java - 由 : org. hibernate.TransientObjectException : The given object has a null identifier: com. models.User on hibernate update 引起

java - Spring RequestMapping 正则表达式排除字符串