CasUserRealm.java 3.0 KB
package com.framework.shiro;

import java.util.HashMap;


import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cas.CasRealm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.fastjson.JSONObject;
import com.eport.rest.entity.EptUserInfoEntity;
import com.eport.rest.service.EptMenuService;
import com.eport.rest.service.EptUserInfoService;
import com.google.common.base.Objects;
import com.google.common.collect.Maps;

public class CasUserRealm extends CasRealm{
	
	@Autowired
	private ShiroFilterFactoryBean shiroBean;
	@Autowired
	private EptUserInfoService userService;
	@Autowired
	private EptMenuService menuService;
	

	/**
	 * 返回当前subject的授权信息
	 * 交由shiro的Authorizer鉴权
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
		String loginAccount = (String) principals.getPrimaryPrincipal();
		HashMap<String, Object> par = Maps.newHashMap();
		par.put("account", loginAccount);
		HashMap<String, Object> user = userService.findByAccount(par);
		if(user!=null){
			EptUserInfoEntity userInfo = JSONObject.parseObject(JSONObject.toJSONString(user), EptUserInfoEntity.class);
			
		}
		return authorizationInfo;
	}
	
	
	
	/**
	 * 1、CAS认证 ,验证用户身份
	 * 2、将用户基本信息设置到会话中
	 */
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) {
		
		AuthenticationInfo authc = super.doGetAuthenticationInfo(token);
		String account = (String) authc.getPrincipals().getPrimaryPrincipal();
		
		HashMap<String, Object> par = Maps.newHashMap();
		par.put("account", account);
		HashMap<String, Object> user = userService.findByAccount(par);
		if (user == null) {
			throw new UnknownAccountException();
		}
		// user.setLastLoginTime(new Date());
		// userService.save(user);
		Subject subject = SecurityUtils.getSubject();
		SimpleAuthenticationInfo authenticationInfo = null;
		EptUserInfoEntity userInfo = JSONObject.parseObject(JSONObject.toJSONString(user), EptUserInfoEntity.class);
		authenticationInfo = new SimpleAuthenticationInfo(userInfo.getAccount(), userInfo.getPassword(), getName());
		if(!Objects.equal(userInfo.getStatus(), 1)){
			throw new LockedAccountException();
		}
		// 创建会话
		subject.getSession().setAttribute("userInfo", userInfo);
		return authenticationInfo;
	}
	
	

}