spring boot爬坑之旅途--shiro-MyRealm配置(9)

package com.zm.blog.config.shiro;

import java.util.HashSet;
import java.util.List;
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.UnknownAccountException;
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.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import com.zm.blog.mapper.customer.Permission;
import com.zm.blog.mapper.customer.Role;
import com.zm.blog.mapper.customer.User;
import com.zm.blog.uib.service.UserService;

public class MyRealm extends AuthorizingRealm {
	
	@Autowired
	private UserService userService;

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		User principal=(User) principals.getPrimaryPrincipal();
		List<Role> userRoles=userService.getUserRoles(principal.getId());
		//添加权限
		Set<String> roles=new HashSet<String>();
		Set<String> permissions=new HashSet<String>();
		if(null!=userRoles){
			for (Role role : userRoles) {
				roles.add(role.getRemark());
				System.out.println("shiro角色:"+role.getRemark());
				List<Permission> ps=userService.getPremission(role.getId());
				for (Permission p : ps) {
					System.out.println("shiro菜单权限:"+p.getUrl());
					permissions.add(p.getUrl());
				}
			}
		}
		SimpleAuthorizationInfo info= new SimpleAuthorizationInfo(roles);
		info.addStringPermissions(permissions);
		return info;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		UsernamePasswordToken upToken = (UsernamePasswordToken) token;
		String userName = upToken.getUsername();
		User userInfo =userService.getUserByName(userName);
		if (null == userInfo) {
			throw new UnknownAccountException("用户不存在!");
		}
		Object credentials = userInfo.getPassword(); 
		ByteSource credentialsSalt=ByteSource.Util.bytes(userInfo.getUsername());
		SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(userInfo, credentials,credentialsSalt, getName());
		return authenticationInfo;
	}
	
	public void clearCached() {
		//清除缓存
		System.out.println("clear Cached");
		PrincipalCollection principals = SecurityUtils.getSubject().getPrincipals();
		super.clearCache(principals);
	}
}

猜你喜欢

转载自blog.csdn.net/z3133464733/article/details/80215257