Shiro认证-SSM

目录

一、盐加密

(一)Shiro环境配置与表生成

1、导入pom相关依赖

2、web.xml配置

3、通过逆向工程将五张表生成对应的model、mapper

4、增加通过账号查询用户信息的方法

数据库存储密码根本不知道是什么,安全系数增加

(二)md5加密 

1、 md5加密:

2、 md5解密:

 (三)Shiro加密

1、PasswordHelper(util包下) : 

2、运行获得结果

二、Shiro认证

1、Myrealm.java

2、applicationContext-shiro.xml

3、ShiroUserController

4、导入相关jsp界面

5、 将applicationContext-shiro.xml交给spring进行管理

6、结果


一、盐加密

继续在ssm项目值续写

(一)Shiro环境配置与表生成

1、导入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>

2、web.xml配置

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

3、通过逆向工程将五张表生成对应的model、mapper

 ①、generatorConfig.xml

<table schema="" tableName="t_shiro_permission" domainObjectName="ShiroPermission"
       enableCountByExample="false" enableDeleteByExample="false"
       enableSelectByExample="false" enableUpdateByExample="false">
</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="ShiroRolePermission"
       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="ShiroUserRole"
       enableCountByExample="false" enableDeleteByExample="false"
       enableSelectByExample="false" enableUpdateByExample="false">
</table>

②、检查是否生成在ssm下面:

运行即可

4、增加通过账号查询用户信息的方法

①、ShiroUserMapper.xml:

<!--添加通过账号查询用户信息的方法-->
  <select id="queryByName" resultType="com.mwy.model.ShiroUser" parameterType="java.lang.String" >
    select
    <include refid="Base_Column_List" />
    from t_shiro_user
    where username = #{userName}
  </select>

②、ShiroUserMapper:

public ShiroUser queryByName(@Param("userName") String userName);

③、ShiroUserService 

package com.mwy.service;
import com.mwy.model.ShiroUser;
import org.apache.ibatis.annotations.Param;
public interface ShiroUserService {

    int deleteByPrimaryKey(Integer userid);

    int insert(ShiroUser record);

    int insertSelective(ShiroUser record);

    ShiroUser selectByPrimaryKey(Integer userid);

    int updateByPrimaryKeySelective(ShiroUser record);

    int updateByPrimaryKey(ShiroUser record);

    public ShiroUser queryByName(String userName);

}

④、ShiroUserServiceImpl 实现ShiroUserService 接口

package com.mwy.service.impl;
import com.mwy.mapper.ShiroUserMapper;
import com.mwy.model.ShiroUser;
import com.mwy.service.ShiroUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
//交给spring进行管理
@Service("shiroUserService")
public class ShiroUserServiceImpl implements ShiroUserService {
    @Autowired
    private ShiroUserMapper shiroUserMapper;

    @Override
    public int deleteByPrimaryKey(Integer userid) {
        return 0;
    }

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

    @Override
    public int insertSelective(ShiroUser record) {
        return 0;
    }

    @Override
    public ShiroUser selectByPrimaryKey(Integer userid) {
        return null;
    }

    @Override
    public int updateByPrimaryKeySelective(ShiroUser record) {
        return 0;
    }

    @Override
    public int updateByPrimaryKey(ShiroUser record) {
        return 0;
    }

    @Override
    public ShiroUser queryByName(String userName) {
        return shiroUserMapper.queryByName(userName);
    }
}

数据库存储密码根本不知道是什么,安全系数增加

(二)md5加密 

1、 md5加密:

密码都有相匹配的对应结果,而且不会改变,同样的密码只会生成一种结果

2、 md5解密:

md5的缺陷: 有破解工具,安全系数降低,

明文与密文一一对应的关系,明文加密成固定的密文;

 (三)Shiro加密

盐加密工具类,在做新增用户的时候使用,将加密后的密码、及加密时候的盐放入数据库;

本篇博客中的表数据是现成的,暂时用不上这个工具类去生成数据;

1、PasswordHelper(util包下) : 

密码工具类,加密1024次不能透露·,透露也就不安全了(因为一个明文对应一个密文,不断反推依旧能推出)

package com.mwy.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);//true
    }
}

2、运行获得结果

第一次运行:

 第二次运行:

 两次运行的结果都不相同,但同时都是123;安全系数高

二、Shiro认证

1、Myrealm.java

 自定义Realm
  Shiro从Realm获取安全数据(如用户、角色、权限),就是说SecurityManager要验证用户身份,那么它需要从Realm获取相应的用户进行比较以确定用户身份是否合法;也需要从Realm得到用户相应的角色/权限进行验证用户是否能进行操作;可以把Realm看成DataSource,即安全数据源。

  最基础的是Realm接口,CachingRealm负责缓存处理,AuthenticationRealm负责认证,AuthorizingRealm负责授权。

  通常自定义的realm继承AuthorizingRealm

  注1:体系结构见“shiro提供的realm.png”

  AuthorizationInfo:授权信息
  AuthenticationInfo:认证信息

继承AuthorizingRealm需要重写两个方法;重写授权与认证

package com.mwy.shiro;
import com.mwy.model.ShiroUser;
import com.mwy.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.stereotype.Service;
public class MyRealm extends AuthorizingRealm {
    private ShiroUserService shiroUserService;


    public ShiroUserService getShiroUserService() {
        return shiroUserService;
    }

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

//重写授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }
//重写认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("身份认证...");
        //token就是controller中的Login请求,subject.login(token);
        String username = token.getPrincipal().toString();
//        String password = token.getCredentials().toString();
        ShiroUser user = shiroUserService.queryByName(username);
//        拿到数据库中的用户信息,放入token凭证中,用于controler进行对比
        AuthenticationInfo info = new SimpleAuthenticationInfo(
                user.getUsername(),
                user.getPassword(),
                ByteSource.Util.bytes(user.getSalt()),
                this.getName()
        );
        return info;
    }
}

2、applicationContext-shiro.xml

MyRealm要交给spring进行管理需要在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.mwy.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>

3、ShiroUserController

在controller包下新增ShiroUserController(登录功能)

package com.mwy.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;

@Controller
public class ShiroUserController {

    @RequestMapping("/login")
    public String login(HttpServletRequest req, HttpServletResponse resp){
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(usernamePasswordToken);
            req.getRequestDispatcher("main.jsp").forward(req, resp);
        } catch (Exception e) {
            req.setAttribute("message", "您的用户名密码输入有误!!!");
            try {
                req.getRequestDispatcher("login.jsp").forward(req, resp);
            } catch (ServletException e1) {
                e1.printStackTrace();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
        return null;
    }

    @RequestMapping("/logout")
    public String logout(HttpServletRequest req, HttpServletResponse resp){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        try {
            resp.sendRedirect(req.getContextPath()+"/login.jsp");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}

4、导入相关jsp界面

5、 将applicationContext-shiro.xml交给spring进行管理

<import resource="classpath:applicationContext-shiro.xml"></import>

6、结果

这与shiro入门测试结果一致,变化的是shiro入门用的是死数据(ini文件),

而这次用的是数据库数据

①、不填写登录

 ②、不同角色登录,查看到的功能各不相同

张三:

 王五:

 ③、权限查看

王五登录点击用户新增显示界面

 zdm登录点击用户新增界面

结束!!!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值