TokenRealm.java 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package com.qxgmat.util.shiro;
  2. import com.qxgmat.data.dao.entity.User;
  3. import com.qxgmat.service.UsersService;
  4. import org.apache.shiro.authc.*;
  5. import org.apache.shiro.authz.AuthorizationInfo;
  6. import org.apache.shiro.authz.SimpleAuthorizationInfo;
  7. import org.apache.shiro.realm.AuthorizingRealm;
  8. import org.apache.shiro.subject.PrincipalCollection;
  9. import org.slf4j.Logger;
  10. import org.slf4j.LoggerFactory;
  11. import org.springframework.beans.factory.annotation.Autowired;
  12. import java.util.ArrayList;
  13. import java.util.Objects;
  14. /**
  15. * Created by GaoJie on 2017/11/3.
  16. */
  17. public class TokenRealm extends AuthorizingRealm {
  18. private static final Logger logger = LoggerFactory.getLogger(TokenRealm.class);
  19. @Autowired
  20. private UsersService usersService;
  21. public TokenRealm() {
  22. super();
  23. setAuthenticationTokenClass(AuthenticationToken.class);
  24. }
  25. @Override
  26. protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
  27. String className = TokenRealm.class.getName();
  28. boolean selected = false;
  29. for(String realmNames: principalCollection.getRealmNames()){
  30. if(realmNames.contains(className)) selected = true;
  31. }
  32. if(!selected) return null;
  33. ArrayList<String> roleAuthorization = new ArrayList<String>();
  34. SimpleAuthorizationInfo sa = new SimpleAuthorizationInfo();
  35. roleAuthorization.add("user");
  36. sa.addRoles(roleAuthorization);
  37. return sa;
  38. }
  39. @Override
  40. protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
  41. AuthenticationToken token = (AuthenticationToken) authenticationToken;
  42. String username = (String)token.getCredentials();
  43. logger.info("Login token: "+username);
  44. User user = usersService.getUserByToken(username);
  45. if (user == null || user.getId() <= 0) {
  46. throw new UnknownAccountException("用户不存在!");
  47. }
  48. return new SimpleAuthenticationInfo(user, username, getName());
  49. }
  50. protected void assertCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) throws AuthenticationException {
  51. }
  52. }