Allen32

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

自定义Realm的基本样例

package realm;

import cn.wolfcode.wms.domain.Employee;
import cn.wolfcode.wms.mapper.EmployeeMapper;
import cn.wolfcode.wms.mapper.PermissionMapper;
import cn.wolfcode.wms.mapper.RoleMapper;
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.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

public class MyReal extends AuthorizingRealm {
    @Autowired
    EmployeeMapper employeeMapper;
    @Autowired
    PermissionMapper permissionMapper;
    @Autowired
    RoleMapper roleMapper;

    //权限检查
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        List<String> permissions = null;

        Employee employee = (Employee) principals.getPrimaryPrincipal();
        //如果是admin
        if (employee.isAdmin()) {
            permissions = permissionMapper.getAllExpression();
        } else {

            permissions = permissionMapper.getExpressionsByEmployeeId(employee.getId());
        }


        //权限列表
        //角色列表
        List<String> roles = roleMapper.getRolesByEmployeeId(employee.getId());
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addRoles(roles);
        simpleAuthorizationInfo.addStringPermissions(permissions);
        return simpleAuthorizationInfo;


    }

    //登陆~
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //获取用户名
        String principal = (String) token.getPrincipal();
        //根据用户名获取用户
        Employee employee = employeeMapper.getEmployeeByName(principal);
        if (employee == null) {
            return null;
        }

        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(employee, employee.getPassword(), "MyReal");

        return simpleAuthenticationInfo;
    }
}
 

 

posted on 2018-01-31 14:17  Allen32  阅读(66)  评论(0)    收藏  举报