zoukankan      html  css  js  c++  java
  • 详解登录认证及授权--Shiro系列(一)

    Apache Shiro 是一个强大而灵活的开源安全框架,它干净利落地处理身份认证,授权,企业会话管理和加密。
    Apache Shiro 的首要目标是易于使用和理解。安全有时候是很复杂的,甚至是痛苦的,但它没有必要这样。框架应该尽可能掩盖复杂的地方,露出一个干净而直观的 API,来简化开发人员在使他们的应用程序安全上的努力。
    以下是你可以用 Apache Shiro 所做的事情:
    验证用户来核实他们的身份
    对用户执行访问控制,如:
    判断用户是否被分配了一个确定的安全角色。
    判断用户是否被允许做某事。
    在任何环境下使用 Session API,即使没有 Web 或 EJB 容器。
    在身份验证,访问控制期间或在会话的生命周期,对事件作出反应。
    聚集一个或多个用户安全数据的数据源,并作为一个单一的复合用户“视图”。

    启用单点登录(SSO)功能。

    并发登录管理(一个账号多人登录作踢人操作)。

    为没有关联到登录的用户启用"Remember Me"服务。

    以及更多——全部集成到紧密结合的易于使用的 API 中。

    目前Java领域主流的安全框架有SpringSecurity和Shiro,相比于SpringSecurity,Shiro轻量化,简单容易上手,且不局限于Java和Spring;SpringSecurity太笨重了,难以上手,且只能在Spring里用,所以博主极力推荐Shiro。

    spring集成shiro要用到shiro-all-1.2.4.jar

    jar包下载地址:http://download.csdn.net/detail/qq_33556185/9540257

    第一步:配置shiro.xml文件

    shiro.xml配置文件代码:

    [html] view plain copy
     
     在CODE上查看代码片派生到我的代码片
    1. <?xml version="1.0" encoding="UTF-8"?>  
    2. <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"  
    3.     xmlns:mvc="http://www.springframework.org/schema/mvc"  
    4.     xsi:schemaLocation="http://www.springframework.org/schema/beans     
    5.     http://www.springframework.org/schema/beans/spring-beans-4.2.xsd     
    6.     http://www.springframework.org/schema/tx     
    7.     http://www.springframework.org/schema/tx/spring-tx-4.2.xsd    
    8.     http://www.springframework.org/schema/context    
    9.     http://www.springframework.org/schema/context/spring-context-4.2.xsd    
    10.     http://www.springframework.org/schema/mvc    
    11.     http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd">  
    12.      <!-- Shiro Filter 拦截器相关配置 -->    
    13.     <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">    
    14.         <!-- securityManager -->    
    15.         <property name="securityManager" ref="securityManager" />    
    16.         <!-- 登录路径 -->    
    17.         <property name="loginUrl" value="/toLogin" />    
    18.         <!-- 用户访问无权限的链接时跳转此页面  -->    
    19.         <property name="unauthorizedUrl" value="/unauthorizedUrl.jsp" />    
    20.         <!-- 过滤链定义 -->    
    21.         <property name="filterChainDefinitions">    
    22.             <value>    
    23.                 /loginin=anon  
    24.                 /toLogin=anon  
    25.                 /css/**=anon   
    26.                 /html/**=anon   
    27.                 /images/**=anon  
    28.                 /js/**=anon   
    29.                 /upload/**=anon   
    30.                 <!-- /userList=roles[admin] -->  
    31.                 /userList=authc,perms[/userList]  
    32.                 /toDeleteUser=authc,perms[/toDeleteUser]  
    33.                 /** = authc  
    34.              </value>    
    35.         </property>    
    36.     </bean>    
    37.     
    38.     <!-- securityManager -->    
    39.     <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">    
    40.         <property name="realm" ref="myRealm" />    
    41.     </bean>    
    42.     <!-- 自定义Realm实现 -->   
    43.     <bean id="myRealm" class="com.core.shiro.realm.CustomRealm" />    
    44.       
    45.     <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" />  
    46.       
    47.     <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">    
    48.        <property name="prefix" value="/"/>    
    49.        <property name="suffix" value=".jsp"></property>    
    50.     </bean>  
    51.       
    52. </beans>    

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

    authc表示需要登录才可访问

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

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

    [html] view plain copy
     
     在CODE上查看代码片派生到我的代码片
    1. <bean id="myRealm" class="com.core.shiro.realm.CustomRealm" />   

    这个是业务对象,需要我们去实现。

    第二步:在web.xml文件里加载shiro.xml,和加载其他配置文件是一样的,就不多说了

    [html] view plain copy
     
     在CODE上查看代码片派生到我的代码片
    1. <context-param>  
    2.     <param-name>contextConfigLocation</param-name>  
    3.     <param-value>  
    4.         classpath*:/spring/spring-common.xml,  
    5.         classpath*:/spring/shiro.xml  
    6.     </param-value>  
    7. </context-param>  

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

    [html] view plain copy
     
     在CODE上查看代码片派生到我的代码片
    1.     <!--  
    2.       DelegatingFilterProxy类是一个代理类,所有的请求都会首先发到这个filter代理  
    3.                     然后再按照"filter-name"委派到spring中的这个bean。  
    4.                     在Spring中配置的bean的name要和web.xml中的<filter-name>一样.  
    5.    targetFilterLifecycle,是否由spring来管理bean的生命周期,设置为true有个好处,可以调用spring后续的bean  
    6. -->  
    7.    <filter>    
    8.     <filter-name>shiroFilter</filter-name>    
    9.     <filter-class>    
    10.         org.springframework.web.filter.DelegatingFilterProxy    
    11.     </filter-class>    
    12.          <init-param>    
    13.     <param-name>targetFilterLifecycle</param-name>    
    14.     <param-value>true</param-value>    
    15.     </init-param>    
    16.   </filter>    
    17.   
    18. <filter-mapping>    
    19.     <filter-name>shiroFilter</filter-name>    
    20.     <url-pattern>/*</url-pattern>    
    21. </filter-mapping>    

    第四步:自定义realm

    [java] view plain copy
     
     在CODE上查看代码片派生到我的代码片
    1. package com.core.shiro.realm;  
    2.   
    3. import java.util.List;  
    4. import javax.annotation.Resource;  
    5. import org.apache.shiro.authc.AuthenticationException;  
    6. import org.apache.shiro.authc.AuthenticationInfo;  
    7. import org.apache.shiro.authc.AuthenticationToken;  
    8. import org.apache.shiro.authc.SimpleAuthenticationInfo;  
    9. import org.apache.shiro.authc.UsernamePasswordToken;  
    10. import org.apache.shiro.authz.AuthorizationInfo;  
    11. import org.apache.shiro.authz.SimpleAuthorizationInfo;  
    12. import org.apache.shiro.realm.AuthorizingRealm;  
    13. import org.apache.shiro.subject.PrincipalCollection;  
    14. import org.springframework.util.StringUtils;  
    15. import com.core.shiro.dao.IPermissionDao;  
    16. import com.core.shiro.dao.IRoleDao;  
    17. import com.core.shiro.dao.IUserDao;  
    18. import com.core.shiro.entity.Permission;  
    19. import com.core.shiro.entity.Role;  
    20. import com.core.shiro.entity.User;  
    21. public class CustomRealm extends AuthorizingRealm{    
    22.     @Resource  
    23.     private IUserDao userDao;  
    24.     @Resource  
    25.     private IPermissionDao permissionDao;  
    26.     @Resource  
    27.     private IRoleDao roleDao;  
    28.       
    29.     /** 
    30.      * 添加角色 
    31.      * @param username 
    32.      * @param info 
    33.      */  
    34.     private void addRole(String username, SimpleAuthorizationInfo info) {  
    35.         List<Role> roles = roleDao.findByUser(username);  
    36.         if(roles!=null&&roles.size()>0){  
    37.             for (Role role : roles) {  
    38.                 info.addRole(role.getRoleName());  
    39.             }  
    40.         }  
    41.     }  
    42.   
    43.     /** 
    44.      * 添加权限 
    45.      * @param username 
    46.      * @param info 
    47.      * @return 
    48.      */  
    49.     private SimpleAuthorizationInfo addPermission(String username,SimpleAuthorizationInfo info) {  
    50.         List<Permission> permissions = permissionDao.findPermissionByName(username);  
    51.         for (Permission permission : permissions) {  
    52.             info.addStringPermission(permission.getUrl());//添加权限    
    53.         }  
    54.         return info;    
    55.     }    
    56.     
    57.       
    58.     /** 
    59.      * 获取授权信息 
    60.      */  
    61.     protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {    
    62.         //用户名    
    63.         String username = (String) principals.fromRealm(getName()).iterator().next();   
    64.         //根据用户名来添加相应的权限和角色  
    65.         if(!StringUtils.isEmpty(username)){  
    66.             SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();  
    67.             addPermission(username,info);  
    68.             addRole(username, info);  
    69.             return info;  
    70.         }  
    71.         return null;    
    72.     }  
    73.   
    74.      
    75.    /**  
    76.     * 登录验证  
    77.     */    
    78.     protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken ) throws AuthenticationException {    
    79.         //令牌——基于用户名和密码的令牌    
    80.         UsernamePasswordToken token = (UsernamePasswordToken) authcToken;    
    81.         //令牌中可以取出用户名  
    82.         String accountName = token.getUsername();  
    83.         //让shiro框架去验证账号密码  
    84.         if(!StringUtils.isEmpty(accountName)){  
    85.             User user = userDao.findUser(accountName);  
    86.             if(user != null){  
    87.             return new SimpleAuthenticationInfo(user.getUserName(), user.getPassword(), getName());  
    88.             }  
    89.         }  
    90.           
    91.         return null;  
    92.     }    
    93.     
    94. }    

    第五步:控制层代码

    [java] view plain copy
     
     在CODE上查看代码片派生到我的代码片
    1. package com.core.shiro.controller;  
    2.   
    3. import javax.servlet.http.HttpServletRequest;  
    4. import org.apache.shiro.SecurityUtils;  
    5. import org.apache.shiro.authc.AuthenticationException;  
    6. import org.apache.shiro.authc.UsernamePasswordToken;  
    7. import org.apache.shiro.crypto.hash.Md5Hash;  
    8. import org.apache.shiro.subject.Subject;  
    9. import org.springframework.stereotype.Controller;  
    10. import org.springframework.web.bind.annotation.RequestMapping;  
    11. @Controller  
    12. public class ShiroAction {  
    13.     @RequestMapping("loginin")  
    14.     public String login(HttpServletRequest request){  
    15.          //当前Subject    
    16.          Subject currentUser = SecurityUtils.getSubject();    
    17.          //加密(md5+盐),返回一个32位的字符串小写  
    18.          String salt="("+request.getParameter("username")+")";    
    19.          String md5Pwd=new Md5Hash(request.getParameter("password"),salt).toString();  
    20.          //传递token给shiro的realm  
    21.          UsernamePasswordToken token = new UsernamePasswordToken(request.getParameter("username"),md5Pwd);    
    22.          try {    
    23.              currentUser.login(token);   
    24.              return "welcome";  
    25.            
    26.          } catch (AuthenticationException e) {//登录失败    
    27.              request.setAttribute("msg", "用户名和密码错误");    
    28.          }   
    29.             return "login";  
    30.     }  
    31.     @RequestMapping("toLogin")  
    32.     public String toLogin(){  
    33.          return "login";  
    34.     }  
    35. }  

    第六步:login页面 略

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

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

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

    http://blog.csdn.net/qq_33556185/article/details/51579680

  • 相关阅读:
    wnmpa或lnmpa 服务器搭建和原理
    windows 桌面图标 隐藏 小盾牌标志
    C# 执行 CMD 终极稳定解决方案
    比较两个object是否相等
    Microsoft Store 加载失败
    ORA-12514: TNS:监听程序当前无法识别连接描述符中请求的服务
    Win10安装gcc、g++、make
    通过proxifier实现酸酸乳全局代理
    C# 字母转数字
    html中设置锚点定位的几种常见方法(#号定位)
  • 原文地址:https://www.cnblogs.com/chen110xi/p/5690863.html
Copyright © 2011-2022 走看看