天天看点

SSM整合Shiro-登录案例

SSM整合Shiro-登录案例

最近几天在学shiro,有一点小的进展,基本了解shiro的身份认证流程,写篇博客记录一下。

大体思路如下(个人总结,不足之处多多指教):

login.jsp输入账号信息后跳转到需要验证的路径下,被指定拦截器拦截后,经过自定义realm验证。若验证成功,跳转到spring-shiro.xml中successUrl的路径下;若验证失败,跳转到spring-shiro.xml中loginUrl的路径下。

流程如下:

1.导入jar包

<!-- shiro的jar包 -->
    <!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-all -->
    <dependency>
      <groupId>org.apache.shiro</groupId>
      <artifactId>shiro-all</artifactId>
      <version>1.3.2</version>
    </dependency>
           

2.配置web.xml文件

<!-- Spring和mybatis、shiro的配置文件 -->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:spring/spring-*.xml</param-value>
  </context-param>
  
   <!-- 配置shiro -->
  <filter>
    <filter-name>shiroFilter</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    <init-param>
      <!-- 表示bean的生命周期由servlet管理 -->
      <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.配置spring-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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
 http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">
    <!-- 配置凭证匹配器 -->
    <bean id="credentialsMatcher" class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
        <!-- 散列算法 -->
        <property name="hashAlgorithmName" value="md5"/>
        <!-- 迭代次数 -->
        <property name="hashIterations" value="2"/>
</bean>

    <!-- 配置authc过滤器 -->
    <bean id="authc" class="org.apache.shiro.web.filter.authc.FormAuthenticationFilter">
        <!-- 修改登录参数 -->
        <property name="usernameParam" value="username"/>
        <property name="passwordParam" value="password"/>
    </bean>

    <!-- 自定义Realm -->
    <bean id="userRealm" class="com.niqi.realm.UserRealm">
        <property name="credentialsMatcher" ref="credentialsMatcher"/>
    </bean>

    <!-- 配置securityManager -->
    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
        <property name="realm" ref="userRealm"/>
    </bean>

    <!-- shiro过滤器 -->
    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
        <!--配置securityManager-->
        <property name="securityManager" ref="securityManager"/>
        <!-- 登录url,如果没有登录,跳到该url;默认为根目录下的login.jsp-->
        <property name="loginUrl" value="/user/tologin"/>
        <!-- 认证成功后跳转的url,默认认证成功后跳转上一个url-->
        <property name="successUrl" value="/user/authentication" />
        <!-- 用户没有权限访问资源时跳转的url -->
        <property name="unauthorizedUrl" value="/refuse"/>
        <!-- 配置shiro的过滤器链 -->
        <property name="filterChainDefinitions" >
            <value>
                /user/login=anon
                /user/tologin=authc
                /user/logout=logout
                /**=authc
            </value>
        </property>
    </bean>

    <!-- 配置logout过滤器 -->
    <bean id="logout" class="org.apache.shiro.web.filter.authc.LogoutFilter">
        <property name="redirectUrl" value="/login"/>
    </bean>

</beans>
           

4.自定义Realm

package com.niqi.realm;

/**
 * @program: shiro
 * @description: 用户域
 * @author: NiQi
 * @create: 2019-09-03 09:23
 **/
public class UserRealm extends AuthorizingRealm {
    @Autowired
    UserService userService;

    @Override
    public String getName(){
        return "userRealm";
    }

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    //验证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username = token.getPrincipal().toString();
        User user = userService.getUser(username);
        if (user != null) {
            String password = user.getPassword();
            String salt = user.getPassword_salt();
            return new SimpleAuthenticationInfo(user,password, ByteSource.Util.bytes(salt),getName());
        } else {
            return null;
        }
    }
}

           

6.Controller层

package com.niqi.controller;
/**
 * @program: shiro
 * @description: 用户控制层
 * @author: NiQi
 * @create: 2019-09-03 11:32
 **/
@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;

    @RequestMapping("/login")
    public String login(){
        return "/login";
    }

    @RequestMapping("/tologin")
    public String tologin(){
        return "/login";
    }

    //身份验证
    @RequestMapping("/authentication")
    public ModelAndView authentication(HttpSession session){
        ModelAndView mav = new ModelAndView("/index");
        //创建subject
        Subject subject = SecurityUtils.getSubject();
        User user = (User)subject.getPrincipal();
        mav.addObject("user",user);
        return mav;
    }

    @RequestMapping("/logout")
    public String logout(){
        return "/login";
    }
}

           

7.UserMapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.niqi.dao.UserMapper">
    <!-- 获取用户 -->
    <select id="getUser" resultType="com.niqi.pojo.User">
        select * from users where username=#{username}
    </select>
</mapper>
           

8.login.jsp

<%--
  Created by IntelliJ IDEA.
  User: niqi
  Date: 2019/9/3
  Time: 11:36
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" %>
<html>
<head>
    <title>登录界面</title>
</head>
<body>
    <form action="${pageContext.request.contextPath}/user/tologin" method="post">
        <table>
            <tr>
                <td>用户名</td>
                <td>
                    <label><input name="username" type="text" ></label>
                </td>
            </tr>
            <tr>
                <td>密码</td>
                <td>
                    <label><input type="password" name="password"></label>
                </td>
            </tr>
            <tr>
                <td colspan="2" align="center">
                    <label>
                        <input type="submit" value="登录">&nbsp;
                        <input type="reset" value="重置">
                    </label>
                </td>
            </tr>
        </table>
    </form>
</body>
</html>

           

代码下载

继续阅读