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

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

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 必不可少



  
	
		contextConfigLocation
		classpath:application.xml
	

	
	
		org.springframework.web.context.ContextLoaderListener
	
  
  
   
        shiroFilter
        org.springframework.web.filter.DelegatingFilterProxy
        
            targetFilterLifecycle
            true
        
    
    
        shiroFilter
        /*
    
    
    
	
        struts2
        org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
    
    
        struts2
        /*
      
  

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




	
	
	
	
	 
		
	
	
	
	

	
	
        
        
    
	
	
	
	
	
	
		
	
		
	
	
	
	
		
	
		
		
		
		
		
		
			
				
				/login.jsp=anon
				/login=anon
				/logout=logout
				
				
				/admin.jsp=roles[admin]
				/user.jsp=roles[user]
				
				
				/**=authc
			
		
	


四、新建自定义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;

	//一、认证 (自定义认证)
	@Override
	protected 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和user
			user.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 Setroles=new HashSet();
		
		public String getUsername() {
			return username;
		}
		public void setUsername(String username) {
			this.username = username;
		}
		public Set getRoles() {
			return roles;
		}
		public void setRoles(Set 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 来渲染视图





    
    

    
		
		
            /list.jsp
            /login.jsp
        
        
        	
        
        
    



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


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


【补充】

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


    
    

    

    


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

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

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


你可能感兴趣的:(Shiro)