Shiro权限验证框架

转载自:https://blog.csdn.net/qq_33556185/article/details/51579680

一、什么是Shiro 
Apache Shiro是一个强大易用的Java安全框架,提供了认证、授权、加密和会话管理等功能: 

  • 认证 - 用户身份识别,常被称为用户“登录”;
  • 授权 - 访问控制;
  • 密码加密 - 保护或隐藏数据防止被偷窥;
  • 会话管理 - 每用户相关的时间敏感的状态。

对于任何一个应用程序,Shiro都可以提供全面的安全管理服务。并且相对于其他安全框架,Shiro要简单的多。

二、Shiro的架构介绍 
首先,来了解一下Shiro的三个核心组件:Subject, SecurityManager 和 Realms. 如下图:

Subject:主体,代表了当前“用户”,这个用户不一定是一个具体的人,与当前应用交互的任何东西都是Subject,如网络爬虫,机器人等;即一个抽象概念;所有Subject都绑定到SecurityManager,与Subject的所有交互都会委托给SecurityManager;可以把Subject认为是一个门面;SecurityManager才是实际的执行者;

SecurityManager:安全管理器;即所有与安全有关的操作都会与SecurityManager交互;且它管理着所有Subject;可以看出它是Shiro的核心,它负责与后边介绍的其他组件进行交互,如果学习过SpringMVC,你可以把它看成DispatcherServlet前端控制器;

Realm:域,Shiro从从Realm获取安全数据(如用户、角色、权限),就是说SecurityManager要验证用户身份,那么它需要从Realm获取相应的用户进行比较以确定用户身份是否合法;也需要从Realm得到用户相应的角色/权限进行验证用户是否能进行操作;可以把Realm看成DataSource,即安全数据源。

Shiro完整架构图: 

第一步:配置shiro.xml文件

