一、Shiro+Spring+Struts2集成演示权限控制Demo示例

来源:互联网 发布:javiewer差不多的软件 编辑:程序博客网 时间:2024/05/29 14:48

一、千里之行,始于新建工程,导入依赖包

asm-3.3.jar
asm-commons-3.3.jar
asm-tree-3.3.jar
com.springsource.net.sf.cglib-2.2.0.jar
com.springsource.org.aopalliance-1.0.0.jar
com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar
commons-fileupload-1.3.jar
commons-io-2.0.1.jar
commons-lang3-3.1.jar
commons-logging-1.1.3.jar
ehcache-core-2.4.3.jar
freemarker-2.3.19.jar
javassist-3.11.0.GA.jar
log4j-1.2.15.jar
log4j-1.2.17.jar
ognl-3.0.6.jar
shiro-aspectj-1.2.2.jar
shiro-cas-1.2.2.jar
shiro-core-1.2.2.jar
shiro-ehcache-1.2.2.jar
shiro-guice-1.2.2.jar
shiro-quartz-1.2.2.jar
shiro-spring-1.2.2.jar
shiro-tools-hasher-1.2.2-cli.jar
shiro-web-1.2.2.jar
slf4j-api-1.6.1.jar
slf4j-log4j12-1.6.1.jar
spring-aop-4.0.0.RELEASE.jar
spring-aspects-4.0.0.RELEASE.jar
spring-beans-4.0.0.RELEASE.jar
spring-context-4.0.0.RELEASE.jar
spring-core-4.0.0.RELEASE.jar
spring-expression-4.0.0.RELEASE.jar
spring-jdbc-4.0.0.RELEASE.jar
spring-orm-4.0.0.RELEASE.jar
spring-tx-4.0.0.RELEASE.jar
spring-web-4.0.0.RELEASE.jar
spring-webmvc-4.0.0.RELEASE.jar
struts2-core-2.3.15.3.jar
struts2-spring-plugin-2.3.15.3.jar
xwork-core-2.3.15.3.jar

二、配置web.xml 必不可少

<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">  <!-- 1.配置springIOC容器监听器 --><context-param><param-name>contextConfigLocation</param-name><param-value>classpath:application.xml</param-value></context-param><!-- Bootstraps the root web application context before servlet initialization --><listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener>    <!--2.配置shiro过滤器  -->   <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>    </filter-mapping>        <!--3.配置struts2过滤器  --><filter>        <filter-name>struts2</filter-name>        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>    </filter>    <filter-mapping>        <filter-name>struts2</filter-name>        <url-pattern>/*</url-pattern>    </filter-mapping>    </web-app>

三、配置spring配置文件application.xml更为重要!

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"><!-- 1.配置要扫描的包 --><context:component-scan base-package="com.tan.shiro"></context:component-scan><!--2.配置CacheManager实例:管理Shiro相关缓存操作  --><bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager"> <property name="cacheManagerConfigFile" value="classpath:ehcache-shiro.xml"></property></bean><!--3.配置realm实例,实际的认证和授权都是由Realm实例来完成的!  --><bean id="myRealm" class="com.tan.shiro.realm.MyRealm"></bean><!-- 4.配置 SecurityManager 实例. SecurityManager 是 Shiro 最核心的组件 --><bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">        <property name="cacheManager" ref="cacheManager"/>        <property name="realm" ref="myRealm"/>    </bean><!--5.配置bean的后置处理器来自动调用Shiro中的bean的init和destroy方法。  --><bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"></bean><!--6.配置使shiro注解起作用的bean,需要放在 lifecycleBeanPostProcessor后面 --><bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" depends-on="lifecycleBeanPostProcessor"></bean><bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor"><property name="securityManager" ref="securityManager"></property></bean><!--7.配置哪些页面需要被拦截,以及访问这些页面所需的权限 。该bean中的id 属性值必须和 web.xml 文件中配置的 filter 的 filter-name 值一致--><bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"><property name="securityManager" ref="securityManager"></property><!--①配置登陆页面  --><property name="loginUrl" value="/login.jsp"></property><property name="successUrl" value="/list.jsp"></property><property name="unauthorizedUrl" value="/unauthorize.jsp"></property><!--②配置需要被拦截的资源 以及访问权限 --><property name="filterChainDefinitions"><value><!-- anon: 表示匿名的, 即任何人都可以访问 -->/login.jsp=anon/login=anon/logout=logout<!--③设置访问具体资源的权限  -->/admin.jsp=roles[admin]/user.jsp=roles[user]<!-- authc 表示必须经过认证之后才可以访问的页面 -->/**=authc</value></property></bean></beans>


四、新建自定义Realm来实现自定义的认证和授权

