SSM之shiro认证

前言

续上篇博客,将上篇博客的死数据变成数据库中的数据

shiro认证的思路

整合依赖:shiro-core、shiro-web、shiro-spring
配置web.xml
       过滤器(他是shiro的核心类)
数据源(ini,自定义Realm)
       要将自定义realm去加载数据源,name需要继承AuthorizingRealm
       动态加载数据:
       与spring做整合
添加application-shiro.xml文件
       @servlet(“shiroUserService”)
       shiroUserServiceImpl
       MyRealm
               <property name=“shiroUserService” ref=“shiroUserService” / >
               解密方式:
                    加密方式
<property name=“hashAlgorithmName” value=“md5”/ >
                    加密次数
<property name=“hashIterations” value=“1024”/ >
                    存储方式
<property name=“storedCredentialsHexEncoded” value=“true”/ >
       securityManager
       配置规则

MyRealm
       doGetAuthenticationInfo(认证方法)
              查询数据库当前登录信息
              交给 AuthenticationInfo info =new SimpleAuthenticationInfo(
                            shiroUser.getUsername(),
                             shiroUser.getPassword(),
                             ByteSource.Util.bytes(shiroUser.getSalt()),
                            this.getName()
             );

Md5加密与加盐加密的区别

md5盐加密:
目的:就是将原来的文明密码转换成密文密码保存到数据,从而增加了数据的安全线
隐患:原生的md5加密,一个明文对应一个密文,那么很容易被反向破解
加盐加密:
由于盐是随机生成的,加密方式未知,加密次数未知,存储方式未知,那么从而提高了数据的安全性

Shiro认证

添加pom.xml依赖

<shiro.version>1.2.5</shiro.version>

 <!-- shiro核心包 -->
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-core</artifactId>
            <version>${shiro.version}</version>
        </dependency>
        <!-- 添加shiro web支持 -->
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-web</artifactId>
            <version>${shiro.version}</version>
        </dependency>

        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-spring</artifactId>
            <version>${shiro.version}</version>
        </dependency>

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>

使用逆向工程生成需要用到的几张表
在这里插入图片描述
在这里插入图片描述
在ShiroUserMapper类中添加方法
在这里插入图片描述
ShiroUserMapper.xml

<select id="querByName" resultType="com.liuchunming.model.ShiroUser" parameterType="java.lang.String" >
    select
    <include refid="Base_Column_List" />
    from t_shiro_user
    where username = #{uname}
  </select>

Service层
ShiroUserService

package com.liuchunming.service;

import com.liuchunming.model.ShiroUser;

/**
 * @author liuchunming
 * @site www.liuchunming.com
 * @company xxx公司
 * @create  2020-10-31 22:18
 */
public interface ShiroUserService {
    ShiroUser querByName(String uname);
}

ShiroUserServiceImpl

package com.liuchunming.service.impl;

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

/**
 * @author liuchunming
 * @site www.liuchunming.com
 * @company xxx公司
 * @create  2020-10-31 22:24
 */
@Service("shiroUserService")
public class ShiroUserServiceImpl implements ShiroUserService {
    @Autowired
    private ShiroUserMapper shiroUserMapper;
    @Override
    public ShiroUser querByName(String uname) {
        return shiroUserMapper.querByName(uname);
    }
}

Myrealm.java
SimpleAuthenticationInfo底层代码中的两个方法一个为加密,一个不加密
我们来看看底层代码
在这里插入图片描述

package com.liuchunming.shiro;

import com.liuchunming.model.ShiroUser;
import com.liuchunming.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 liuchunming
 * @site www.liuchunming.com
 * @company xxx公司
 * @create  2020-10-30 19:49
 *
 * 替换掉了上堂课的ini文件,所有用户的身份都从这里来
 */
public class MyRealm extends AuthorizingRealm {
    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.querByName(uname);
        /**
         * 三个参数:
         * 第一个,身份(用户名)
         * 第二个,凭证(密码)
         * 第三个,盐(加密)
         * 第四个,realm (realm的名字)
         */
        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.liuchunming.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>

ShiroUserController.java

package com.liuchunming.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.http.HttpServletRequest;

/**
 * @author liuchunming
 * @site www.liuchunming.com
 * @company xxx公司
 * @create  2020-10-31 23:06
 */
@Controller
public class ShiroUserController {
    @RequestMapping("/login")
    public  String login(HttpServletRequest req){
        Subject subject = SecurityUtils.getSubject();
        String uname = req.getParameter("username");
        String pwd = req.getParameter("password");
        UsernamePasswordToken token=new UsernamePasswordToken(uname,pwd);
        try {
            //这里会跳转MyRealm中的认证方法
            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";
    }
}

导入上一篇博客所用的jsp然后进行测试
在这里插入图片描述

盐加密

盐加密工具类,在做新增用户的时候使用,将加密后的密码、及加密时候的盐放入数据库;
本篇博客中的表数据是现成的,暂时用不上这个工具类去生成数据;
PasswordHelper

package com.liuchunming.util;

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);
    }
}

测试:注意每次执行的密文都不一样
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值