Web登录验证之 Shiro

1、需要用到的shiro相关包

<!-- shiro begin -->  
<dependency>  
<groupId>org.apache.shiro</groupId>  
<artifactId>shiro-core</artifactId>  
<version>1.2.3</version>  
</dependency>  
<dependency>  
<groupId>org.apache.shiro</groupId>  
<artifactId>shiro-web</artifactId>  
<version>1.2.3</version>  
</dependency>  
<dependency>  
<groupId>org.apache.shiro</groupId>  
<artifactId>shiro-ehcache</artifactId>  
<version>1.2.3</version>  
</dependency>  
<dependency>  
<groupId>org.apache.shiro</groupId>  
<artifactId>shiro-spring</artifactId>  
<version>1.2.3</version>  
</dependency>  
<!-- shiro end -->  

2、首先在web.xml中添加shiro过滤器

<?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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"  
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"  
    version="2.5">  
     <display-name>abel-shiro Application</display-name>  
       
     <!-- 指定上下文配置文件 -->  
     <context-param>  
        <param-name>contextConfigLocation</param-name>  
        <param-value>  
                 classpath:applicationContext.xml  
        </param-value>  
    </context-param>  
      
    <!-- spring监听器,监听springMvc环境 -->  
    <listener>  
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
    </listener>  
      
    <!-- 压入项目路径 -->  
    <listener>  
       <listener-class>org.springframework.web.util.WebAppRootListener</listener-class>  
    </listener>  
      
    <!-- 配置Shiro过滤器,先让Shiro过滤系统接收到的请求 -->    
    <!-- 通常将这段代码中的filter-mapping放在所有filter-mapping之前,以达到shiro是第一个对web请求进行拦截过滤之目的。  
        这里的fileter-name(shiroFilter) 对应下面applicationContext.xml中的<bean id="shiroFilter" />   
        DelegatingFilterProxy会自动到Spring容器中查找名字为shiroFilter的bean并把filter请求交给它处理-->    
    <!-- 使用[/*]匹配所有请求,保证所有的可控请求都经过Shiro的过滤 -->    
    <filter>    
        <filter-name>shiroFilter</filter-name>    
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>    
        <init-param>    
            <!-- 该值缺省为false,表示生命周期由SpringApplicationContext管理,设置为true则表示由ServletContainer管理   -->  
            <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>  
    
     <!-- springMvc前置总控制器,在分发其它的控制器前都要经过这个总控制器 -->  
     <servlet>  
        <servlet-name>spring</servlet-name>  
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
        <init-param>  
            <param-name>contextConfigLocation</param-name>  
            <param-value>/WEB-INF/spring-shiro.xml</param-value>  
        </init-param>  
        <!-- 启动顺序 -->  
        <load-on-startup>1</load-on-startup>  
    </servlet>  
      
    <servlet-mapping>  
        <servlet-name>spring</servlet-name>  
        <url-pattern>/</url-pattern>  
        <!--   
        <url-pattern>/</url-pattern>  会匹配到/login这样的路径型url,不会匹配到模式为*.jsp这样的后缀型url  
        <url-pattern>/*</url-pattern> 会匹配所有url:路径型的和后缀型的url(包括/login,*.jsp,*.js和*.html等)  
         -->  
    </servlet-mapping>  
      
</web-app>  

3、shiro相关配置

<?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-4.0.xsd  
        http://www.springframework.org/schema/context  http://www.springframework.org/schema/context/spring-context-4.0.xsd"  
    default-lazy-init="true">  
  
    <description>Shiro Configuration</description>  
      
    <!-- 继承自AuthorizingRealm的自定义Realm,即指定Shiro验证用户登录的类为自定义的ShiroDbRealm.java -->    
    <bean id="systemAuthorizingRealm" class="com.abel.shiro.security.SystemAuthorizingRealm">   
        <!-- 密码加密验证方式 -->  
        <property name="credentialsMatcher">    
            <bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">    
                <property name="hashAlgorithmName" value="MD5" />  
            </bean>    
        </property>    
    </bean>   
    
    <!-- Shiro默认会使用Servlet容器的Session,可通过sessionMode属性来指定使用Shiro原生Session -->    
    <!-- 即<property name="sessionMode" value="native"/>,详细说明见官方文档 -->    
    <!-- 这里主要是设置自定义的单Realm应用,若有多个Realm,可使用'realms'属性代替 -->    
    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">    
        <property name="realm" ref="systemAuthorizingRealm"/>    
    </bean>    
    
    <!-- Shiro主过滤器本身功能十分强大,其强大之处就在于它支持任何基于URL路径表达式的、自定义的过滤器的执行 -->    
    <!-- Web应用中,Shiro可控制的Web请求必须经过Shiro主过滤器的拦截,Shiro对基于Spring的Web应用提供了完美的支持 -->    
    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">    
        <!-- Shiro的核心安全接口,这个属性是必须的 -->    
        <property name="securityManager" ref="securityManager"/>    
        <!-- 要求登录时的链接(可根据项目的URL进行替换),非必须的属性,默认会自动寻找Web工程根目录下的"/login.jsp"页面 -->    
        <property name="loginUrl" value="/login"/>    
        <!-- 登录成功后要跳转的连接 -->    
        <property name="successUrl" value="/admin/index"/>  
        <!-- 用户访问未对其授权的资源时,所显示的连接 -->    
        <!-- 若想更明显的测试此属性可以修改它的值,如unauthor.jsp,然后用[玄玉]登录后访问/admin/listUser.jsp就看见浏览器会显示unauthor.jsp -->    
        <property name="unauthorizedUrl" value="/403"/>    
          
        <!-- Shiro权限过滤过滤器定义 -->  
        <property name="filterChainDefinitions">  
            <ref bean="shiroFilterChainDefinitions"/>  
        </property>   
    </bean>    
      
    <!--   
    filterChainDefinitions参数说明,注意其验证顺序是自上而下  
    =================================================================================================  
    anon        org.apache.shiro.web.filter.authc.AnonymousFilter  
    authc       org.apache.shiro.web.filter.authc.FormAuthenticationFilter  
    authcBasic  org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter  
    perms       org.apache.shiro.web.filter.authz.PermissionsAuthorizationFilter  
    port        org.apache.shiro.web.filter.authz.PortFilter  
    rest        org.apache.shiro.web.filter.authz.HttpMethodPermissionFilter  
    roles       org.apache.shiro.web.filter.authz.RolesAuthorizationFilter  
    ssl         org.apache.shiro.web.filter.authz.SslFilter  
    user        org.apache.shiro.web.filter.authc.UserFilter  
    =================================================================================================  
    anon: 例子/admins/**=anon 没有参数,表示可以匿名使用。  
    authc: 例如/admins/user/**=authc表示需要认证(登录)才能使用,没有参数  
    roles: 例子/admins/user/**=roles[admin],参数可以写多个,多个时必须加上引号,  
                    并且参数之间用逗号分割,当有多个参数时,例如admins/user/**=roles["admin,guest"],  
                    每个参数通过才算通过,相当于hasAllRoles()方法。  
    perms: 例子/admins/user/**=perms[user:add:*],参数可以写多个,多个时必须加上引号,并且参数之间用逗号分割,  
                    例如/admins/user/**=perms["user:add:*,user:modify:*"],当有多个参数时必须每个参数都通过才通过,  
                    想当于isPermitedAll()方法。  
    rest:  例子/admins/user/**=rest[user],根据请求的方法,相当于/admins/user/**=perms[user:method] ,  
                   其中method为post,get,delete等。  
    port:  例子/admins/user/**=port[8081],当请求的url的端口不是8081是跳转到schemal://serverName:8081?queryString,  
                   其中schmal是协议http或https等,serverName是你访问的host,8081是url配置里port的端口,queryString是你访问的url里的?后面的参数。  
    authcBasic:例如/admins/user/**=authcBasic没有参数表示httpBasic认证  
    ssl:  例子/admins/user/**=ssl没有参数,表示安全的url请求,协议为https  
    user: 例如/admins/user/**=user没有参数表示必须存在用户,当登入操作时不做检查  
    注:anon,authcBasic,auchc,user是认证过滤器,  
    perms,roles,ssl,rest,port是授权过滤器  
    =================================================================================================  
    -->   
    <!-- 下面value值的第一个'/'代表的路径是相对于HttpServletRequest.getContextPath()的值来的 -->  
    <bean name="shiroFilterChainDefinitions" class="java.lang.String">  
        <constructor-arg>  
            <value>  
                /login=anon    
                /dologin=anon  
                /logout=anon  
                /getVerifyCodeImage=anon    
                /admin/channel/** = authc,perms[admin:channel]  
                /admin/content/** = authc,perms[admin:content]  
                /admin/sys/** = authc,perms[admin:sys]  
                /admin/**=authc   
            </value>  
        </constructor-arg>  
    </bean>  
    
    <!-- 保证实现了Shiro内部lifecycle函数的bean执行 -->    
    <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>    
    
    <!-- AOP式方法级权限检查,开启Shiro的注解(如@RequiresRoles,@RequiresPermissions),需借助SpringAOP扫描使用Shiro注解的类,并在必要时进行安全逻辑验证 -->    
    <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" depends-on="lifecycleBeanPostProcessor"/>    
    <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">    
        <property name="securityManager" ref="securityManager"/>    
    </bean>    
          
</beans>  

4、SystemAuthorizingRealm的实现

package com.abel.shiro.security;  
  
import java.util.List;  
  
import org.apache.shiro.SecurityUtils;  
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.authz.AuthorizationInfo;  
import org.apache.shiro.authz.SimpleAuthorizationInfo;  
import org.apache.shiro.realm.AuthorizingRealm;  
import org.apache.shiro.session.InvalidSessionException;  
import org.apache.shiro.session.Session;  
import org.apache.shiro.subject.PrincipalCollection;  
import org.apache.shiro.subject.Subject;  
import org.springframework.beans.factory.annotation.Autowired;  
  
import com.abel.shiro.Constants;  
import com.abel.shiro.model.MemberModel;  
import com.abel.shiro.model.PermissionModel;  
import com.abel.shiro.model.RoleModel;  
import com.abel.shiro.services.MemberService;  
  
/** 
 * 自定义的指定Shiro验证用户登录的类 
 * @author abel.lin 
 */  
public class SystemAuthorizingRealm extends AuthorizingRealm {  
    @Autowired  
    private MemberService memberService;  
    /** 
     * 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用 
     */  
    @Override  
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals){  
        //获取当前登录的用户名,等价于(String)principals.fromRealm(this.getName()).iterator().next()  
        String currentUsername = (String)super.getAvailablePrincipal(principals);  
        MemberModel member = memberService.getMemberByName(currentUsername);  
        if(member == null){  
            throw new AuthenticationException("msg:用户不存在。");  
        }  
        SimpleAuthorizationInfo simpleAuthorInfo = new SimpleAuthorizationInfo();  
          
        List<RoleModel> roleList = memberService.selectRoleByMemberId(member.getId());  
        List<PermissionModel> permList = memberService.selectPermissionByMemberId(member.getId());  
          
        if(roleList != null && roleList.size() > 0){  
            for(RoleModel role : roleList){  
                if(role.getRoleCode() != null){  
                    simpleAuthorInfo.addRole(role.getRoleCode());  
                }  
            }  
        }  
          
        if(permList != null && permList.size() > 0){  
            for(PermissionModel perm : permList){  
                if(perm.getCode() != null){  
                    simpleAuthorInfo.addStringPermission(perm.getCode());  
                }  
            }  
        }  
        return simpleAuthorInfo;  
          
    }  
  
      
    /** 
     * 认证回调函数, 登录时调用 
     */  
    @Override  
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {  
        //获取基于用户名和密码的令牌  
        //实际上这个authcToken是从LoginController里面currentUser.login(token)传过来的  
        UsernamePasswordToken token = (UsernamePasswordToken)authcToken;  
          
        Session session = getSession();  
        String code = (String)session.getAttribute(Constants.VALIDATE_CODE);  
        if (token.getCaptcha() == null || !token.getCaptcha().toUpperCase().equals(code)){  
            throw new AuthenticationException("msg:验证码错误, 请重试.");  
        }  
        MemberModel member = memberService.getMemberByName(token.getUsername());  
        if(member != null){  
            if(member.getIslock() !=null && member.getIslock() == 1){  
                throw new AuthenticationException("msg:该已帐号禁止登录.");  
            }  
            AuthenticationInfo authcInfo = new SimpleAuthenticationInfo(member.getLoginName(), member.getPwd(), this.getName());  
            this.setSession("currentUser", member.getLoginName());  
              
            return authcInfo;  
        }  
        return null;  
          
    }  
      
    /** 
     * 保存登录名 
     */  
    private void setSession(Object key, Object value){  
        Session session = getSession();  
        System.out.println("Session默认超时时间为[" + session.getTimeout() + "]毫秒");  
        if(null != session){  
            session.setAttribute(key, value);  
        }  
    }  
      
    private Session getSession(){  
        try{  
            Subject subject = SecurityUtils.getSubject();  
            Session session = subject.getSession(false);  
            if (session == null){  
                session = subject.getSession();  
            }  
            if (session != null){  
                return session;  
            }  
        }catch (InvalidSessionException e){  
              
        }  
        return null;  
    }  
}  

