Shiro认证

Shiro认证

前提准备

逆向生成需要用的包

提供数据库
链接:https://pan.baidu.com/s/1L9eSoFr_QM1tuSyKCIUtCg
提取码:jcrp
在这里插入图片描述

<table schema="" tableName="t_shiro_permission" domainObjectName="ShiroPermission"
               enableCountByExample="false" enableDeleteByExample="false"
               enableSelectByExample="false" enableUpdateByExample="false">
            <!-- 忽略列,不生成bean 字段 -->
            <!-- <ignoreColumn column="FRED" /> -->
            <!-- 指定列的java数据类型 -->
            <!-- <columnOverride column="LONG_VARCHAR_FIELD" jdbcType="VARCHAR" /> -->
        </table>
        <table schema="" tableName="t_shiro_role" domainObjectName="ShiroRole"
               enableCountByExample="false" enableDeleteByExample="false"
               enableSelectByExample="false" enableUpdateByExample="false">
        </table>
        <table schema="" tableName="t_shiro_role_permission" domainObjectName="RolePermission"
               enableCountByExample="false" enableDeleteByExample="false"
               enableSelectByExample="false" enableUpdateByExample="false">

        </table>
        <table schema="" tableName="t_shiro_user" domainObjectName="ShiroUser"
               enableCountByExample="false" enableDeleteByExample="false"
               enableSelectByExample="false" enableUpdateByExample="false">
        </table>
        <table schema="" tableName="t_shiro_user_role" domainObjectName="UserRole"
               enableCountByExample="false" enableDeleteByExample="false"
               enableSelectByExample="false" enableUpdateByExample="false">
        </table>

导入pom依赖

<dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-core</artifactId>
    <version>1.3.2</version>
</dependency>

<dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-web</artifactId>
    <version>1.3.2</version>
</dependency>

<dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-spring</artifactId>
    <version>1.3.2</version>
</dependency>

整个pom

<?xml version="1.0" encoding="UTF-8"?>


4.0.0

com.zking
ssm
1.0-SNAPSHOT
war

ssm Maven Webapp

http://www.example.com

org.springframework spring-webmvc ${spring.version} org.springframework spring-orm ${spring.version} org.springframework spring-tx ${spring.version} org.springframework spring-aspects ${spring.version} org.springframework spring-web ${spring.version} org.springframework spring-test ${spring.version} org.mybatis mybatis ${mybatis.version} mysql mysql-connector-java ${mysql.version} com.github.pagehelper pagehelper ${pagehelper.version} org.mybatis mybatis-spring ${mybatis.spring.version} org.apache.commons commons-dbcp2 ${commons.dbcp2.version} org.apache.commons commons-pool2 ${commons.pool2.version} org.slf4j slf4j-api ${slf4j.version} org.slf4j jcl-over-slf4j ${slf4j.version} runtime org.apache.logging.log4j log4j-api ${log4j2.version} org.apache.logging.log4j log4j-core ${log4j2.version} org.apache.logging.log4j log4j-slf4j-impl ${log4j2.version} org.apache.logging.log4j log4j-web ${log4j2.version} runtime com.lmax disruptor ${log4j2.disruptor.version} junit junit ${junit.version} test javax.servlet javax.servlet-api ${servlet.version} provided org.projectlombok lombok ${lombok.version} provided
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-context-support</artifactId>
  <version>${spring.version}</version>
</dependency>
<!--mybatis与ehcache整合-->
<dependency>
  <groupId>org.mybatis.caches</groupId>
  <artifactId>mybatis-ehcache</artifactId>
  <version>1.1.0</version>
</dependency>
<!--ehcache依赖-->
<dependency>
  <groupId>net.sf.ehcache</groupId>
  <artifactId>ehcache</artifactId>
  <version>2.10.0</version>
</dependency>
<dependency>
  <groupId>redis.clients</groupId>
  <artifactId>jedis</artifactId>
  <version>${redis.version}</version>
</dependency>
<dependency>
  <groupId>org.springframework.data</groupId>
  <artifactId>spring-data-redis</artifactId>
  <version>${redis.spring.version}</version>
</dependency>
<!-- jackson -->
<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-databind</artifactId>
  <version>${jackson.version}</version>
</dependency>
<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-core</artifactId>
  <version>${jackson.version}</version>
</dependency>
<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-annotations</artifactId>
  <version>${jackson.version}</version>
</dependency>
<!--自定义标签库-->
<!-- 5.3、jstl、standard -->
<dependency>
  <groupId>jstl</groupId>
  <artifactId>jstl</artifactId>
  <version>${jstl.version}</version>
</dependency>
<dependency>
  <groupId>taglibs</groupId>
  <artifactId>standard</artifactId>
  <version>${standard.version}</version>
