目录
本期内容代码基于Springmvc内容代码上做shiro延伸

- <filter>
- <filter-name>shiroFilterfilter-name>
- <filter-class>org.springframework.web.filter.DelegatingFilterProxyfilter-class>
- <init-param>
-
- <param-name>targetFilterLifecycleparam-name>
- <param-value>trueparam-value>
- init-param>
- filter>
- <filter-mapping>
- <filter-name>shiroFilterfilter-name>
- <url-pattern>/*url-pattern>
- filter-mapping>
-

这次的web.xml配置与上一期博客内容中web.xml配置相比少了一点内容 监听器 (监听器的作用是加载配置文件中的数据源);为什么不需要监听器呢,因为本次内容的数据源从数据库中加载,所以监听器就不需要了。
接下来我们通过逆向工程将下图五张表收藏对应的model mapper



选择当前数据表所在的模块后并点击ok⬇⬇

开始生成

接下来编写查询方法:

- <!--通过用户名进行查询-->
- <select id="queryUserByUserName" resultMap="com.xiaokun.ssm.model.User" parameterType="java.lang.String" >
- select
- <include refid="Base_Column_List" />
- from t_shiro_user
- where username = #{userName}
- </select>

编写biz层
UserBiz
- package com.xiaokun.ssm.biz;
-
- import com.xiaokun.ssm.model.User;
- import org.apache.ibatis.annotations.Param;
-
- public interface UserBiz {
- int deleteByPrimaryKey(Integer userid);
-
- int insert(User record);
-
- int insertSelective(User record);
-
- User selectByPrimaryKey(Integer userid);
-
- User queryUserByUserName(@Param("userName") String userName);
-
- int updateByPrimaryKeySelective(User record);
-
- int updateByPrimaryKey(User record);
- }

UserBizImpl
- package com.xiaokun.ssm.biz.impl;
-
- import com.xiaokun.ssm.biz.UserBiz;
- import com.xiaokun.ssm.mapper.UserMapper;
- import com.xiaokun.ssm.model.User;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Service;
-
- /**
- * @author 小坤
- * @create 2022-08-25-13:30
- */
- @Service
- public class UserBizImpl implements UserBiz {
- @Autowired
- private UserMapper userMapper;
-
- @Override
- public int deleteByPrimaryKey(Integer userid) {
- return userMapper.deleteByPrimaryKey(userid);
- }
-
- @Override
- public int insert(User record) {
-
- return userMapper.insert(record);
- }
-
- @Override
- public int insertSelective(User record) {
-
- return userMapper.insertSelective(record);
- }
-
- @Override
- public User selectByPrimaryKey(Integer userid) {
-
- return userMapper.selectByPrimaryKey(userid);
- }
-
- @Override
- public User queryUserByUserName(String userName) {
-
- return userMapper.queryUserByUserName(userName);
- }
-
- @Override
- public int updateByPrimaryKeySelective(User record) {
- return userMapper.updateByPrimaryKeySelective(record);
- }
-
- @Override
- public int updateByPrimaryKey(User record) {
- return userMapper.updateByPrimaryKey(record);
- }
- }

UserMapper
- package com.xiaokun.ssm.mapper;
-
- import com.xiaokun.ssm.model.User;
- import org.apache.ibatis.annotations.Param;
- import org.springframework.stereotype.Repository;
-
- @Repository
- public interface UserMapper {
- int deleteByPrimaryKey(Integer userid);
-
- int insert(User record);
-
- int insertSelective(User record);
-
- User selectByPrimaryKey(Integer userid);
-
- User queryUserByUserName(@Param("userName") String userName);
-
- int updateByPrimaryKeySelective(User record);
-
- int updateByPrimaryKey(User record);
- }


- package com.xiaokun.ssm.shiro;
-
- import com.xiaokun.ssm.biz.UserBiz;
- import org.apache.shiro.authc.AuthenticationException;
- import org.apache.shiro.authc.AuthenticationInfo;
- import org.apache.shiro.authc.AuthenticationToken;
- import org.apache.shiro.authz.AuthorizationInfo;
- import org.apache.shiro.realm.AuthorizingRealm;
- import org.apache.shiro.subject.PrincipalCollection;
-
- /**
- * @author 小坤
- * @create 2022-08-25-13:37
- */
- public class MyRealm extend AuthorizingRealm {
-
- public UserBiz userBiz;
-
- public UserBiz getUserBiz() {
- return userBiz;
- }
-
- public void setUserBiz(UserBiz userBiz) {
- this.userBiz = userBiz;
- }
-
- /**
- * 授权
- * @param principals
- * @return
- * 替代了上一期博客的shiro-web.ini文件
- */
- @Override
- protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
- return null;
- }
-
- /**
- * 认证
- * @param token
- * @return
- * @throws AuthenticationException
- * shiro.ini
- */
- @Override
- protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
- return null;
- }
- }

