【问题标题】:How to create Custom UserDetail Object in Spring Security如何在 Spring Security 中创建自定义 UserDetails 对象
【发布时间】:2014-12-14 09:04:37
【问题描述】:

我已经为 Spring Security 构建了我的自定义身份验证管理器,类似于这样

   public class AccountAuthenticationProvider implements  AuthenticationProvider{

    @Autowired
    private AuthenticationService authService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {

        String userName = authentication.getName();
        String password = (String)authentication.getCredentials();

        if(authService.isValid(userName,password)){
            List<GrantedAuthority> grantedAuthorityList = new ArrayList<GrantedAuthority>();
            grantedAuthorityList.add(new SimpleGrantedAuthority("ROLE_USER"));
            SecurityContext securityContext = new SecurityContextImpl();
            return  new UsernamePasswordAuthenticationToken(userName,password);
        }

        return null;
    }


    public void setAuthService(AuthenticationService authService) {
        this.authService = authService;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return true;
    }

}

但是如何创建自己的自定义 UserDetail 对象?我将使用它来存储与帐户相关的值

【问题讨论】:

    标签: java spring spring-mvc spring-security


    【解决方案1】:

    你几乎拥有它!

    if(authService.isValid(userName,password)) {
        List<GrantedAuthority> grantedAuthorityList = new ArrayList<GrantedAuthority>();
        grantedAuthorityList.add(new SimpleGrantedAuthority("ROLE_USER"));
        MyObject myObj = new MyObject(userName, password, otherInfo);
        return  new UsernamePasswordAuthenticationToken(mjObj,"", grantedAuthorityList);
    }
    

    UsernamePasswordAuthenticationToken 的第一个参数是原则。原理是系统中代表刚刚登录的人(或事物)的对象。

    在身份验证之前,原则只是(字符串)用户名,因为这就是您当时拥有的所有信息。登录后,您可能会收集其他信息以与用户一起使用。

    Spring 提供接口:UserUserDetailsUserDetailsService 来帮助管理用户并与用户一起做有弹性的事情,所以如果你让 MyObject 实现 UserDetails 那么你可以从Spring 环境,但您不必只使用MyObject

    在您的控制器中(在 Spring 4 中),您可以使用 @AuthenticationPrincipal 将用户对象注入到调用中,例如:

    @RequestMapping(method = RequestMethod.GET, value = "/foo/{bar}")
    public SomeObject myCommand(@AuthenticationPrincipal MyObject user, @PathVariable String bar);
    

    【讨论】:

      【解决方案2】:

      您需要实现 UserDetailsS​​ervice 并重写 loadUserByUsername 方法以返回您自定义的 UserDetails 类。像这样-

      public class UserServiceImpl implements UserDetailsService {`
      
      @Autowired
      UserDaoImpl userDao;
      
      @Override
      public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
          System.out.println(username);
          Users user = (Users) userDao.findByUserName(username);
          List<GrantedAuthority> authorities = buildUserAuthority(user.getUserRoles());
          System.out.println("after....");
          return buildUserForAuthentication(user, authorities);
      }
      
      private List<GrantedAuthority> buildUserAuthority(Set<UserRole> userRoles) {
          Set<GrantedAuthority> setAuths = new HashSet<GrantedAuthority>(); 
          for(UserRole userRole  : userRoles){
              System.out.println("called buildUserAuthority(Set<UserRole> userRoles) method.....");
              setAuths.add(new SimpleGrantedAuthority(userRole.getRole()));
          }
      
          List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>(setAuths);
          return grantedAuthorities;
      }
      
      private User buildUserForAuthentication(Users user, List<GrantedAuthority> authorities) {
          //accountNonExpired, credentialsNonExpired, accountNonLocked, authorities properties
          System.out.println("called buildUserForAuthentication(Users user, List<GrantedAuthority> authorities) method....");
          return new User(user.getUsername(), user.getPassword(), user.getEnabled(), true, true, true, authorities);
      }}
      

      【讨论】:

        【解决方案3】:

        您需要实现 UserDetailsS​​ervice 并重写 loadUserByUsername 方法以返回您自定义的 UserDetails 类。

        查看以下链接:

        http://www.javaroots.com/2013/03/how-to-use-custom-dao-classe-in-spring.html http://www.javacodegeeks.com/2012/08/spring-security-implementing-custom.html

        【讨论】:

          猜你喜欢
          • 2012-01-29
          • 2018-04-02
          • 2017-01-31
          • 2019-08-22
          • 2018-02-04
          • 2018-10-09
          • 2013-07-23
          • 2013-10-11
          • 2014-11-21
          相关资源
          最近更新 更多