问题
I implemented the UserDetailsService
interface and override the loadUserByUsername
method.
I thought that, inside loadUserByUsername
, I could get username and password, to check if they match username and password on the DB. But I can't understand how to get the password typed by the user, provided that it is possibile.
Probably, I'm implementing the wrong interface.
Is UserDetailsService
enough to do what I want to or I have to implement or extend something else?
回答1:
The UserDetailsService.loadUserByUsername() is just to load (retrieve) the user details from the database - it isn't to do the password comparison.
The comparison happens in UsernamePasswordAuthenticationFilter.attemptAuthentication(). Then it calls to getAuthenticationManager().authenticate(), where the comparison occurs.
See this: What is the default AuthenticationManager in Spring-Security? How does it authenticate?
As for replacing UsernamePasswordAuthenticationFilter
, ask yourself what is your use case? what are you trying to do that the default implementation does not? maybe you do not have to replace it... anyways, you can see how to do it in Spring's docs
HTH
回答2:
The UserDetailsService
is just to retrieve the user details from the database - it isn't to do the password comparison.
If you want to do your own password comparison - you can implement your own PasswordEncoder
(more specifically the isPasswordValid(pass1,pass2,salt)
method but there are several you could extend - for example Md5PasswordEncoder
To wire your custom PassordEncoder
you'll need something along the lines of this:
<authentication-manager id="authenticationManager">
<authentication-provider user-service-ref="myUserDetailsService">
<password-encoder ref="myPasswordEncoder"/>
</authentication-provider>
</authentication-manager>
来源:https://stackoverflow.com/questions/26607203/how-to-perform-my-own-authentication-checking-username-and-password-typed-by-th