Shiro:登陆成功并未执行doGetAuthorizationInfo

package com.hk3t.core.security;

import java.util.Set;

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.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.hk3t.model.entity.User;
import com.hk3t.model.service.UserService;

/**
 * 自定义DB Realm
 * 
 */
public class CmsAuthorizingRealm extends AuthorizingRealm {

	/**
	 * 登录认证
	 */
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
		UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
		User user = userService.findByUsername(token.getUsername());
		if (user != null) {
			return new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(), getName());
		} else {
			return null;
		}
	}

	/**
	 * 授权
	 */
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		String username = (String) principals.getPrimaryPrincipal();
		User user = userService.findByUsername(username);
		SimpleAuthorizationInfo auth = new SimpleAuthorizationInfo();
		if (user != null) {
			Set perms = user.getPerms();
			if (!CollectionUtils.isEmpty(perms)) {
				// 权限加入AuthorizationInfo认证对象
				auth.setStringPermissions(perms);
			}
		}
		return auth;
	}
	
	public void removeUserAuthorizationInfoCache(String username) {
		SimplePrincipalCollection pc = new SimplePrincipalCollection();
		pc.add(username, super.getName());
		super.clearCachedAuthorizationInfo(pc);
	}
	
	@Autowired
	private UserService userService;
}

自定义AuthorizingRealm类


	@RequiresPermissions( "index" )
	@RequestMapping( "/index.do" )
	public String index( HttpServletRequest request, ModelMap model )

在Controller加入@RequiresPermissions注解


	
	
	
    	
	
在spring-action.xml

启用AOP自动代理

AuthorizationAttributeSourceAdvisor在访问所有有@RequiresPermissions注解的方法,都会判断是否具有权限


            org.aspectj
            aspectjweaver
            ${aspectj.version}
        

如果aspectj支持

登陆之后权限不会改变,如果在有service中有改变权限的操作时,在AuthorizingRealm中添加下面的方法

	public void removeUserAuthorizationInfoCache(String username) {
		SimplePrincipalCollection pc = new SimplePrincipalCollection();
		pc.add(username, super.getName());
		super.clearCachedAuthorizationInfo(pc);
	}

手动清空Cache中权限,重新获取,username为你登陆的用户名

上述操作只会重新doGetAuthorizationInfo,不会需要重新验证

你可能感兴趣的:(Shiro)