配置文件



- "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">
-
-
- <bean id="shiroRealm" class="com.xiaokun.ssm.shiro.MyRealm">
- <property name="userBiz" ref="userBiz" />
-
-
-
-
- <property name="credentialsMatcher">
- <bean id="credentialsMatcher" class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
-
- <property name="hashAlgorithmName" value="md5"/>
-
- <property name="hashIterations" value="1024"/>
-
- <property name="storedCredentialsHexEncoded" value="true"/>
- bean>
- property>
- bean>
-
-
- <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
- <property name="realm" ref="shiroRealm" />
- bean>
-
-
- <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
-
- <property name="securityManager" ref="securityManager" />
-
- <property name="loginUrl" value="/login"/>
-
-
-
- <property name="unauthorizedUrl" value="/unauthorized.jsp"/>
-
- <property name="filterChainDefinitions">
- <value>
-
-
-
-
- /user/login=anon
- /user/updatePwd.jsp=authc
- /admin/*.jsp=roles[admin]
- /user/teacher.jsp=perms["user:update"]
-
- value>
- property>
- bean>
-
-
- <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
- beans>
-
Spring与shiro的整合(注意❗shiro在加载的时候,Spring上下文海没有加载完毕,所以@component与@autowised是不能使用的;spring-shiro.xml文件中,MyRealm需要依赖的业务类由于没有被spring配置,所以需要指定bean的id,通过@Service("具体的名字"))


- /**
- * 认证
- * @param token
- * @return
- * @throws AuthenticationException
- * shiro.ini
- */
- @Override
- protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
- //拿到用户名
- String UserName = token.getPrincipal().toString();
- //调用查询方法
- User user = userBiz.queryUserByUserName(UserName);
- AuthenticationInfo info=new SimpleAuthenticationInfo(
- user.getUsername(),
- user.getPassword(),
- ByteSource.Util.bytes(user.getSalt()),
- this.getName()
- );
- return info;
- }
将前端界面导入
login.jsp
- <%@ page contentType="text/html;charset=UTF-8" language="java" %>
- <html>
- <head>
- <title>Titletitle>
- 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="重置">
- form>
- body>
- html>
LoginController
- package com.xiaokun.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.http.HttpServletRequest;
- import javax.servlet.http.HttpSession;
-
- @Controller
- public class LoginController {
-
- @RequestMapping("/login")
- public String login(HttpServletRequest req){
- try {
- String username = req.getParameter("username");
- String password = req.getParameter("password");
- UsernamePasswordToken token=new UsernamePasswordToken(username,password);
- Subject subject = SecurityUtils.getSubject();
- subject.login(token);
- return "main";
- }catch (Exception e){
- req.setAttribute("message","账号密码错误");
- return "login";
- }
- }
-
- @RequestMapping("/logout")
- public String logout(HttpServletRequest req){
- Subject subject = SecurityUtils.getSubject();
- subject.logout();
- return "login";
- }
-
- }
resultMap:前提做了映射关系的
resultType:放实体类
运行一下


debug断点拿到数据库盐密码


总结:doGetAuthenticationInfo认证方法是web层执行subject.login 方法触发的
1.Mapper层 —— 通过账户名获取用户信息
2.将用户信息给MyRealm 认证方法,认证的过程交给安全管理器
3.MyRealm的配置,配置spring-shiro.xml 文件中
① shiro接管MyRealm的时候,还没有被Spring所接管导致@component与 @autowised用不了
② 采用配置的形式配置UserBiz,需要给@service指定bean的名称
第一阶段:明文密码(在数据库中展现出来的密码)
第二阶段:MD5加密
第三阶段:MD5加盐加密
第四阶段:MD5加盐加密加次数

创建一个测试包,演示盐加密

创建一个类PasswordHelper
- package com.xiaokun.shiro;
-
-
- 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);
- }
- }


假设用户:zhangsan
用户密码:zhangsan
传到后台:1.生成随机的盐 2.利用zhangsan原始密码+生成随机的盐 得到加密后的密码
3.再insert