Advertisement
Guest User

CustomAuthenticationProvider

a guest
Apr 22nd, 2016
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.09 KB | None | 0 0
  1. package com.netcracker.unc.services;
  2.  
  3. import com.netcracker.unc.entity.CustomUserDetails;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.security.authentication.AuthenticationProvider;
  6. import org.springframework.security.authentication.BadCredentialsException;
  7. import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
  8. import org.springframework.security.core.Authentication;
  9. import org.springframework.security.core.AuthenticationException;
  10. import org.springframework.security.core.GrantedAuthority;
  11. import org.springframework.security.core.userdetails.UserDetails;
  12. import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
  13. import org.springframework.stereotype.Component;
  14.  
  15. import java.util.Collection;
  16.  
  17.  
  18. @Component
  19. public class CustomAuthenticationProvider implements AuthenticationProvider {
  20.  
  21. @Autowired
  22. private UserService userService;
  23. @Autowired
  24. BCryptPasswordEncoder passwordEncoder;
  25.  
  26. /**
  27. * Аутентификация пользователя по введенным паролю и имени
  28. *
  29. * @param authentication - Данные переданные пользователем
  30. * @return UsernamePasswordAuthenticationToken
  31. * @throws AuthenticationException
  32. */
  33. @Override
  34. public Authentication authenticate(Authentication authentication) throws AuthenticationException {
  35. String username = authentication.getName();
  36. String password = (String) authentication.getCredentials();
  37.  
  38. UserDetails user = userService.loadUserByUsername(username);
  39.  
  40. if ((user == null) || (!passwordEncoder.matches(password, user.getPassword()))) {
  41. throw new BadCredentialsException("Wrong username or password.");
  42. }
  43. //user.setPassword("");
  44. Collection<? extends GrantedAuthority> authorities = user.getAuthorities();
  45. return new UsernamePasswordAuthenticationToken(user, null, authorities);
  46. }
  47.  
  48. @Override
  49. public boolean supports(Class<?> arg0) {
  50. return true;
  51. }
  52.  
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement