shiro的入门实例-shiro于spring的整合

shiro是一款java安全框架、简单而且可以满足实际的工作需要

第一步、导入maven依赖

<!-- shiro -->
<dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-core</artifactId>
    <version>${org.apache.shiro.version}</version>
</dependency>
<dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-web</artifactId>
    <version>${org.apache.shiro.version}</version>
</dependency>
<dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-spring</artifactId>
    <version>${org.apache.shiro.version}</version>
</dependency>
<dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-ehcache</artifactId>
    <version>${org.apache.shiro.version}</version>
</dependency>

  第二步、在项目中定义shiro的过滤器(shiro的实现主要是通过filter实现)

<!-- Shiro Security filter -->
<filter>
    <filter-name>shiroFilter</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    <init-param>
    <param-name>targetFilterLifecycle</param-name>
    <param-value>true</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>shiroFilter</filter-name>
    <url-pattern>/*</url-pattern>
    <dispatcher>REQUEST</dispatcher>
</filter-mapping>

  第三步、创建一个Realm

public class UserRealm extends AuthorizingRealm {
    @Autowired
    private UserBiz biz;
    //验证用户信息,认证的实现
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String userno = (String) authenticationToken.getPrincipal();
        String password = new String((char[]) authenticationToken.getCredentials());
        Result<RcUser> result = biz.login(userno, password);
        if (result.isStatus()) {
            Session session = SecurityUtils.getSubject().getSession();
            session.setAttribute(Constants.Token.RONCOO, userno);
            RcUser user = result.getResultData();
            return new SimpleAuthenticationInfo(user.getUserNo(), user.getPassword(), getName());
        }
        return null;
    }
    //验证用户的权限,实现认证
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        String userno = (String) principals.getPrimaryPrincipal();
        Result<RcUser> result = biz.queryByUserNo(userno);
        if(result.isStatus()){
            Result<List<RcRole>> resultRole = biz.queryRoles(result.getResultData().getId());
            if(resultRole.isStatus()){
                //获取角色
                HashSet<String> roles = new HashSet<String>();
                for (RcRole rcRole : resultRole.getResultData()) {
                    roles.add(rcRole.getRoleValue());
                }
                System.out.println("角色:"+roles);
                authorizationInfo.setRoles(roles);
                //获取权限
                Result<List<RcPermission>> resultPermission = biz.queryPermissions(resultRole.getResultData());
                if(resultPermission.isStatus()){
                    HashSet<String> permissions = new HashSet<String>();
                    for (RcPermission rcPermission : resultPermission.getResultData()) {
                        permissions.add(rcPermission.getPermissionsValue());
                    }
                    System.out.println("权限:"+permissions);
                    authorizationInfo.setStringPermissions(permissions);
                }
            }
        }
        return authorizationInfo;
    }
}

  第四步、添加shiro配置

1、shiro缓存
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE xml>
<ehcache updateCheck="false" name="shiroCache">
	<!-- http://ehcache.org/ehcache.xml -->
    <defaultCache
            maxElementsInMemory="10000"
            eternal="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            overflowToDisk="false"
            diskPersistent="false"
            diskExpiryThreadIntervalSeconds="120"
            />
</ehcache>

2、在spring的core配置文件中配置shiro
<description>Shiro安全配置</description>

	<bean id="userRealm" class="com.roncoo.adminlte.controller.realm.UserRealm" /> 

	<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
		<property name="realm" ref="userRealm" />
		<property name="cacheManager" ref="shiroEhcacheManager" />
	</bean>

	<!-- Shiro 过滤器 -->
	<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
		<!-- Shiro的核心安全接口,这个属性是必须的 -->
		<property name="securityManager" ref="securityManager" />
		<!-- 身份认证失败,则跳转到登录页面的配置 -->
		<property name="loginUrl" value="/login" />
		<property name="successUrl" value="/certification" />
		<property name="unauthorizedUrl" value="/error" />
		<!-- Shiro连接约束配置,即过滤链的定义 -->
		<property name="filterChainDefinitions">
			<value>
				/login = authc
				/exit = anon
				/admin/security/list=authcBasic,perms[admin:read]
				/admin/security/save=authcBasic,perms[admin:insert]
				/admin/security/update=authcBasic,perms[admin:update]
				/admin/security/delete=authcBasic,perms[admin:delete]
			</value>
		</property>
	</bean>

	<!-- 用户授权信息Cache, 采用EhCache -->
	<bean id="shiroEhcacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
		<property name="cacheManagerConfigFile" value="classpath:ehcache/ehcache-shiro.xml" />
	</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>

  第五步、shiro退出登录的实现

        第一种方式
        /**
	 * 退出登陆操作
	 */
	@RequestMapping(value = "/exit", method = RequestMethod.GET)
	public String exit(RedirectAttributes redirectAttributes, HttpSession session) {
		session.removeAttribute(Constants.Token.RONCOO);
		SecurityUtils.getSubject().logout();
		redirectAttributes.addFlashAttribute("msg", "您已经安全退出");
		return redirect("/login");
	}

	第二种方式:在shiroFilter的约束配置中配置
	<!-- Shiro连接约束配置,即过滤链的定义 -->
	<property name="filterChainDefinitions">
		<value>
		    /exit = logout
		</value>
	</property>

  更多学习文章:http://www.roncoo.com/article/index

shiro是一款java安全框架、简单而且可以满足实际的工作需要

第一步、导入maven依赖

<!-- shiro -->
<dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-core</artifactId>
    <version>${org.apache.shiro.version}</version>
</dependency>
<dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-web</artifactId>
    <version>${org.apache.shiro.version}</version>
</dependency>
<dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-spring</artifactId>
    <version>${org.apache.shiro.version}</version>
</dependency>
<dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-ehcache</artifactId>
    <version>${org.apache.shiro.version}</version>
</dependency>

第二步、在项目中定义shiro的过滤器(shiro的实现主要是通过filter实现)

<!-- Shiro Security filter -->
<filter>
    <filter-name>shiroFilter</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    <init-param>
    <param-name>targetFilterLifecycle</param-name>
    <param-value>true</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>shiroFilter</filter-name>
    <url-pattern>/*</url-pattern>
    <dispatcher>REQUEST</dispatcher>
</filter-mapping>

第三步、创建一个Realm

public class UserRealm extends AuthorizingRealm {
    @Autowired
    private UserBiz biz;
    //验证用户信息,认证的实现
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String userno = (String) authenticationToken.getPrincipal();
        String password = new String((char[]) authenticationToken.getCredentials());
        Result<RcUser> result = biz.login(userno, password);
        if (result.isStatus()) {
            Session session = SecurityUtils.getSubject().getSession();
            session.setAttribute(Constants.Token.RONCOO, userno);
            RcUser user = result.getResultData();
            return new SimpleAuthenticationInfo(user.getUserNo(), user.getPassword(), getName());
        }
        return null;
    }
    //验证用户的权限,实现认证
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        String userno = (String) principals.getPrimaryPrincipal();
        Result<RcUser> result = biz.queryByUserNo(userno);
        if(result.isStatus()){
            Result<List<RcRole>> resultRole = biz.queryRoles(result.getResultData().getId());
            if(resultRole.isStatus()){
                //获取角色
                HashSet<String> roles = new HashSet<String>();
                for (RcRole rcRole : resultRole.getResultData()) {
                    roles.add(rcRole.getRoleValue());
                }
                System.out.println("角色:"+roles);
                authorizationInfo.setRoles(roles);
                //获取权限
                Result<List<RcPermission>> resultPermission = biz.queryPermissions(resultRole.getResultData());
                if(resultPermission.isStatus()){
                    HashSet<String> permissions = new HashSet<String>();
                    for (RcPermission rcPermission : resultPermission.getResultData()) {
                        permissions.add(rcPermission.getPermissionsValue());
                    }
                    System.out.println("权限:"+permissions);
                    authorizationInfo.setStringPermissions(permissions);
                }
            }
        }
        return authorizationInfo;
    }
}

第四步、添加shiro配置

1、shiro缓存
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE xml>
<ehcache updateCheck="false" name="shiroCache">
	<!-- http://ehcache.org/ehcache.xml -->
    <defaultCache
            maxElementsInMemory="10000"
            eternal="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            overflowToDisk="false"
            diskPersistent="false"
            diskExpiryThreadIntervalSeconds="120"
            />
</ehcache>

2、在spring的core配置文件中配置shiro
<description>Shiro安全配置</description>

	<bean id="userRealm" class="com.roncoo.adminlte.controller.realm.UserRealm" /> 

	<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
		<property name="realm" ref="userRealm" />
		<property name="cacheManager" ref="shiroEhcacheManager" />
	</bean>

	<!-- Shiro 过滤器 -->
	<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
		<!-- Shiro的核心安全接口,这个属性是必须的 -->
		<property name="securityManager" ref="securityManager" />
		<!-- 身份认证失败,则跳转到登录页面的配置 -->
		<property name="loginUrl" value="/login" />
		<property name="successUrl" value="/certification" />
		<property name="unauthorizedUrl" value="/error" />
		<!-- Shiro连接约束配置,即过滤链的定义 -->
		<property name="filterChainDefinitions">
			<value>
				/login = authc
				/exit = anon
				/admin/security/list=authcBasic,perms[admin:read]
				/admin/security/save=authcBasic,perms[admin:insert]
				/admin/security/update=authcBasic,perms[admin:update]
				/admin/security/delete=authcBasic,perms[admin:delete]
			</value>
		</property>
	</bean>

	<!-- 用户授权信息Cache, 采用EhCache -->
	<bean id="shiroEhcacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
		<property name="cacheManagerConfigFile" value="classpath:ehcache/ehcache-shiro.xml" />
	</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>

第五步、shiro退出登录的实现

        第一种方式
        /**
	 * 退出登陆操作
	 */
	@RequestMapping(value = "/exit", method = RequestMethod.GET)
	public String exit(RedirectAttributes redirectAttributes, HttpSession session) {
		session.removeAttribute(Constants.Token.RONCOO);
		SecurityUtils.getSubject().logout();
		redirectAttributes.addFlashAttribute("msg", "您已经安全退出");
		return redirect("/login");
	}

	第二种方式:在shiroFilter的约束配置中配置
	<!-- Shiro连接约束配置,即过滤链的定义 -->
	<property name="filterChainDefinitions">
		<value>
		    /exit = logout
		</value>
	</property>	
上一篇:如何读懂 Intel HEX 文件


下一篇:看看80万程序员怎么评论:程序员工资为什么这么高?