5、登录操作LoginController

 
package com.abel.shiro.controller;  
  
import java.awt.Color;  
import java.awt.image.BufferedImage;  
import java.io.IOException;  
  
import javax.imageio.ImageIO;  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  
  
import org.apache.shiro.SecurityUtils;  
import org.apache.shiro.subject.Subject;  
import org.springframework.stereotype.Controller;  
import org.springframework.web.bind.annotation.RequestMapping;  
import org.springframework.web.bind.annotation.ResponseBody;  
  
import com.abel.shiro.Constants;  
import com.abel.shiro.security.UsernamePasswordToken;  
  
/** 
 * @author abel.lin 
 */  
@Controller  
public class LoginController {  
  
    @RequestMapping("login")  
    public String login(HttpServletRequest request){  
          
        return "login";  
    }  
      
    @RequestMapping("login/auth")  
    public String doLogin(HttpServletRequest request){  
        String username = request.getParameter("loginname");  
        String pwd = request.getParameter("password");  
        String captcha = request.getParameter("captcha");  
        UsernamePasswordToken token = new UsernamePasswordToken(username, pwd, captcha);   
        Subject currentUser = SecurityUtils.getSubject();   
        currentUser.login(token);    
        return "redirect:/admin/index";  
    }  
      
    @ResponseBody  
    @RequestMapping("admin/index")  
    public String index(HttpServletRequest request){  
        return "wellcome index";  
    }  
    @ResponseBody  
    @RequestMapping("admin/channel")  
    public String channel(HttpServletRequest request){  
        return "wellcome channel";  
    }  
    @ResponseBody  
    @RequestMapping("admin/content")  
    public String content(HttpServletRequest request){  
        return "wellcome content";  
    }  
    @ResponseBody  
    @RequestMapping("admin/sys")  
    public String sys(HttpServletRequest request){  
        return "wellcome sys";  
    }  
      