shiro.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:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/beans   
    http://www.springframework.org/schema/beans/spring-beans-4.2.xsd   
    http://www.springframework.org/schema/tx   
    http://www.springframework.org/schema/tx/spring-tx-4.2.xsd  
    http://www.springframework.org/schema/context  
    http://www.springframework.org/schema/context/spring-context-4.2.xsd  
    http://www.springframework.org/schema/mvc  
    http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd">
	 <!-- Shiro Filter 拦截器相关配置 -->  
    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">  
        <!-- securityManager -->  
        <property name="securityManager" ref="securityManager" />  
        <!-- 登录路径 -->  
        <property name="loginUrl" value="/toLogin" />  
        <!-- 用户访问无权限的链接时跳转此页面  -->  
        <property name="unauthorizedUrl" value="/unauthorizedUrl.jsp" />  
        <!-- 过滤链定义 -->  
        <property name="filterChainDefinitions">  
            <value>  
            	/loginin=anon
            	/toLogin=anon
            	/css/**=anon 
                /html/**=anon 
                /images/**=anon
                /js/**=anon 
                /upload/**=anon 
                <!-- /userList=roles[admin] -->
                /userList=authc,perms[/userList]
                /toDeleteUser=authc,perms[/toDeleteUser]
                /** = authc
             </value>  
        </property>  
    </bean>  
  
    <!-- securityManager -->  
    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">  
        <property name="realm" ref="myRealm" />  
    </bean>  
    <!-- 自定义Realm实现 --> 
    <bean id="myRealm" class="com.core.shiro.realm.CustomRealm" />  
    
    <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" />
    
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
	   <property name="prefix" value="/"/>  
	   <property name="suffix" value=".jsp"></property>  
	</bean>
	
</beans>  

anno代表不需要授权即可访问,对于静态资源,访问权限都设置为anno

authc表示需要登录才可访问

/userList=roles[admin]的含义是要访问/userList需要有admin这个角色,如果没有此角色访问此URL会返回无授权页面

/userList=authc,perms[/userList]的含义是要访问/userList需要有/userList的权限,要是没分配此权限访问此URL会返回无授权页面

<bean id="myRealm" class="com.core.shiro.realm.CustomRealm" /> 

第二步:在web.xml文件里加载shiro.xml

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            classpath*:/spring/spring-common.xml,
            classpath*:/spring/shiro.xml
        </param-value>
    </context-param>

第三步:配置shiroFilter,所有请求都要先进shiro的代理类

     <!--
       DelegatingFilterProxy类是一个代理类,所有的请求都会首先发到这个filter代理
                     然后再按照"filter-name"委派到spring中的这个bean。
                     在Spring中配置的bean的name要和web.xml中的<filter-name>一样.
	   targetFilterLifecycle,是否由spring来管理bean的生命周期,设置为true有个好处,可以调用spring后续的bean
	-->
    <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>  

第四步:自定义realm

package com.core.shiro.realm;
 
import java.util.List;
import javax.annotation.Resource;
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.springframework.util.StringUtils;
import com.core.shiro.dao.IPermissionDao;
import com.core.shiro.dao.IRoleDao;
import com.core.shiro.dao.IUserDao;
import com.core.shiro.entity.Permission;
import com.core.shiro.entity.Role;
import com.core.shiro.entity.User;
public class CustomRealm extends AuthorizingRealm{  
    @Resource
    private IUserDao userDao;
    @Resource
    private IPermissionDao permissionDao;
    @Resource
    private IRoleDao roleDao;
    
    /**
     * 添加角色
     * @param username
     * @param info
     */
    private void addRole(String username, SimpleAuthorizationInfo info) {
    	List<Role> roles = roleDao.findByUser(username);
		if(roles!=null&&roles.size()>0){
			for (Role role : roles) {
			    info.addRole(role.getRoleName());
			}
		}
    }
 
    /**
     * 添加权限
     * @param username
     * @param info
     * @return
     */
    private SimpleAuthorizationInfo addPermission(String username,SimpleAuthorizationInfo info) {
		List<Permission> permissions = permissionDao.findPermissionByName(username);
		for (Permission permission : permissions) {
		    info.addStringPermission(permission.getUrl());//添加权限  
		}
		return info;  
    }  
  
    
    /**
     * 获取授权信息
     */
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {  
        //用户名  
        String username = (String) principals.fromRealm(getName()).iterator().next(); 
        //根据用户名来添加相应的权限和角色
        if(!StringUtils.isEmpty(username)){
            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
            addPermission(username,info);
            addRole(username, info);
            return info;
        }
        return null;  
    }
 
   
   /** 
    * 登录验证 
    */  
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken ) throws AuthenticationException {  
        //令牌——基于用户名和密码的令牌  
        UsernamePasswordToken token = (UsernamePasswordToken) authcToken;  
        //令牌中可以取出用户名
        String accountName = token.getUsername();
        //让shiro框架去验证账号密码
        if(!StringUtils.isEmpty(accountName)){
            User user = userDao.findUser(accountName);
            if(user != null){
        	return new SimpleAuthenticationInfo(user.getUserName(), user.getPassword(), getName());
            }
        }
        
        return null;
    }  
  
}  

第五步:控制层代码

package com.core.shiro.controller;
 
import javax.servlet.http.HttpServletRequest;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class ShiroAction {
    @RequestMapping("loginin")
    public String login(HttpServletRequest request){
         //当前Subject  
         Subject currentUser = SecurityUtils.getSubject();  
         //加密(md5+盐),返回一个32位的字符串小写
         String salt="("+request.getParameter("username")+")";  
         String md5Pwd=new Md5Hash(request.getParameter("password"),salt).toString();
         //传递token给shiro的realm
         UsernamePasswordToken token = new UsernamePasswordToken(request.getParameter("username"),md5Pwd);  
         try {  
             currentUser.login(token); 
             return "welcome";
         
         } catch (AuthenticationException e) {//登录失败  
             request.setAttribute("msg", "用户名和密码错误");  
         } 
            return "login";
    }
    @RequestMapping("toLogin")
    public String toLogin(){
         return "login";
    }
}
 

第六步:login页面 略

     login请求调用currentUser.login之后,shiro会将token传递给自定义realm,此时realm会先调用doGetAuthenticationInfo(AuthenticationToken authcToken )登录验证的方法,验证通过后会接着调用 doGetAuthorizationInfo(PrincipalCollection principals)获取角色和权限的方法(授权),最后返回视图。   

     当其他请求进入shiro时,shiro会调用doGetAuthorizationInfo(PrincipalCollection principals)去获取授权信息,若是没有权限或角色,会跳转到未授权页面,若有权限或角色,shiro会放行,ok,此时进入真正的请求方法……

到此shiro的认证及授权便完成了。

猜你喜欢

转载自blog.csdn.net/weixin_42038771/article/details/82528484