shiro(二)盐加密和shiro认证

1.盐加密

什么是盐加密:
加盐加密是一种对系统登录口令的加密方式,它实现的方式是将每一个口令同一个叫做”盐“(salt)的n位随机数相关联。无论何时只要口令改变,随机数就改变。随机数以未加密的方式存放在口令文件中,这样每个人都可以读。不再只保存加密过的口令,而是先将口令和随机数连接起来然后一同加密,加密后的结果放在口令文件中。

如何使用盐加密:
首先导入pom依赖,这里的pom依赖是shiro认证所需要用到的:

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

然后导入写好的工具类:

package com.swx.ssm.util;


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

/**
 * 用于shiro权限认证的密码工具类
 */
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("123456", salt);
        System.out.println("凭证+盐加密后得到的密码:"+ credentials);
        System.out.println("凭证+盐加密后得到的密码的长度:"+ credentials.length());
        boolean b = checkCredentials("123456", salt, credentials);
        System.out.println("输入的密码是否能够通过盐+密码的验证:"+b);
    }
}

测试一下:

在这里插入图片描述

2.ssm整合shiro认证

2.1 在web.xml中配置shiro的过滤器

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

2.2 通过逆向工程生成五张我要用的表:
在这里插入图片描述
在这里插入图片描述
不过本次我们只做认证,所以就只使用ShiroUserMapper就行
2.3 在ShiroUserMapper中加上我们的登录方法:

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

2.4 MyRealm 自定义数据源

package com.swx.ssm.shiro;

import com.swx.ssm.model.ShiroUser;
import com.swx.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;

/**
 * @author Songwanxi
 * @site www.lentter.club
 * @company
 * @create  2019-12-01 15:11
 * 数据源
 * 跟随着过滤器启动,无法用spring进行管理
 * 写一个配置文件进行管理
 *
 */
public class MyRealm extends AuthorizingRealm {

    public ShiroUserService getShiroUserService() {
        return shiroUserService;
    }

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

    private ShiroUserService shiroUserService;

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

    /**
     * 认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     * authenticationToken 是从controller层传递过来的,如果一做登录操作,就会访问这个方法
     *
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //getPrincipal 身份   getCredentials 令牌
        String userName = authenticationToken.getPrincipal().toString();
        ShiroUser shiroUser = this.shiroUserService.queryByName(userName);
        AuthenticationInfo info = new SimpleAuthenticationInfo(
                shiroUser.getUsername(),//名
                shiroUser.getPassword(),//密码
                ByteSource.Util.bytes(shiroUser.getSalt()),//盐
                this.getName()

        );
        //返回 AuthenticationInfo
        return info;
    }
}

2.5 配置数据源的管理文件applicationContext-shiro.xml并且将其配置到applicationContext.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"
       xmlns:context="http://www.springframework.org/schema/context"
       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">


    <!--配置自定义的Realm-->
    <bean id="shiroRealm" class="com.swx.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>

2.6 ShiroUserService

package com.swx.ssm.service;

import com.swx.ssm.model.ShiroUser;

/**
 * @author Songwanxi
 * @site www.lentter.club
 * @company
 * @create  2019-12-01 15:07
 */
public interface ShiroUserService {
    //登录
    ShiroUser queryByName (String userName);
    //注册
    int insert(ShiroUser record);
}

2.7 ShiroUserServiceImpl

package com.swx.ssm.service.impl;

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

/**
 * @author Songwanxi
 * @site www.lentter.club
 * @company
 * @create  2019-12-01 15:08
 */
@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);
    }
}

2.8 ShiroUserController

package com.swx.ssm.controller;

import com.swx.ssm.model.ShiroUser;
import com.swx.ssm.service.ShiroUserService;
import com.swx.ssm.util.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.http.HttpServletRequest;

/**
 * @author Songwanxi
 * @site www.lentter.club
 * @company
 * @create  2019-12-01 15:34
 */
@Controller
public class ShiroUserController {
    @Autowired
    private ShiroUserService shiroUserService;

    @RequestMapping("/login")
    public  String login(HttpServletRequest req){
        String uname = req.getParameter("username");
        String pwd = req.getParameter("password");
        //组成令牌
        UsernamePasswordToken token = new UsernamePasswordToken(uname, pwd);
        //主体
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
            //登录成功
            req.getSession().setAttribute("username",uname);
            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("/register")
    public String registered(HttpServletRequest req){
        //获取注册的用户名和密码
        String uname = req.getParameter("username");
        String pwd = req.getParameter("password");
        //生成随机盐
        String salt = PasswordHelper.createSalt();
        //盐+密码
        String credentials = PasswordHelper.createCredentials(pwd, salt);
        //存入数据库
        ShiroUser shiroUser = new ShiroUser();
        shiroUser.setUsername(uname);
        shiroUser.setPassword(credentials);
        shiroUser.setSalt(salt);
        this.shiroUserService.insert(shiroUser);


        return "redirect:/login.jsp";
    }
}

2.9 登录和注册页面:
login.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h1>用户登陆</h1>
    <div style="color: red">${message}</div>
    <form action="${pageContext.request.contextPath}/login" method="post">
        帐号:<input type="text" name="username"><br>
        密码:<input type="password" name="password"><br>
        <input type="submit" value="确定">
        <input type="reset" value="重置">
        <a href="register.jsp">注册</a>
    </form>
</body>
</html>

register.jsp

<%--
  Created by IntelliJ IDEA.
  User: Lentter
  Date: 2019/12/1
  Time: 15:57
  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}/register" method="post">
    帐号:<input type="text" name="username"><br>
    密码:<input type="password" name="password"><br>
    <input type="submit" value="确定">
    <input type="reset" value="重置">
    <a href="login.jsp">返回登录</a>
</form>
</body>
</html>

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值