spring mvc 集成shiro 做权限的简单使用

本文介绍了如何在Spring MVC项目中集成Shiro进行权限控制,包括引入依赖、实现Controller、权限验证、配置Shiro及注解授权等步骤。
摘要由CSDN通过智能技术生成

1.概述

现在的项目使用的权限控制系统是spring security 3.因为项目的框架使用spring,就顺便使用了。最近研究了一下spring side4,推荐使用shiro。照着示例做了一遍。在原有的spring web工程中。步骤如下。


2.引进包,maven设置

 <dependency>
    	<groupId>org.apache.shiro</groupId>
    	<artifactId>shiro-all</artifactId>
    	<version>1.2.1</version>
    	<type>jar</type>
    	<scope>compile</scope>
    </dependency>

3.实现Controller层

主要是登陆url和几个掩饰url

@Controller
public class AdminController {

	@RequestMapping(value = "/admin/index", method = RequestMethod.GET)
	public String index(Model model) {

		return "admin/index";
	}
	
	
	@RequestMapping(value = "/admin/login", method = RequestMethod.GET)
	public String login(Model model) {
		logger.info("login get");
		return "admin/login";
	}
	
	
	@RequestMapping(value = "/admin/login", method = RequestMethod.POST)
	public String doLogin(Model model) {
		logger.info("login post");
		return "admin/login";
	}
	
	@RequiresRoles("user")
	@RequestMapping(value = "/admin/user", method = RequestMethod.GET)
	public String shiroUser(Model model) {
	
		return "admin/index";
	}
	
	@RequiresRoles("admin")
	@RequestMapping(value = "/admin/admin", method = RequestMethod.GET)
	public String shiroAdmin(Model model) {
		
		return "admin/index";
	}
	
	Logger logger = LoggerFactory.getLogger(AdminController.class);

}


4.实现权限验证

继承shiro的AuthorizingRealm

public class ShiroDbRealm extends AuthorizingRealm {

	protected AccountService accountService;

	@Autowired
	public void setAccountService(AccountService accountService) {
		this.accountService = accountService;
	}

	/**
	 * 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用.
	 */

	@SuppressWarnings("unused")
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection p) {

		logger.info("授权认证:" + p.getRealmNames());
		
		ShiroUser shiroUser = (ShiroUser) p.getPrimaryPrincipal();
		User user = accountService.findUserByLoginName(shiroUser.loginName);

		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		for (Role role : user.getRoleList()) {
			//基于Role的权限信息
			info.addRole(role.getName());
			//基于Permission的权限信息
			info.addStringPermission(role.getPermissions());
		}
		return info;
		
	}

	/**
	 * 认证回调函数,登录时调用.
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken authcToken) throws AuthenticationException {
		logger.info("authc pass:");
		UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
		logger.info("authc name:" + token.getUsername());
		User user = accountService.findUserByLoginName(token.getUsername());
		if (user != null) {

			if (user.getStatus().equals("disabled")) {
				throw new DisabledAccountException();
			}			

			logger.info("authc name:" + token.getUsername() + " user:"
					+ user.getLoginName() + " pwd:" + user.getPassword()
					+ "getname:" + getName());

			// byte[] salt = Encodes.decodeHex(user.getSalt());
			return new SimpleAuthenticationInfo(new ShiroUser(user.getLoginName(), user.getName()),					
					user.getPassword(), getName());
		}
		return null;

	}

	/**
	 * 自定义Authentication对象,使得Subject除了携带用户的登录名外还可以携带更多信息.
	 */
	public static class ShiroUser implements Serializable {
		private static final long serialVersionUID = -1373760761780840081L;
		public String loginName;
		public String name;

		public ShiroUser(String loginName, String name) {
			this.loginName = loginName;
			this.name = name;
		}

		public String getName() {
			return loginName;
		}

		/**
		 * 本函数输出将作为默认的<shiro:principal/>输出.
		 */
		@Override
		public String toString() {
			return loginName;
		}

		/**
		 * 重载hashCode,只计算loginName;
		 */
		@Override
		public int hashCode() {
			return Objects.hashCode(loginName);
		}

		/**
		 * 重载equals,只计算loginName;
		 */
		@Override
		public boolean equals(Object obj) {
			if (this == obj)
				return true;
			if (obj == null)
				return false;
			if (getClass() != obj.getClass())
				return false;
			ShiroUser other = (ShiroUser) obj;
			if (loginName == null) {
				if (other.loginName != null)
					return false;
			} else if (!loginName.equals(other.loginName))
				return false;
			return true;
		}
	}

	Logger logger = LoggerFactory.getLogger(ShiroDbRealm.class);

}

自定义的类ShiroUser是为了,可以多传输一些内容,供后面验证时使用,例子中只用了一个loginName,一般可以用String 传输就够了。

