All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.haoxuer.discover.user.shiro.realm.UserInfoRealm Maven / Gradle / Ivy

There is a newer version: 3.3.18-20230117
Show newest version
package com.haoxuer.discover.user.shiro.realm;

import com.haoxuer.discover.user.shiro.utils.UserUtil;
import com.haoxuer.discover.user.data.entity.UserInfo;
import com.haoxuer.discover.user.data.service.UserInfoService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * Created by ada on 2017/6/12.
 */
public class UserInfoRealm extends AuthorizingRealm {


  Logger logger = LoggerFactory.getLogger("ada");

  @Autowired
  UserInfoService userService;

  /**
   * 授权
   *
   * @param principals
   * @return
   */
  @Override
  protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
    UserAuthorization authorization = new UserAuthorization(userService);
    return authorization.doGetAuthorizationInfo(principals);
  }

  @Override
  public Class getAuthenticationTokenClass() {
    return UserInfoToken.class;
  }

  /**
   * 认证
   *
   * @param token
   * @return
   * @throws AuthenticationException
   */
  @Override
  protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    UserInfoToken casToken = (UserInfoToken) token;
    if (token == null) {
      return null;
    } else {
      Long userid = (Long) casToken.getCredentials();
      if (userid == null || userid < 0L) {
        return null;
      } else {
        try {
          UserInfo user = userService.findById(userid);
          ShiroUser shiroUser = new ShiroUser(user.getId(), user.getId() + "", user.getName());
          // 设置用户session
          UserUtil.setCurrentUser(user);
          PrincipalCollection principalCollection = new SimplePrincipalCollection(shiroUser, this.getName());
          SimpleAuthenticationInfo aa = new SimpleAuthenticationInfo(principalCollection, userid);
          return aa;
        } catch (Exception e) {
          return null;
        }
      }
    }
  }


}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy