关于spring mvc + shiro 的登陆认证

来源:互联网 发布:太极线指标软件 编辑:程序博客网 时间:2024/06/06 17:56

简单介绍一下shiro 是apache 下的一个框架,其目的在于精简系统登陆认证和权限控制的开发。更好的维护系统的安全性。

在项目已经搭建好的前提下:
1.首先准备shiro 的相关jar 包

这里写图片描述

当然也可以用一个包来代替上面所有的包shiro-all.jar
加载build path 加载到项目中去

  1. 在web.xml中配置filter 拦截器
<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> 

3.创建applicationContext-shiro.xml 要使这个文件在web.xml中加载
这里写图片描述

4.配置applicationContext-shiro.xml 文件

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"    xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context"    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:jdbc="http://www.springframework.org/schema/jdbc"    xsi:schemaLocation="    http://www.springframework.org/schema/beans    http://www.springframework.org/schema/beans/spring-beans.xsd    http://www.springframework.org/schema/aop    http://www.springframework.org/schema/aop/spring-aop.xsd    http://www.springframework.org/schema/tx    http://www.springframework.org/schema/tx/spring-tx-3.0.xsd    http://www.springframework.org/schema/jdbc    http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd    http://www.springframework.org/schema/context    http://www.springframework.org/schema/context/spring-context-3.0.xsd" default-lazy-init="false"> <!-- Root Context: defines shared resources visible to all other web components -->    <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"></bean>        <!-- 缓存管理 -->          <bean id="cacheManager" class="org.apache.shiro.cache.MemoryConstrainedCacheManager"></bean>          <!--登陆验证验证 -->        <bean id="shiroLocalRealm" class="com.model.interceptor.ShiroLocalRealm" />        <!-- Shiro安全管理器 -->          <bean id="securityManager"class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">          <!-- 本地认证 -->        <property name="realm" ref="shiroLocalRealm" />         <property name="cacheManager" ref="cacheManager"></property>          </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"></property>              <!-- 要求登录时的链接(登录页面地址),非必须的属性,默认会自动寻找Web工程根目录下的"/login.jsp"页面 -->              <property name="loginUrl" value="/login.jsp"></property>              <!-- 登录成功后要跳转的连接(本例中此属性用不到,因为登录成功后的处理逻辑在LoginController里硬编码) -->              <!-- <property name="successUrl" value="/" ></property> -->              <!-- 用户访问未对其授权的资源时,所显示的连接 -->              <property name="unauthorizedUrl" value="/"></property>              <property name="filterChainDefinitions">                  <value>                      /static/*=anon                      /loginSave=anon                      /**=authc                  </value>              </property>          </bean>      </beans>     

5.编写shiro后台登录验证的代码

1.访问登录的Controller// 登录验证shiro    @RequestMapping(value = "/loginSave", method = RequestMethod.POST)    public void loginSave(            @RequestParam(value = "passport") String passport,            @RequestParam(value = "pwd") String pwd,             HttpSession session,            HttpServletResponse response,             HttpServletRequest request    )throws Exception     {        response.setContentType("application/text; charset=UTF-8");        //获取主体对象        Subject currentUser = SecurityUtils.getSubject();        //shiro容器认证        if (!currentUser.isAuthenticated()) {            UsernamePasswordToken token = new UsernamePasswordToken(passport, pwd);            currentUser.login(token);        }        // 若认证异常,不会执行下面的语句        //session 保存用户信息和常用的信息        response.getWriter().print(1);    }2.登录校验的类package com.model.interceptor;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.realm.AuthorizingRealm;import org.apache.shiro.subject.PrincipalCollection;public class ShiroLocalRealm extends AuthorizingRealm {    /**     * 授权信息     */    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {        return null;    }    /**     * 认证信息     */    protected AuthenticationInfo doGetAuthenticationInfo(            AuthenticationToken authcToken) throws AuthenticationException {        UsernamePasswordToken token = (UsernamePasswordToken) authcToken;        String userName = token.getUsername();        String password = String.valueOf(token.getPassword());        int status = 0;        if(("123").equals(userName)&&"123".equals(password)){            status=1;        }        if (status == 1) {            AuthenticationInfo info = new SimpleAuthenticationInfo(userName, password, getName());            clearCache(info.getPrincipals());            return info;        }        return null;    }}3. 关闭shiro, 退出登录    @RequestMapping(value = "/out", method = RequestMethod.GET)    public ModelAndView out(HttpSession session, HttpServletResponse response,            HttpServletRequest request) {        Subject currentUser = SecurityUtils.getSubject();        // session 注销        // session.invalidate();          try {            currentUser.logout();          } catch (Exception e) {        }        ModelAndView modelAndView = new ModelAndView();        modelAndView.setViewName("/login");        return modelAndView;    } 
0 0