package com.tan.shiro.realm;import java.io.Serializable;import java.util.HashSet;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.IncorrectCredentialsException;import org.apache.shiro.authc.LockedAccountException;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;public class MyRealm extends AuthorizingRealm implements Serializable {private static final long serialVersionUID = 1L;//一、认证 (自定义认证)@Overrideprotected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken arg0) throws AuthenticationException {//强转为UsernamePasswordToken类型UsernamePasswordToken token=(UsernamePasswordToken)arg0; //获取用户名和密码(密码要转为字符串类型)String username = token.getUsername();String password = new String(token.getPassword());//测试一下,看是否得到了用户名和密码 System.out.println("username: " + username + ", password: " + password);//模拟查询数据库进行登录操作 if("a".equals(username)){ throw new UnknownAccountException("没有这个账号");  } if("a".equals(password)){ throw new IncorrectCredentialsException("密码错误");  } if("b".equals(username)){ throw new LockedAccountException("账号被锁定!");  } //利用新建的类来创建对象 ShiroUser user=new ShiroUser(); user.setUsername(username); //将页面中的username值设置进去  //模拟设置权限部分:要分别来判断if("admin".equals(username)){//如果用户名为:admin,则为其增加2个角色 admin和useruser.getRoles().add("admin");user.getRoles().add("user");}else if("user".equals(username)){//如果用户名为:user,则为其增加user角色user.getRoles().add("user");}return new SimpleAuthenticationInfo(user, password,getName());}//二、授权(自定义) @Override    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {//arg0.getPrimaryPrincipal(): 实际上是在认证时返回的 SimpleAuthenticationInfo 的第一个参数!        Object principal = arg0.getPrimaryPrincipal();        ShiroUser user = (ShiroUser) principal;        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(user.getRoles());        return info;    } //新建一个类定义用户角色和权限class ShiroUser implements Serializable{private static final long serialVersionUID = 1L;private String username;private Set<String>roles=new HashSet<String>();public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public Set<String> getRoles() {return roles;}public void setRoles(Set<String> roles) {this.roles = roles;}}}


五、利用Struts2新建Controller来控制登陆

package com.tan.shiro.action;import org.apache.shiro.authc.AuthenticationException;import org.apache.shiro.SecurityUtils;import org.apache.shiro.authc.IncorrectCredentialsException;import org.apache.shiro.authc.LockedAccountException;import org.apache.shiro.authc.UnknownAccountException;import org.apache.shiro.authc.UsernamePasswordToken;import org.apache.shiro.subject.Subject;import org.springframework.context.annotation.Scope;import org.springframework.stereotype.Controller;@Controller@Scope("prototype")public class LoginAction {    private String username;    private String password;     public void setUsername(String username) {        this.username = username;    }     public void setPassword(String password) {        this.password = password;    }     public String login(){         System.out.println("[login...]");                 //1.获取当前的用户         Subject currentUser = SecurityUtils.getSubject();         //2.把登录信息封装为一个 UsernamePasswordToken 对象         UsernamePasswordToken token=new UsernamePasswordToken(this.username,this.password);         //3.设置"记住我"功能         token.setRememberMe(true);            try {                // *登录操作!                currentUser.login(token);            } catch (UnknownAccountException uae) {                System.out.println("用户名不存在: " + uae);                return "input";            } catch (IncorrectCredentialsException ice) {                System.out.println("用户名存在,但密码和用户名不匹配: " + ice);                return "input";            } catch (LockedAccountException lae) {                System.out.println("用户被锁定: " + lae);                return "input";            } catch (AuthenticationException ae) {                System.out.println("其他异常: " + ae);                return "input";            }          return "success";     }}

六、配置struts.xml 来渲染视图

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE struts PUBLIC"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN""http://struts.apache.org/dtds/struts-2.3.dtd"><struts>    <constant name="struts.enable.DynamicMethodInvocation" value="false" />    <constant name="struts.devMode" value="true" />    <package name="default" namespace="/" extends="struts-default"><action name="login" class="loginAction" method="login">            <result>/list.jsp</result>            <result name="input">/login.jsp</result>        </action>        <action name="page" class="loginAction" method="getPage">        <result name="success"></result>        </action>            </package></struts>


七、在webContent下新建几个简单的跳转页面


     admin.jsp  | list.jsp  |  login.jsp  |user.jsp | unauthorize.jsp


【补充】

  ehcache-shiro.xml文件可以从源码中获取,为了大家方便还是粘出来O(∩_∩)O~

<ehcache>    <diskStore path="java.io.tmpdir/shiro-spring-sample"/>    <defaultCache            maxElementsInMemory="10000"            eternal="false"            timeToIdleSeconds="120"            timeToLiveSeconds="120"            overflowToDisk="false"            diskPersistent="false"            diskExpiryThreadIntervalSeconds="120"            />    <cache name="shiro-activeSessionCache"           maxElementsInMemory="10000"           eternal="true"           overflowToDisk="true"           diskPersistent="true"           diskExpiryThreadIntervalSeconds="600"/>    <cache name="org.apache.shiro.realm.SimpleAccountRealm.authorization"           maxElementsInMemory="100"           eternal="false"           timeToLiveSeconds="600"           overflowToDisk="false"/></ehcache>


   当然,本人也有很多不明白的地方,毫无保留粘出来给大家分享,如果有什么意见尽管提出!

这个Shiro框架着实很强大,能将权限级别控制到方法上,是不是更加细粒度的权限控制呢?

    下节继续探讨更加深入的权限控制以及使用shiro注解,欢迎拍砖指正!


0 1