登陆时用doGetAuthenticationInfo()函数获得相关信息。

登陆后访问url 使用doGetAuthorizationInfo()获得用户的权限。


5.配置文件shiro部分

将controller的url纳入权限验证范围。

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd"
	default-lazy-init="true">

	<description>Shiro安全配置</description>

	

	<!-- 項目自定义的Realm -->
	<bean id="shiroDbRealm" class="com.blueinfo.jee.shiro.ShiroDbRealm" depends-on="userDao,roleDao">
		<property name="accountService" ref="accountService"/>
	</bean>
	
	<!-- Shiro Filter -->
	<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
		<property name="securityManager" ref="securityManager" />
		<property name="loginUrl" value="/admin/login" />
		<property name="successUrl" value="/admin/index" />
		<property name="unauthorizedUrl" value="/admin/logout" />
		<property name="filterChainDefinitions">
			<value>
				/admin/login = authc				
				/admin/logout = logout
				/static/** = anon
				/admin/** = authc
				
			</value>
		</property>
	</bean>

	<!-- 用户授权信息Cache, 采用EhCache -->
	<bean id="shiroEhcacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
		<property name="cacheManagerConfigFile" value="classpath:security/ehcache-shiro.xml"/>
	</bean>
	
	<!-- Shiro's main business-tier object for web-enabled applications -->
	<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
		<property name="realm" ref="shiroDbRealm" />
		<property name="cacheManager" ref="shiroEhcacheManager" />
	</bean>
	
	
	<!-- 保证实现了Shiro内部lifecycle函数的bean执行 -->
	<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
	
	<!-- AOP式方法级权限检查  -->
	<bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" depends-on="lifecycleBeanPostProcessor">
		<property name="proxyTargetClass" value="true" />
	</bean>
	<bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
    	<property name="securityManager" ref="securityManager"/>
	</bean>
</beans>

主要内容是shiroFilter的定义。

loginUrl:登陆页面,用户登陆不成功,自动返回此页面。

successUrl:登陆成功后跳转此页面

unauthorizedUrl:用户访问无权限的链接时跳转此页面

filterChainDefinitions:设置url的访问权限。anon表示不用验证,都可以访问。anthc:authc filter 监听,不登陆不能访问。logout:logout filter监听。没有列出的常用配置:perms["remote:invoke"] :需要角色romote 和权限invoke才能访问。roles["admin"]需要角色admin才能访问。设置可用“,”隔开,如:

/admin/test = authc,roles[admin]

关于filter的列表:

Filter NameClass
anonorg.apache.shiro.web.filter.authc.AnonymousFilter
authcorg.apache.shiro.web.filter.authc.FormAuthenticationFilter
authcBasicorg.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter
permsorg.apache.shiro.web.filter.authz.PermissionsAuthorizationFilter
portorg.apache.shiro.web.filter.authz.PortFilter
restorg.apache.shiro.web.filter.authz.HttpMethodPermissionFilter
rolesorg.apache.shiro.web.filter.authz.RolesAuthorizationFilter
sslorg.apache.shiro.web.filter.authz.SslFilter
userorg.apache.shiro.web.filter.authc.UserFilter

6.配置文件,启用shiroFilter

上面的配置和源码定义了shiroFilter,在web.xml中启用它

<!-- Shiro Security filter -->
	
	<filter>
		<filter-name>shiroFilter</filter-name>
		<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>shiroFilter</filter-name>
		<url-pattern>/*</url-pattern>
		<dispatcher>REQUEST</dispatcher>
		<dispatcher>FORWARD</dispatcher>
	</filter-mapping>

7.使用annotation控制权限

在2中controller使用@RequiresRoles 注解控制权限,还可以是@RequirePermissions,要在方法上使用注解需要做如下配置:

1.在spring-mvc.xml中加入

	<!-- 支持 Shiro对Controller的方法级AOP安全控制-->
	<bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" depends-on="lifecycleBeanPostProcessor">
		<property name="proxyTargetClass" value="true" />
	</bean>
	
	<bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
    	<property name="securityManager" ref="securityManager"/>
	</bean>

2.出错控制,在spring-mvc.xml中加入

<!-- 将Controller抛出的异常转到特定View -->
	<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">  
		<property name="exceptionMappings">  
			<props>
				<prop key="org.apache.shiro.authz.UnauthorizedException">error/403</prop>
				<prop key="java.lang.Throwable">error/500</prop>
            </props>  
		</property>  
    </bean> 
将UnauthorizedException异常转到403页面,也可以使用其它页面.


8.参考

1,文中的内容大部分来源于开源工程,spring-side,真心感谢其作者江南白衣

2.apache-shiro官网:http://shiro.apache.org/



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值