Spring Security Authenticationprovider authenticate()'返回null的原因

Spring Security Authentication Provider autenticate()'s reason for returning null

最近在研究Spring security的Authentication provider

在 authenticate() 方法中,文档说,“如果 AuthenticationProvider 无法支持对传递的 Authentication 对象的身份验证,则可能 return null。在这样的情况下在这种情况下,将尝试下一个支持当前身份验证 class 的 AuthenticationProvider。"

我们有另一种方法 supports() 指示此提供程序是否支持身份验证类型。

据我所知"AuthenticationManager"首先调用supports()检查提供者是否支持这种类型。然后调用 authenticate() 方法。因此,根据我的理解,只有在提供者支持时才会调用 authenticate。

所以,我的问题是“如果提供者支持这种类型的身份验证,那么为什么它 return null from authenticating ()?为什么文档说 "May return null if the AuthenticationProvider is unable to support authentication of the passed Authentication object" ??? 它不应该总是支持它吗?(因为我们检查了它的兼容性通过支持().)

您能否举例说明提供商需要 return null?

提前致谢。

引自 Spring Security in Action 作者 Laurentiu Spilca

The second method in the AuthenticationProvider interface is supports- (Class<?> authentication). You can implement this method to return true if the current AuthenticationProvider supports the type provided as an Authentication object. Observe that even if this method returns true for an object, there is still a chance that the authenticate() method rejects the request by returning null. Spring Security is designed like this to be more flexible and to allow you to implement an AuthenticationProvider that can reject an authentication request based on the request’s details, not only by its type.

和它的比喻我想清楚了。

An analogy of how the authentication manager and authentication provider work together to validate or invalidate an authentication request is having a more complex lock for your door. You can open this lock either by using a card or an old fashioned physical key . The lock itself is the authentication manager that decides whether to open the door. To make that decision, it delegates to the two authentication providers: one that knows how to validate the card or the other that knows how to verify the physical key. If you present a card to open the door, the authentication provider that works only with physical keys complains that it doesn’t know this kind of authentication. But the other provider supports this kind of authentication and verifies whether the card is valid for the door. This is actually the purpose of the supports() methods. Besides testing the authentication type, Spring Security adds one more layer for flexibility. The door’s lock can recognize multiple kinds of cards. In this case, when you present a card, one of the authentication providers could say, “I understand this as being a card. But it isn’t the type of card I can validate!” This happens when supports() returns true but authenticate() returns null.