Guest User

Untitled

a guest
Jun 12th, 2018
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.42 KB | None | 0 0
  1. package com.eureka.auth.security;
  2.  
  3. import java.util.Arrays;
  4. import java.util.List;
  5.  
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.security.core.GrantedAuthority;
  8. import org.springframework.security.core.authority.AuthorityUtils;
  9. import org.springframework.security.core.userdetails.User;
  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.security.crypto.bcrypt.BCryptPasswordEncoder;
  14. import org.springframework.stereotype.Service;
  15.  
  16. @Service // It has to be annotated with @Service.
  17. public class UserDetailsServiceImpl implements UserDetailsService {
  18.  
  19. @Autowired
  20. private BCryptPasswordEncoder encoder;
  21.  
  22. @Override
  23. public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
  24.  
  25. // hard coding the users. All passwords must be encoded.
  26. final List<AppUser> users = Arrays.asList(
  27. new AppUser(1, "omar", encoder.encode("12345"), "USER"),
  28. new AppUser(2, "admin", encoder.encode("12345"), "ADMIN")
  29. );
  30.  
  31.  
  32. for(AppUser appUser: users) {
  33. if(appUser.getUsername().equals(username)) {
  34.  
  35. // Remember that Spring needs roles to be in this format: "ROLE_" + userRole (i.e. "ROLE_ADMIN")
  36. // So, we need to set it to that format, so we can verify and compare roles (i.e. hasRole("ADMIN")).
  37. List<GrantedAuthority> grantedAuthorities = AuthorityUtils
  38. .commaSeparatedStringToAuthorityList("ROLE_" + appUser.getRole());
  39.  
  40. // The "User" class is provided by Spring and represents a model class for user to be returned by UserDetailsService
  41. // And used by auth manager to verify and check user authentication.
  42. return new User(appUser.getUsername(), appUser.getPassword(), grantedAuthorities);
  43. }
  44. }
  45.  
  46. // If user not found. Throw this exception.
  47. throw new UsernameNotFoundException("Username: " + username + " not found");
  48. }
  49.  
  50. // A (temporary) class represent the user saved in the database.
  51. private static class AppUser {
  52. private Integer id;
  53. private String username, password;
  54. private String role;
  55.  
  56. public AppUser(Integer id, String username, String password, String role) {
  57. this.id = id;
  58. this.username = username;
  59. this.password = password;
  60. this.role = role;
  61. }
  62.  
  63. // getters and setters ....
  64. }
  65. }
Add Comment
Please, Sign In to add comment