当前位置: 移动技术网 > IT编程>网页制作>Html5 > 默认鉴权与自定义鉴权

默认鉴权与自定义鉴权

2018年11月01日  | 移动技术网IT编程  | 我要评论

国考试题,夕阳之约老头图片,让爱自由落地林笛儿

过滤链中定义:


[html]
<!-- 过滤链定义 --> 
        <property name="filterchaindefinitions"> 
            <value> 
                ... 
                /pages/user/create.do* = perms[user:create] 
                ... 
            </value> 
        </property> 

<!-- 过滤链定义 -->
  <property name="filterchaindefinitions">
   <value>
    ...
    /pages/user/create.do* = perms[user:create]
    ...
   </value>
  </property>
这段配置的含义是:/pages/user/create.do*这样的请求路径,需要鉴权,且需要用户有“user:create”的权限字符串。

perms是拦截器的名字,默认实现类是:org.apache.shiro.web.filter.authz.permissionsauthorizationfilter

这个过滤器会得到配置中请求路径对应的权限字符串,如“user:create”,然后到realm中查找当前用户包含的权限,具体来说是调用reaml的回调函数:


[java]
  /**
     * 鉴权回调函数,提取当事人的角色和权限
     * principals  当事人
     */ 
    protected authorizationinfo dogetauthorizationinfo( 
            principalcollection principals) { 
        //用户名  
        string username = (string) principals.fromrealm( 
                getname()).iterator().next(); 
        
        /*这些代码应该是动态从中取出的,此处写死*/ 
        if(username!=null&&username.equals("admin")){ 
            simpleauthorizationinfo info = new simpleauthorizationinfo(); 
//          info.addrole("admin");//添加一个角色,不是配置意义上的添加,而是证明该用户拥有admin角色  
            info.addstringpermission("user:create"); 
            info.addstringpermission("/pages/index.");//添加权限  
            info.addstringpermission("/pages/info.jsp");//添加权限  
            return info; 
        } 
        return null; 
    } 

 /**
  * 鉴权回调函数,提取当事人的角色和权限
  * principals  当事人
  */
    protected authorizationinfo dogetauthorizationinfo(
            principalcollection principals) {
     //用户名
        string username = (string) principals.fromrealm(
                getname()).iterator().next();
      
        /*这些代码应该是动态从数据库中取出的,此处写死*/
        if(username!=null&&username.equals("admin")){
         simpleauthorizationinfo info = new simpleauthorizationinfo();
//         info.addrole("admin");//添加一个角色,不是配置意义上的添加,而是证明该用户拥有admin角色
         info.addstringpermission("user:create");
         info.addstringpermission("/pages/index.jsp");//添加权限
         info.addstringpermission("/pages/info.jsp");//添加权限
         return info;
        }
        return null;
    }
此代码属于自定义realm——public class customrealm extends authorizingrealm

代码中我们使用的是测试数据,直接往info里面添加角色字符串和权限字符串,我们也可以从数据库中获取,这不是本节重点。

现在关键要明白securitymanager是从请求端得到应该有的权限字串,从realm得到当事人具备的角色和权限字串,然后比对,比对成功说明鉴权成功,否则鉴权失败。

 


事实上,这种配置鉴权的方式,连自定义realm都不需要,用户信息、角色信息、权限信息都可以配置:


[html]
[users] 
# user1 = sha256-hashed-hex-encoded password, role1, role2, ... 
user1 = 2bb80d537b1da3e38bd30361aa855686bde0eacd7162fef6a25fe97bf527a25b, role1, role2, ...  
[roles] 
# 'admin' role has all permissions, indicated by the wildcard '*' 
admin = * 
# the 'schwartz' role can do anything (*) with any lightsaber: 
schwartz = lightsaber:* 
# the 'goodguy' role is allowed to 'drive' (action) the winnebago (type) with 
# license plate 'eagle5' (instance specific id) 
goodguy = winnebago:drive:eagle5 

[users]
# user1 = sha256-hashed-hex-encoded password, role1, role2, ...
user1 = 2bb80d537b1da3e38bd30361aa855686bde0eacd7162fef6a25fe97bf527a25b, role1, role2, ...
[roles]
# 'admin' role has all permissions, indicated by the wildcard '*'
admin = *
# the 'schwartz' role can do anything (*) with any lightsaber:
schwartz = lightsaber:*
# the 'goodguy' role is allowed to 'drive' (action) the winnebago (type) with
# license plate 'eagle5' (instance specific id)
goodguy = winnebago:drive:eagle5
这点可以参考官方文档。

 


===================自定义鉴权=================

往往我们的项目,特别是遗留项目都会设计几张表来存储用户信息和角色信息以及权限映射信息,所以realm这块,一般要自定义。

而且通常的作法是直接用请求的url作为权限字符串的,也就是不需要url再去映射一些权限字符串,所以过滤器这块,我们可能也需要自定义。

自定义鉴权过滤器:


[java]
package javacommon.shiro; 
 
import java.io.ioexception; 
import java.util.regex.matcher; 
import java.util.regex.pattern; 
 
import javax.servlet.servletrequest; 
import javax.servlet.servletresponse; 
import javax.servlet.http.httpservletrequest; 
 
import org.apache.shiro.web.filter.authz.permissionsauthorizationfilter; 
 
/**
 * 基于url的权限判断过滤器<p>
 * 我们自动根据url产生所谓的权限字符串,这一项在shiro示例中是写在配置文件里面的,默认认为权限不可动态配置<p>
 * url举例:/user/create.do?***=***  -->权限字符串:/user/create.do
 * @author zhengwei lastmodified 2013年8月15日
 *
 */ 
