UserNamePasswordAuthenticationProvider.java 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  1. package com.yihu.base.security.rbas.provider;
  2. import org.springframework.security.authentication.BadCredentialsException;
  3. import org.springframework.security.authentication.InternalAuthenticationServiceException;
  4. import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
  5. import org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider;
  6. import org.springframework.security.authentication.dao.SaltSource;
  7. import org.springframework.security.authentication.encoding.PasswordEncoder;
  8. import org.springframework.security.authentication.encoding.PlaintextPasswordEncoder;
  9. import org.springframework.security.core.AuthenticationException;
  10. import org.springframework.security.core.userdetails.UserDetails;
  11. import org.springframework.security.core.userdetails.UserDetailsService;
  12. import org.springframework.security.core.userdetails.UsernameNotFoundException;
  13. import org.springframework.util.Assert;
  14. /**
  15. * Created by 刘文彬 on 2018/6/1.
  16. */
  17. public class UserNamePasswordAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider {
  18. // ~ Static fields/initializers
  19. // =====================================================================================
  20. /**
  21. * The plaintext password used to perform
  22. * {@link PasswordEncoder#isPasswordValid(String, String, Object)} on when the user is
  23. * not found to avoid SEC-2056.
  24. */
  25. private static final String USER_NOT_FOUND_PASSWORD = "userNotFoundPassword";
  26. // ~ Instance fields
  27. // ================================================================================================
  28. private PasswordEncoder passwordEncoder;
  29. /**
  30. * The password used to perform
  31. * {@link PasswordEncoder#isPasswordValid(String, String, Object)} on when the user is
  32. * not found to avoid SEC-2056. This is necessary, because some
  33. * {@link PasswordEncoder} implementations will short circuit if the password is not
  34. * in a valid format.
  35. */
  36. private String userNotFoundEncodedPassword;
  37. private SaltSource saltSource;
  38. private UserDetailsService userDetailsService;
  39. public UserNamePasswordAuthenticationProvider() {
  40. setPasswordEncoder(new PlaintextPasswordEncoder());
  41. }
  42. // ~ Methods
  43. // ========================================================================================================
  44. @SuppressWarnings("deprecation")
  45. protected void additionalAuthenticationChecks(UserDetails userDetails,
  46. UsernamePasswordAuthenticationToken authentication)
  47. throws AuthenticationException {
  48. Object salt = null;
  49. if (this.saltSource != null) {
  50. salt = this.saltSource.getSalt(userDetails);
  51. }
  52. if (authentication.getCredentials() == null) {
  53. logger.debug("Authentication failed: no credentials provided");
  54. throw new BadCredentialsException(messages.getMessage(
  55. "AbstractUserDetailsAuthenticationProvider.badCredentials",
  56. "Bad credentials"));
  57. }
  58. String presentedPassword = authentication.getCredentials().toString();
  59. if (!passwordEncoder.isPasswordValid(userDetails.getPassword(),
  60. presentedPassword, salt)) {
  61. logger.debug("Authentication failed: password does not match stored value");
  62. throw new BadCredentialsException(messages.getMessage(
  63. "AbstractUserDetailsAuthenticationProvider.badCredentials",
  64. "Bad credentials"));
  65. }
  66. }
  67. protected void doAfterPropertiesSet() throws Exception {
  68. Assert.notNull(this.userDetailsService, "A UserDetailsService must be set");
  69. }
  70. protected final UserDetails retrieveUser(String username,
  71. UsernamePasswordAuthenticationToken authentication)
  72. throws UsernameNotFoundException {
  73. UserDetails loadedUser;
  74. try {
  75. loadedUser = this.getUserDetailsService().loadUserByUsername(username);
  76. }
  77. catch (UsernameNotFoundException notFound) {
  78. // if (authentication.getCredentials() != null) {
  79. // String presentedPassword = authentication.getCredentials().toString();
  80. // passwordEncoder.isPasswordValid(userNotFoundEncodedPassword,
  81. // presentedPassword, null);
  82. // }
  83. throw notFound;
  84. }
  85. catch (Exception repositoryProblem) {
  86. throw new InternalAuthenticationServiceException(
  87. repositoryProblem.getMessage(), repositoryProblem);
  88. }
  89. if (loadedUser == null) {
  90. throw new InternalAuthenticationServiceException(
  91. "UserDetailsService returned null, which is an interface contract violation");
  92. }
  93. return loadedUser;
  94. }
  95. /**
  96. * Sets the PasswordEncoder instance to be used to encode and validate passwords. If
  97. * not set, the password will be compared as plain text.
  98. * <p>
  99. * For systems which are already using salted password which are encoded with a
  100. * previous release, the encoder should be of type
  101. * {@code org.springframework.security.authentication.encoding.PasswordEncoder}.
  102. * Otherwise, the recommended approach is to use
  103. * {@code org.springframework.security.crypto.password.PasswordEncoder}.
  104. *
  105. * @param passwordEncoder must be an instance of one of the {@code PasswordEncoder}
  106. * types.
  107. */
  108. public void setPasswordEncoder(Object passwordEncoder) {
  109. Assert.notNull(passwordEncoder, "passwordEncoder cannot be null");
  110. if (passwordEncoder instanceof PasswordEncoder) {
  111. setPasswordEncoder((PasswordEncoder) passwordEncoder);
  112. return;
  113. }
  114. if (passwordEncoder instanceof org.springframework.security.crypto.password.PasswordEncoder) {
  115. final org.springframework.security.crypto.password.PasswordEncoder delegate = (org.springframework.security.crypto.password.PasswordEncoder) passwordEncoder;
  116. setPasswordEncoder(new PasswordEncoder() {
  117. public String encodePassword(String rawPass, Object salt) {
  118. checkSalt(salt);
  119. return delegate.encode(rawPass);
  120. }
  121. public boolean isPasswordValid(String encPass, String rawPass, Object salt) {
  122. checkSalt(salt);
  123. return delegate.matches(rawPass, encPass);
  124. }
  125. private void checkSalt(Object salt) {
  126. Assert.isNull(salt,
  127. "Salt value must be null when used with crypto module PasswordEncoder");
  128. }
  129. });
  130. return;
  131. }
  132. throw new IllegalArgumentException(
  133. "passwordEncoder must be a PasswordEncoder instance");
  134. }
  135. private void setPasswordEncoder(PasswordEncoder passwordEncoder) {
  136. Assert.notNull(passwordEncoder, "passwordEncoder cannot be null");
  137. this.userNotFoundEncodedPassword = passwordEncoder.encodePassword(
  138. USER_NOT_FOUND_PASSWORD, null);
  139. this.passwordEncoder = passwordEncoder;
  140. }
  141. protected PasswordEncoder getPasswordEncoder() {
  142. return passwordEncoder;
  143. }
  144. /**
  145. * The source of salts to use when decoding passwords. <code>null</code> is a valid
  146. * value, meaning the <code>DaoAuthenticationProvider</code> will present
  147. * <code>null</code> to the relevant <code>PasswordEncoder</code>.
  148. * <p>
  149. * Instead, it is recommended that you use an encoder which uses a random salt and
  150. * combines it with the password field. This is the default approach taken in the
  151. * {@code org.springframework.security.crypto.password} package.
  152. *
  153. * @param saltSource to use when attempting to decode passwords via the
  154. * <code>PasswordEncoder</code>
  155. */
  156. public void setSaltSource(SaltSource saltSource) {
  157. this.saltSource = saltSource;
  158. }
  159. protected SaltSource getSaltSource() {
  160. return saltSource;
  161. }
  162. public void setUserDetailsService(UserDetailsService userDetailsService) {
  163. this.userDetailsService = userDetailsService;
  164. }
  165. @Override
  166. public boolean supports(Class<?> authentication) {
  167. return true;
  168. }
  169. protected UserDetailsService getUserDetailsService() {
  170. return userDetailsService;
  171. }
  172. }