UserRealm.java 2.75 KB
package com.glsx.usercenter.shiro;

import java.util.HashSet;
import java.util.Set;

import org.apache.shiro.SecurityUtils;
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.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.Permission;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import com.glsx.usercenter.pojo.menu.SysMenu;
import com.glsx.usercenter.pojo.user.SysUser;
import com.glsx.usercenter.service.ISysMenuService;
import com.glsx.usercenter.service.SysRoleService;
import com.glsx.usercenter.service.SysUserService;
import com.glsx.usercenter.utils.ShiroUtil;

public class UserRealm extends AuthorizingRealm{
	
	@Autowired
	private SysUserService sysUserService;
	
	@Autowired
	private ISysMenuService menuService;
	
	@Autowired
	private SysRoleService roleService;

	/**
	 * 授权
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(
			PrincipalCollection principals) {
		// TODO Auto-generated method stub
		SysUser user = ShiroUtil.getUser();
		// 角色列表
		Set<String> roles = new HashSet<String>();
		roles.add("运营");
		// 功能列表
		Set<String> menus = new HashSet<String>();
		menus.add("system:test:get");
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		/*roles = roleService.selectRoleKeys(user.getUserId());
		menus = menuService.selectPermsByUserId(user.getUserId());*/
		// 角色加入AuthorizationInfo认证对象
		info.setRoles(roles);
		// 权限加入AuthorizationInfo认证对象
		info.setStringPermissions(menus);
		return info;
	}

	/**
	 * 登录认证
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken token) throws AuthenticationException {
		// TODO Auto-generated method stub
		UsernamePasswordToken upToken = (UsernamePasswordToken) token;
		String username = (String) upToken.getPrincipal();
		String password = "";
		if (upToken.getCredentials() != null) {
			password = new String(upToken.getPassword());
		}
		SysUser user = sysUserService.login(username, password);
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, user.getPassword(), getName());
		return info;
	}

	/**
     * 清理缓存权限
     */
    public void clearCachedAuthorizationInfo() {
        this.clearCachedAuthorizationInfo(SecurityUtils.getSubject().getPrincipals());
    }
}