public class urlpermissionsfilter extends permissionsauthorizationfilter{ 
    /**
     *@param mappedvalue 指的是在声明url时指定的权限字符串,如/user/create.do=perms[user:create].我们要动态产生这个权限字符串,所以这个配置对我们没用
     */ 
    public boolean isaccessallowed(servletrequest request, 
            servletresponse response, object mappedvalue) throws ioexception { 
         return super.isaccessallowed(request, response, buildpermissions(request)); 
    } 
    /**
     * 根据请求url产生权限字符串,这里只产生,而比对的事交给realm
     * @param request
     * @return
     */ 
    protected string[] buildpermissions(servletrequest request) { 
        string[] perms = new string[1]; 
        httpservletrequest req = (httpservletrequest) request; 
        string path = req.getservletpath(); 
        perms[0] = path;//path直接作为权限字符串  
        /*string regex = "/(.*?)/(.*?)\\.(.*)";
        if(url.matches(regex)){
            pattern pattern = pattern.compile(regex);
            matcher matcher = pattern.matcher(url);
            string controller =  matcher.group(1);
            string action = matcher.group(2);
            
        }*/ 
        return perms; 
    } 

package javacommon.shiro;

import java.io.ioexception;
import java.util.regex.matcher;
import java.util.regex.pattern;

import javax.servlet.servletrequest;
import javax.servlet.servletresponse;
import javax.servlet.http.httpservletrequest;

import org.apache.shiro.web.filter.authz.permissionsauthorizationfilter;

/**
 * 基于url的权限判断过滤器<p>
 * 我们自动根据url产生所谓的权限字符串,这一项在shiro示例中是写在配置文件里面的,默认认为权限不可动态配置<p>
 * url举例:/user/create.do?***=***  -->权限字符串:/user/create.do
 * @author zhengwei lastmodified 2013年8月15日
 *
 */
public class urlpermissionsfilter extends permissionsauthorizationfilter{
 /**
  *@param mappedvalue 指的是在声明url时指定的权限字符串,如/user/create.do=perms[user:create].我们要动态产生这个权限字符串,所以这个配置对我们没用
  */
 public boolean isaccessallowed(servletrequest request,
   servletresponse response, object mappedvalue) throws ioexception {
   return super.isaccessallowed(request, response, buildpermissions(request));
 }
 /**
  * 根据请求url产生权限字符串,这里只产生,而比对的事交给realm
  * @param request
  * @return
  */
 protected string[] buildpermissions(servletrequest request) {
  string[] perms = new string[1];
  httpservletrequest req = (httpservletrequest) request;
  string path = req.getservletpath();
  perms[0] = path;//path直接作为权限字符串
  /*string regex = "/(.*?)/(.*?)\\.(.*)";
  if(url.matches(regex)){
   pattern pattern = pattern.compile(regex);
   matcher matcher = pattern.matcher(url);
   string controller =  matcher.group(1);
   string action = matcher.group(2);
   
  }*/
  return perms;
 }
}

可以看出我们直接将请求路径作为权限字符串,过滤器会去调用realm,所以自定义realm中也要为用户添加同样格式的权限字符串


[java]
info.addstringpermission("/pages/index.jsp");//添加权限,admin可访问这个路径 

info.addstringpermission("/pages/index.jsp");//添加权限,admin可访问这个路径
最后再来看看全局filter的配置:


[html]
<!-- shiro filter 拦截器相关配置 --> 
<bean id="shirofilter" class="org.apache.shiro.spring.web.shirofilterfactorybean"> 
    ... 
    <property name="filters"> 
        <util:map> 
            <entry key="authc" value-ref="myauthenfilter" /> 
            <entry key="perms" value-ref="urlpermissionsfilter" /> 
        </util:map> 
    </property> 
    <!-- 过滤链定义 --> 
    <property name="filterchaindefinitions"> 
        <value> 
            /login.jsp = authc 
            /pages/* = authc,perms 
            /logout.do = logout 
            ... 
        </value> 
    </property> 
</bean> 
 
... 
<!-- 自定义鉴权拦截器 --> 
<bean id="urlpermissionsfilter" class="javacommon.shiro.urlpermissionsfilter" /> 

 <!-- shiro filter 拦截器相关配置 -->
 <bean id="shirofilter" class="org.apache.shiro.spring.web.shirofilterfactorybean">
  ...
  <property name="filters">
   <util:map>
    <entry key="authc" value-ref="myauthenfilter" />
    <entry key="perms" value-ref="urlpermissionsfilter" />
   </util:map>
  </property>
  <!-- 过滤链定义 -->
  <property name="filterchaindefinitions">
   <value>
    /login.jsp = authc
    /pages/* = authc,perms
    /logout.do = logout
    ...
   </value>
  </property>
 </bean>

 ...
 <!-- 自定义鉴权拦截器 -->
 <bean id="urlpermissionsfilter" class="javacommon.shiro.urlpermissionsfilter" />

 


这段配置意味着访问/pages/*都需要鉴权,而鉴权使用的是自定义的拦截器。

测试:

以admin身份登录并访问pages/info.jsp,没问题,因为它拥有这个权限。

访问pages/nb.jsp,因为这个路径没有添加到admin的权限中,所以鉴权失败,将跳转到unauthorizedurl指定的路径。

 

 

 

小节:

对于客户要求者自己管理权限,而且不需要动态配置的情况,使用默认配置法,非常简单。

当需要动态管理权限,那就要自定义realm和filter,关键在于请求url--》权限字符串,realm可返回一个用户拥有的权限字符串。

这些字符串应该能比对上。


 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网