</dependency>
<!-- 5.4、tomcat-jsp-api -->
<dependency>
  <groupId>org.apache.tomcat</groupId>
  <artifactId>tomcat-jsp-api</artifactId>
  <version>${tomcat-jsp-api.version}</version>
</dependency>
<!--文件上传-->
<dependency>
  <groupId>commons-fileupload</groupId>
  <artifactId>commons-fileupload</artifactId>
  <version>${commons-fileupload.version}</version>
</dependency>
<!--Shiro认证-->
<dependency>
  <groupId>org.apache.shiro</groupId>
  <artifactId>shiro-core</artifactId>
  <version>1.3.2</version>
</dependency>
<dependency>
  <groupId>org.apache.shiro</groupId>
  <artifactId>shiro-web</artifactId>
  <version>1.3.2</version>
</dependency>
<dependency>
  <groupId>org.apache.shiro</groupId>
  <artifactId>shiro-spring</artifactId>
  <version>1.3.2</version>
</dependency>
ssm src/main/java **/*.xml src/main/resources jdbc.properties *.xml maven-clean-plugin 3.1.0 maven-resources-plugin 3.0.2 maven-compiler-plugin 3.8.0 maven-surefire-plugin 2.22.1 maven-war-plugin 3.2.2 maven-install-plugin 2.5.2 maven-deploy-plugin 2.8.2 org.apache.maven.plugins maven-compiler-plugin ${maven.compiler.plugin.version} ${maven.compiler.source} ${maven.compiler.target} ${project.build.sourceEncoding} org.mybatis.generator mybatis-generator-maven-plugin 1.3.2 mysql mysql-connector-java ${mysql.version} true

web.xml添加过滤器(读取数据源Realm)

<!-- 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>

ShiroUserMapper.xml中新增

 <select id="queryByName" resultType="com.onlyK.ssm.model.ShiroUser" parameterType="java.lang.String">
    select
    <include refid="Base_Column_List" />
    from t_shiro_user
    where userName = #{userName}
  </select>

ShiroUserService

package com.onlyK.ssm.service;

import com.onlyK.ssm.model.ShiroUser;
import org.apache.ibatis.annotations.Param;

/**
 * @author only老K
 * @create  2019-12-01 14:24
 */
public interface ShiroUserService {
    ShiroUser queryByName(String userName);
}

ShiroUserServiceImpl

package com.onlyK.ssm.service.impl;

import com.onlyK.ssm.mapper.ShiroUserMapper;
import com.onlyK.ssm.model.ShiroUser;
import com.onlyK.ssm.service.ShiroUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author only老K
 * @create  2019-12-01 14:25
 */
@Service("shiroUserService")
public class ShiroUserServiceImpl implements ShiroUserService {
    @Autowired
    private ShiroUserMapper shiroUserMapper;
    @Override
    public ShiroUser queryByName(String userName) {
        return shiroUserMapper.queryByName(userName);
    }
}

MyRealm

package com.onlyK.ssm.shiro;

import com.onlyK.ssm.model.ShiroUser;
import com.onlyK.ssm.service.ShiroUserService;
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.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author only老K
 * @create  2019-12-01 14:12
 *
 * 替换掉了上篇博客的数据源
 */

public class MyRealm extends AuthorizingRealm {
     @Autowired
    private ShiroUserService shiroUserService;

    public ShiroUserService getShiroUserService() {
        return shiroUserService;
    }

    public void setShiroUserService(ShiroUserService shiroUserService) {
        this.shiroUserService = shiroUserService;
    }

