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

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.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.user.SysUser;
import com.glsx.usercenter.service.SysUserService;

public class UserRealm extends AuthorizingRealm {

    @Autowired
    private SysUserService sysUserService;


    /**
     * 授权
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(
            PrincipalCollection principals) {
        // TODO Auto-generated method stub
        /*SysUser user = ShiroUtil.getUser();
		// 角色列表
		Set<String> roles = new HashSet<String>();
		// 功能列表
		Set<String> menus = new HashSet<String>();*/
        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());
    }
}