    @RequestMapping("logout")  
    public String logout(HttpServletRequest request){  
        SecurityUtils.getSubject().logout();    
        return "redirect:/login";  
    }  
      
    /**  
     * 获取验证码图片和文本(验证码文本会保存在HttpSession中)  
     */    
    @RequestMapping("/genCaptcha")    
    public void genCaptcha(HttpServletRequest request, HttpServletResponse response) throws IOException {    
        //设置页面不缓存    
        response.setHeader("Pragma", "no-cache");    
        response.setHeader("Cache-Control", "no-cache");    
        response.setDateHeader("Expires", 0);    
        String verifyCode = VerifyCodeUtil.generateTextCode(VerifyCodeUtil.TYPE_NUM_ONLY, 4, null);    
        //将验证码放到HttpSession里面    
        request.getSession().setAttribute(Constants.VALIDATE_CODE, verifyCode);    
        System.out.println("本次生成的验证码为[" + verifyCode + "],已存放到HttpSession中");    
        //设置输出的内容的类型为JPEG图像    
        response.setContentType("image/jpeg");    
        BufferedImage bufferedImage = VerifyCodeUtil.generateImageCode(verifyCode, 90, 30, 5, true, Color.WHITE, null, null);    
        //写给浏览器    
        ImageIO.write(bufferedImage, "JPEG", response.getOutputStream());    
    }    
      
}  

6、登录页面

<!DOCTYPE html>  
<html>  
<head>  
<meta charset="UTF-8">  
<title>Shiro login</title>  
</head>  
<body>  
<form action="/login/auth" method="post">  
<div><label>用户名</label><input type="text" name="loginname" /></div>  
<div><label>密 码</label><input type="text" name="password" /></div>  
<div><label>验证码</label><input type="text" name="captcha" /><img src="/genCaptcha" /></div>  
<div><input type="submit" value="登录" /></div>  
</form>  
</body>  
</html>  

**************************************************************************************************

原文点击此处

原文地址:https://www.cnblogs.com/kuoAT/p/8440703.html