目录
8、applicationContext-shiro.xml
PasswordHelper
- package com.liaoxin.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);
- }
- }
-
- <groupId>org.apache.shirogroupId>
- <artifactId>shiro-coreartifactId>
- <version>1.3.2version>
-
- <dependency>
- <groupId>org.apache.shirogroupId>
- <artifactId>shiro-webartifactId>
- <version>1.3.2version>
- dependency>
-
- <dependency>
- <groupId>org.apache.shirogroupId>
- <artifactId>shiro-springartifactId>
- <version>1.3.2version>
- dependency>
-
-
- <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>
-
-
- "1.0" encoding="UTF-8" ?>
- mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
- <mapper namespace="com.liaoxin.ssm.mapper.UserMapper" >
- <resultMap id="BaseResultMap" type="com.liaoxin.ssm.model.User" >
- <constructor >
- <idArg column="userid" jdbcType="INTEGER" javaType="java.lang.Integer" />
- <arg column="username" jdbcType="VARCHAR" javaType="java.lang.String" />
- <arg column="password" jdbcType="VARCHAR" javaType="java.lang.String" />
- <arg column="salt" jdbcType="VARCHAR" javaType="java.lang.String" />
- <arg column="createdate" jdbcType="TIMESTAMP" javaType="java.util.Date" />
- constructor>
- resultMap>
- <sql id="Base_Column_List" >
- userid, username, password, salt, createdate
- sql>
- <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
- select
- <include refid="Base_Column_List" />
- from t_shiro_user
- where userid = #{userid,jdbcType=INTEGER}
- select>
- <select id="queryByName" resultType="com.liaoxin.ssm.model.User" parameterType="java.lang.String">
- select
- <include refid="Base_Column_List" />
- from t_shiro_user
- where userName = #{userName}
- select>
-
- <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
- delete from t_shiro_user
- where userid = #{userid,jdbcType=INTEGER}
- delete>
- <insert id="insert" parameterType="com.liaoxin.ssm.model.User" >
- insert into t_shiro_user (userid, username, password,
- salt, createdate)
- values (#{userid,jdbcType=INTEGER}, #{username,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR},
- #{salt,jdbcType=VARCHAR}, #{createdate,jdbcType=TIMESTAMP})
- insert>
- <insert id="insertSelective" parameterType="com.liaoxin.ssm.model.User" >
- insert into t_shiro_user
- <trim prefix="(" suffix=")" suffixOverrides="," >
- <if test="userid != null" >
- userid,
- if>
- <if test="username != null" >
- username,
- if>
- <if test="password != null" >
- password,
- if>
- <if test="salt != null" >
- salt,
- if>
- <if test="createdate != null" >
- createdate,
- if>
- trim>
- <trim prefix="values (" suffix=")" suffixOverrides="," >
- <if test="userid != null" >
- #{userid,jdbcType=INTEGER},
- if>
- <if test="username != null" >
- #{username,jdbcType=VARCHAR},
- if>
- <if test="password != null" >
- #{password,jdbcType=VARCHAR},
- if>
- <if test="salt != null" >
- #{salt,jdbcType=VARCHAR},
- if>
- <if test="createdate != null" >
- #{createdate,jdbcType=TIMESTAMP},
- if>
- trim>
- insert>
- <update id="updateByPrimaryKeySelective" parameterType="com.liaoxin.ssm.model.User" >
- update t_shiro_user
- <set >
- <if test="username != null" >
- username = #{username,jdbcType=VARCHAR},
- if>
- <if test="password != null" >
- password = #{password,jdbcType=VARCHAR},
- if>
- <if test="salt != null" >
- salt = #{salt,jdbcType=VARCHAR},
- if>
- <if test="createdate != null" >
- createdate = #{createdate,jdbcType=TIMESTAMP},
- if>
- set>
- where userid = #{userid,jdbcType=INTEGER}
- update>
- <update id="updateByPrimaryKey" parameterType="com.liaoxin.ssm.model.User" >
- update t_shiro_user
- set username = #{username,jdbcType=VARCHAR},
- password = #{password,jdbcType=VARCHAR},
- salt = #{salt,jdbcType=VARCHAR},
- createdate = #{createdate,jdbcType=TIMESTAMP}
- where userid = #{userid,jdbcType=INTEGER}
- update>
- mapper>
②UserMapper.java
- package com.liaoxin.ssm.mapper;
-
- import com.liaoxin.ssm.model.User;
-
- public interface UserMapper {
- int deleteByPrimaryKey(Integer userid);
-
- int insert(User record);
-
- int insertSelective(User record);
-
- User selectByPrimaryKey(Integer userid);
-
- User queryByName(String userName);
-
- int updateByPrimaryKeySelective(User record);
-
- int updateByPrimaryKey(User record);
- }
- package com.liaoxin.ssm.web;
-
- 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 liaoxin
- * @create 2022-08-25 18:30
- */
- @Controller
- public class UserController {
- @RequestMapping("/login")
- public String login(HttpServletRequest request, HttpServletResponse response){
- try{
- String username=request.getParameter("username");
- String password = request.getParameter("password");
- UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password);
- Subject subject = SecurityUtils.getSubject();
- subject.login(usernamePasswordToken);
- return "main";
- }catch (Exception e){
- request.setAttribute("message","您的用户名或者密码有误");
- return "login";
- }
- }
- @RequestMapping("/logout")
- public String logout(HttpServletRequest request, HttpServletResponse response){
- try{
- Subject subject = SecurityUtils.getSubject();
- subject.logout();
- return "login";
- }catch (Exception e){
- request.setAttribute("message","您的用户名或者密码有误");
- return "login";
- }
- }
- }
-
- package com.liaoxin.ssm.biz;
-
- import com.liaoxin.ssm.model.User;
-
- /**
- * @author liaoxin
- * @create 2022-08-25 18:06
- */
- public interface UserBiz {
- int deleteByPrimaryKey(Integer userid);
-
- int insert(User record);
-
- int insertSelective(User record);
-
- User selectByPrimaryKey(Integer userid);
-
- User queryByName(String userName);
-
- int updateByPrimaryKeySelective(User record);
-
- int updateByPrimaryKey(User record);
- }
-
②UserBizImpl
- package com.liaoxin.ssm.biz.impl;
-
- import com.liaoxin.ssm.biz.UserBiz;
- import com.liaoxin.ssm.mapper.UserMapper;
- import com.liaoxin.ssm.model.User;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Service;
-
- /**
- * @author liaoxin
- * @create 2022-08-25 18:08
- */
- @Service("UserService")
- 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 queryByName(String userName) {
- return userMapper.queryByName(userName);
- }
-
- @Override
- public int updateByPrimaryKeySelective(User record) {
- return userMapper.updateByPrimaryKeySelective(record);
- }
-
- @Override
- public int updateByPrimaryKey(User record) {
- return userMapper.updateByPrimaryKey(record);
- }
- }
-
- package com.liaoxin.ssm.shiro;
-
- import com.liaoxin.ssm.biz.UserBiz;
- import com.liaoxin.ssm.model.User;
- 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 liaoxin
- * @create 2022-08-25 18:16
- */
- public class Myrealm extends AuthorizingRealm {
- private UserBiz userBiz;
-
- public UserBiz getUserBiz() {
- return userBiz;
- }
-
- public void setUserBiz(UserBiz userBiz) {
- this.userBiz = userBiz;
- }
-
- @Override
- protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
- return null;
- }
-
- @Override
- protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
- System.out.println("身份验证...");
- String username = token.getPrincipal().toString();
- String password = token.getCredentials().toString();
- User user = userBiz.queryByName(username);
- AuthenticationInfo info=new SimpleAuthenticationInfo(
- user.getUsername(),
- user.getPassword(),
- ByteSource.Util.bytes(user.getSalt()),
- this.getName()
- );
- return info;
- }
- }
-
- "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.javaxl.ssm.shiro.MyRealm">
- <property name="shiroUserService" ref="shiroUserService" />
-
-
-
-
- <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>
-
-