    /**
     * 认证授权的
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    /**
     * 身份认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String uname = authenticationToken.getPrincipal().toString();
        String pwd = authenticationToken.getCredentials().toString();
        ShiroUser shiroUser = shiroUserService.queryByName(uname);
        AuthenticationInfo info = new SimpleAuthenticationInfo(
                shiroUser.getUsername(),
                shiroUser.getPassword(),
                ByteSource.Util.bytes(shiroUser.getSalt()),
                this.getName()
        );
        return info;
    }
}

applicationContext-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.xsd">

    <!--配置自定义的Realm-->
    <bean id="shiroRealm" class="com.onlyK.ssm.shiro.MyRealm">
        <property name="shiroUserService" ref="shiroUserService" />
        <!--注意:重要的事情说三次~~~~~~此处加密方式要与用户注册时的算法一致 -->
        <!--注意:重要的事情说三次~~~~~~此处加密方式要与用户注册时的算法一致 -->
        <!--注意:重要的事情说三次~~~~~~此处加密方式要与用户注册时的算法一致 -->
        <!--以下三个配置告诉shiro将如何对用户传来的明文密码进行加密-->
        <property name="credentialsMatcher">
            <bean id="credentialsMatcher" class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
                <!--指定hash算法为MD5-->
                <property name="hashAlgorithmName" value="md5"/>
                <!--指定散列次数为1024-->
                <property name="hashIterations" value="1024"/>
                <!--true指定Hash散列值使用Hex加密存. false表明hash散列值用用Base64-encoded存储-->
                <property name="storedCredentialsHexEncoded" value="true"/>
            </bean>
        </property>
    </bean>

    <!--注册安全管理器-->
    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
        <property name="realm" ref="shiroRealm" />
    </bean>

    <!--Shiro核心过滤器-->
    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
        <!-- Shiro的核心安全接口,这个属性是必须的 -->
        <property name="securityManager" ref="securityManager" />
        <!-- 身份验证失败,跳转到登录页面 -->
        <property name="loginUrl" value="/login"/>
        <!-- 身份验证成功,跳转到指定页面 -->
        <!--<property name="successUrl" value="/index.jsp"/>-->
        <!-- 权限验证失败,跳转到指定页面 -->
        <property name="unauthorizedUrl" value="/unauthorized.jsp"/>
        <!-- Shiro连接约束配置,即过滤链的定义 -->
        <property name="filterChainDefinitions">
            <value>
                <!--
                注:anon,authcBasic,auchc,user是认证过滤器
                    perms,roles,ssl,rest,port是授权过滤器
                -->
                <!--anon 表示匿名访问,不需要认证以及授权-->
                <!--authc表示需要认证 没有进行身份认证是不能进行访问的-->
                <!--roles[admin]表示角色认证,必须是拥有admin角色的用户才行-->
                /user/login=anon
                /user/updatePwd.jsp=authc
                /admin/*.jsp=roles[admin]
                /user/teacher.jsp=perms["user:update"]
                <!-- /css/**               = anon
                 /images/**            = anon
                 /js/**                = anon
                 /                     = anon
                 /user/logout          = logout
                 /user/**              = anon
                 /userInfo/**          = authc
                 /dict/**              = authc
                 /console/**           = roles[admin]
                 /**                   = anon-->
            </value>
        </property>
    </bean>

    <!-- Shiro生命周期,保证实现了Shiro内部lifecycle函数的bean执行 -->
    <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
</beans>

applicationContext

<?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" xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">

    <!--多数据源导入配置-->
    <context:property-placeholder location="classpath:jdbc.properties,classpath:redis.properties"></context:property-placeholder>
    <!--spring整合mybatis-->
    <!--在全局配置文件中导入整合mybaits的文件-->
    <import resource="applicationContext-mybatis.xml"/>
    <!--整合ehcache-->
   <!-- <import resource="applicationContext-ehcache.xml"></import>-->
    <!--整合redis-->
  <!--  <import resource="applicationContext-redis.xml"></import>-->
    <!--shiro-->
    <import resource="applicationContext-shiro.xml"></import>
</beans>

ShiroUserController

package com.onlyK.ssm.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author only老K
 * @create  2019-12-01 14:41
 */
@Controller
public class ShiroUserController {
    @RequestMapping("/login")
    public String login(HttpServletRequest req){
        Subject subject = SecurityUtils.getSubject();
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        try {
            //这里会跳转到MyRealm中的认证方法中
            subject.login(token);
            req.getSession().setAttribute("username",username);
            return "main";
        } catch (Exception e) {
            req.setAttribute("message", "用户名或者密码错误!!!");
            return "login";
        }
    }
    @RequestMapping("/logout")
    public String logout(HttpServletRequest req){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "redirect:/login.jsp";
    }
}

效果图

在这里插入图片描述
在这里插入图片描述

盐加密

PassWordHelper

package com.onlyK.ssm.utils;

import org.apache.shiro.crypto.RandomNumberGenerator;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;

public class PasswordHelper {

    /**
     * 随机数生成器
     */
    private static RandomNumberGenerator randomNumberGenerator = new SecureRandomNumberGenerator();

    /**
     * 指定hash算法为MD5
     */
    private static final String hashAlgorithmName = "md5";

    /**
     * 指定散列次数为1024次,即加密1024次
     */
    private static final int hashIterations = 1024;

    /**
     * true指定Hash散列值使用Hex加密存. false表明hash散列值用用Base64-encoded存储
     */
    private static final boolean storedCredentialsHexEncoded = true;

    /**
     * 获得加密用的盐
     *
     * @return
     */
    public static String createSalt() {
        return randomNumberGenerator.nextBytes().toHex();
    }

