Spring安全性获取User对象

时间:2014-07-27 10:32:33

标签: spring spring-security

我已经通过Spring Security Framework实现了用户身份验证,一切正常。我可以登录并注销,我可以获得记录的用户名,例如:

String userName = ((UserDetails) auth.getPrincipal()).getUsername();

现在我想让用户像数据库中的对象(我需要用户ID和其他用户属性)。

这是我迄今为止的尝试:

User user = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();

此后我得到以下例外:

Request processing failed; nested exception is java.lang.ClassCastException: org.springframework.security.core.userdetails.User cannot be cast to net.viralpatel.contact.model.User

这是一个问题 - 如何将User作为对象,我应该如何修改我的类UserDetailsS​​erviceImpl和UserAssembler,任何想法?

@Component
@Transactional
public class UserDetailsServiceImpl implements UserDetailsService{

    @Autowired
    private UserDAO userDAO;

    @Autowired
    private UserAssembler userAssembler;

    private static final Logger logger = LoggerFactory.getLogger(UserDetailsServiceImpl.class);

    @Transactional(readOnly = true)
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
        User user = userDAO.findByEmail(username);

        if(null == user) throw new UsernameNotFoundException("User not found");
        return userAssembler.buildUserFromUser(user);
    }
}

还有一个:

@Service("assembler")
public class UserAssembler {

    @Autowired
    private UserDAO userDAO;

    @Transactional(readOnly = true)
    public User buildUserFromUser(net.viralpatel.contact.model.User user) {
        String role = "ROLE_USER";//userEntityDAO.getRoleFromUserEntity(userEntity);

        Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
        authorities.add(new GrantedAuthorityImpl(role));

        return new User(user.getLogin(), user.getPassword(), true, true, true, true,  authorities);
    }
}

3 个答案:

答案 0 :(得分:13)

基本上,您需要返回UserDetails的实施,以便提供对User的访问权限。

您有两种选择:

  • 将您的User添加为字段(您可以将其扩展为org.springframework.security.core.userdetails.User):

    public class UserPrincipal extends org.springframework.security.core.userdetails.User {
        private final User user;
       ...
    }  
    

    并从该字段中获取User

    Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    User user = ((UserPrincipal) principal).getUser();
    
  • 创建一个扩展User的类并实现UserDetails

    public class UserPrincipal extends User implements UserDetails {
        ...
        public UserPrincipal(User user) {
            // copy fields from user
        }
    }
    

    此方法允许您直接将主体转换为User

    User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    

答案 1 :(得分:0)

看起来你的User类没有扩展Spring的org.springframework.security.core.userdetails.User类。

以下是一个供参考的示例代码,我将其命名为&#39; AuthenticUser&#39;:

 public class AuthenticUser extends User {

        public AuthenticUser(String username, String password, boolean enabled,
        boolean accountNonExpired, boolean credentialsNonExpired,
        boolean accountNonLocked,
        Collection<? extends GrantedAuthority> authorities) {

        super(username, password, enabled, accountNonExpired, credentialsNonExpired,
            accountNonLocked, authorities);
    }
   .....
   .....
 }

现在,您可以在代码中创建此类的对象,并将其设置为Spring Authentication Context的一部分,例如

  AuthenticUser user  = new AuthenticUser(username, password, .... rest of the parameters);
  Authentication authentication =  new UsernamePasswordAuthenticationToken(user, null,
      user.getAuthorities());
  SecurityContextHolder.getContext().setAuthentication(authentication);

这将验证您的用户并在安全上下文中设置用户。

答案 2 :(得分:0)

您需要实现自己的UserDetailsS​​ervice和您自己的UserDetails对象(根据您的意愿):

public class CustomService implements UserDetailsService {
@Transactional(readOnly = true)
public UserDetails loadUserByUsername(String userId) {

    Account account = accountDAO.findAccountByName(userId);

    // validation of the account
    if (account == null) {
        throw new UsernameNotFoundException("not found");
    }
    return buildUserFromAccount(account);
}


@SuppressWarnings("unchecked")
@Transactional(readOnly = true)
private User buildUserFromAccount(Account account) {

    // take whatever info you need
    String username = account.getUsername();
    String password = account.getPassword();
    boolean enabled = account.getEnabled();
    boolean accountNonExpired = account.getAccountNonExpired();
    boolean credentialsNonExpired = account.getCredentialsNonExpired();
    boolean accountNonLocked = account.getAccountNonLocked();

    // additional information goes here
    String companyName = companyDAO.getCompanyName(account);


    Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
    for (Role role : account.getRoles()) {
        authorities.add(new SimpleGrantedAuthority(role.getName()));
    }

    CustomUserDetails user = new CustomUserDetails (username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked,
            authorities, company);

    return user;
}


public class CustomUserDetails extends User{

// ...
public CustomUserDetails(..., String company){
     super(...);
     this.company = company;
}

private String company;

public String getCompany() { return company;}

public void setCompany(String company) { this.company = company;}
}

注意:
这是User类的默认实现,您需要一些自定义信息,您可以创建自定义类并扩展User类