    /**
     * 获得加密后的凭证
     *
     * @param credentials 凭证(即密码)
     * @param salt        盐
     * @return
     */
    public static String createCredentials(String credentials, String salt) {
        SimpleHash simpleHash = new SimpleHash(hashAlgorithmName, credentials,
                salt, hashIterations);
        return storedCredentialsHexEncoded ? simpleHash.toHex() : simpleHash.toBase64();
    }


    /**
     * 进行密码验证
     *
     * @param credentials        未加密的密码
     * @param salt               盐
     * @param encryptCredentials 加密后的密码
     * @return
     */
    public static boolean checkCredentials(String credentials, String salt, String encryptCredentials) {
        return encryptCredentials.equals(createCredentials(credentials, salt));
    }

    public static void main(String[] args) {
        //盐
        String salt = createSalt();
        System.out.println(salt);
        System.out.println(salt.length());
        //凭证+盐加密后得到的密码
        String credentials = createCredentials("123", salt);
        System.out.println(credentials);
        System.out.println(credentials.length());
        boolean b = checkCredentials("123", salt, credentials);
        System.out.println(b);
    }
}

注册新用户

快乐就完事

zhuce.jsp

<%--
  Created by IntelliJ IDEA.
  User: 86135
  Date: 2019/12/1
  Time: 15:31
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>用户注册</title>
</head>
<body>
<h1>用户注册</h1>
<form action="${pageContext.request.contextPath}/zhuce" method="post">
    帐号:<input type="text" name="username"><br>
    密码:<input type="password" name="password"><br>
    <input type="submit" value="确定">
    <input type="reset" value="重置">
</form>
</body>
</html>

因为ShiroUserMapper是因为逆向工具生成的所有有增加方法直接写Service方法就好

ShiroUserService

package com.onlyK.ssm.service;

import com.onlyK.ssm.model.ShiroUser;
import org.apache.ibatis.annotations.Param;

/**
 * @author only老K
 * @create  2019-12-01 14:24
 */
public interface ShiroUserService {
    ShiroUser queryByName(String userName);
    int insert(ShiroUser record);
}

ShiroUserServiceImpl

package com.onlyK.ssm.service.impl;

import com.onlyK.ssm.mapper.ShiroUserMapper;
import com.onlyK.ssm.model.ShiroUser;
import com.onlyK.ssm.service.ShiroUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author only老K
 * @create  2019-12-01 14:25
 */
@Service("shiroUserService")
public class ShiroUserServiceImpl implements ShiroUserService {
    @Autowired
    private ShiroUserMapper shiroUserMapper;
    @Override
    public ShiroUser queryByName(String userName) {
        return shiroUserMapper.queryByName(userName);
    }

    @Override
    public int insert(ShiroUser record) {
        return shiroUserMapper.insert(record);
    }
}

ShiroUserController

package com.onlyK.ssm.controller;

import com.onlyK.ssm.model.ShiroUser;
import com.onlyK.ssm.service.ShiroUserService;
import com.onlyK.ssm.service.impl.ShiroUserServiceImpl;
import com.onlyK.ssm.utils.PasswordHelper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author only老K
 * @create  2019-12-01 14:41
 */
@Controller
public class ShiroUserController {
    @Autowired
    private ShiroUserService shiroUserService;

    @RequestMapping("/login")
    public String login(HttpServletRequest req){
        Subject subject = SecurityUtils.getSubject();
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        try {
            //这里会跳转到MyRealm中的认证方法中
            subject.login(token);
            req.getSession().setAttribute("username",username);
            return "main";
        } catch (Exception e) {
            req.setAttribute("message", "用户名或者密码错误!!!");
            return "login";
        }
    }
    @RequestMapping("/logout")
    public String logout(HttpServletRequest req){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "redirect:/login.jsp";
    }
    @RequestMapping("/zhuce")
    public String zhuce(HttpServletRequest req){
      String uername=req.getParameter("username");//得到zhuce.jsp传过来的名字
      String password=req.getParameter("password");//得到zhuce.jsp传来的密码
      String salt= PasswordHelper.createSalt();//生成一个盐
       String  credentials=PasswordHelper.createCredentials(password,salt); //凭证+盐加密后得到的密码
        ShiroUser shiroUser=new ShiroUser();//创建一个用户出来  然后给用户赋值
        shiroUser.setUsername(uername);//用户名赋值
        shiroUser.setPassword(credentials);//密码赋值 赋值加密过后的
        shiroUser.setSalt(salt);//把盐进去
        //调用增加方法
        int num = shiroUserService.insert(shiroUser);
        if(num>0){
            System.out.println("成功");
            return "login";
        }else{
            return "redirect:/zhuce.jsp";
        }
    }
}

效果图

在这里插入图片描述
在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值