Shiro认证
程序员文章站
2023-12-21 18:52:04
...
shiro认证
1.导入pom.xml依赖
<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
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd" >
<generatorConfiguration>
<!-- 引入配置文件 -->
<properties resource="jdbc.properties"/>
<!--指定数据库jdbc驱动jar包的位置-->
<classPathEntry location="D:\\tools\\mvn\\mysql\\mysql-connector-java\\5.1.44\\mysql-connector-java-5.1.44.jar"/>
<!-- 一个数据库一个context -->
<context id="infoGuardian">
<!-- 注释 -->
<commentGenerator>
<property name="suppressAllComments" value="true"/><!-- 是否取消注释 -->
<property name="suppressDate" value="true"/> <!-- 是否生成注释代时间戳 -->
</commentGenerator>
<!-- jdbc连接 -->
<jdbcConnection driverClass="${jdbc.driver}"
connectionURL="${jdbc.url}" userId="${jdbc.username}" password="${jdbc.password}"/>
<!-- 类型转换 -->
<javaTypeResolver>
<!-- 是否使用bigDecimal, false可自动转化以下类型(Long, Integer, Short, etc.) -->
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<!-- 01 指定javaBean生成的位置 -->
<!-- targetPackage:指定生成的model生成所在的包名 -->
<!-- targetProject:指定在该项目下所在的路径 -->
<javaModelGenerator targetPackage="com.xwt.ssm.model"
targetProject="src/main/java">
<!-- 是否允许子包,即targetPackage.schemaName.tableName -->
<property name="enableSubPackages" value="false"/>
<!-- 是否对model添加构造函数 -->
<property name="constructorBased" value="true"/>
<!-- 是否针对string类型的字段在set的时候进行trim调用 -->
<property name="trimStrings" value="false"/>
<!-- 建立的Model对象是否 不可改变 即生成的Model对象不会有 setter方法,只有构造方法 -->
<property name="immutable" value="false"/>
</javaModelGenerator>
<!-- 02 指定sql映射文件生成的位置 -->
<sqlMapGenerator targetPackage="com.xwt.ssm.mapper"
targetProject="src/main/java">
<!-- 是否允许子包,即targetPackage.schemaName.tableName -->
<property name="enableSubPackages" value="false"/>
</sqlMapGenerator>
<!-- 03 生成XxxMapper接口 -->
<!-- type="ANNOTATEDMAPPER",生成Java Model 和基于注解的Mapper对象 -->
<!-- type="MIXEDMAPPER",生成基于注解的Java Model 和相应的Mapper对象 -->
<!-- type="XMLMAPPER",生成SQLMap XML文件和独立的Mapper接口 -->
<javaClientGenerator targetPackage="com.xwt.ssm.mapper"
targetProject="src/main/java" type="XMLMAPPER">
<!-- 是否在当前路径下新加一层schema,false路径com.oop.eksp.user.model, true:com.oop.eksp.user.model.[schemaName] -->
<property name="enableSubPackages" value="false"/>
</javaClientGenerator>
<!-- 配置表信息 -->
<!-- schema即为数据库名 -->
<!-- tableName为对应的数据库表 -->
<!-- domainObjectName是要生成的实体类 -->
<!-- enable*ByExample是否生成 example类 -->
<!--<table schema="" tableName="t_book" domainObjectName="Book"-->
<!--enableCountByExample="false" enableDeleteByExample="false"-->
<!--enableSelectByExample="false" enableUpdateByExample="false">-->
<!--<!– 忽略列,不生成bean 字段 –>-->
<!--<!– <ignoreColumn column="FRED" /> –>-->
<!--<!– 指定列的java数据类型 –>-->
<!--<!– <columnOverride column="LONG_VARCHAR_FIELD" jdbcType="VARCHAR" /> –>-->
<!--</table>-->
<table schema="" tableName="t_shiro_user" domainObjectName="ShiroUser"
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_role" domainObjectName="ShiroRole"
enableCountByExample="false" enableDeleteByExample="false"
enableSelectByExample="false" enableUpdateByExample="false">
</table>
<table schema="" tableName="t_shiro_permission" domainObjectName="ShiroPermission"
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>
</context>
</generatorConfiguration>
生成以下文件
ShiroUserMapper.xml
<select id="queryByName" resultType="com.xwt.ssm.model.ShiroUser" parameterType="java.lang.String">
select
<include refid="Base_Column_List" />
from t_shiro_user
where userName = #{userName}
</select>
ShiroUserMapper.java
package com.xwt.ssm.mapper;
import com.xwt.ssm.model.ShiroUser;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
@Repository
public interface ShiroUserMapper {
int deleteByPrimaryKey(Integer userid);
int insert(ShiroUser record);
int insertSelective(ShiroUser record);
ShiroUser selectByPrimaryKey(Integer userid);
int updateByPrimaryKeySelective(ShiroUser record);
int updateByPrimaryKey(ShiroUser record);
ShiroUser queryByName(@Param("uname")String uname);
}
ShiroUserService.java
package com.xwt.ssm.service;
import com.xwt.ssm.model.ShiroUser;
/**
* @author XWT
* @site www.Xiao.com
* @company 卓京
* @create 2019-11-30 20:13
*/
public interface ShiroUserService {
ShiroUser queryByName(String uname);
}
ShiroUserServiceImpl.java
package com.xwt.ssm.service.impl;
import com.xwt.ssm.mapper.ShiroUserMapper;
import com.xwt.ssm.model.ShiroUser;
import com.xwt.ssm.service.ShiroUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* @author XWT
* @site www.Xiao.com
* @company 卓京
* @create 2019-11-30 20:15
*/
@Service("shiroUserService")
public class ShiroUserServiceImpl implements ShiroUserService {
@Autowired
private ShiroUserMapper shiroUserMapper;
@Override
public ShiroUser queryByName(String uname) {
return shiroUserMapper.queryByName(uname);
}
}
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.xwt.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"]
</value>
</property>
</bean>
<!-- Shiro生命周期,保证实现了Shiro内部lifecycle函数的bean执行 -->
<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
</beans>
在applicationContext.xml整合
<!--整合Shiro-->
<import resource="applicationContext-shiro.xml"></import>
MyRealm.java
package com.xwt.ssm.shiro;
import com.xwt.ssm.model.ShiroUser;
import com.xwt.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 XWT
* @site www.Xiao.com
* @company 卓京
* @create 2019-11-30 19:55
*
* 替换掉了上堂课的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();
ShiroUser shiroUser = this.shiroUserService.queryByName(uname);
AuthenticationInfo info = new SimpleAuthenticationInfo(
shiroUser.getUsername(),
shiroUser.getPassword(),
ByteSource.Util.bytes(shiroUser.getSalt()),
this.getName()
);
return info;
}
}
ShiroUserController.java
package com.xwt.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;
/**
* @author XWT
* @site www.Xiao.com
* @company 卓京
* @create 2019-12-01 14:23
*/
@Controller
public class ShiroUserController {
@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";
}
}
导入上一篇博客所用的jsp
运行:
盐加密
**盐加密工具类,在做新增用户的时候使用,将加密后的密码、及加密时候的盐放入数据库;
**
PasswordHelper.java
package com.xwt.ssm.utils;
import org.apache.shiro.crypto.RandomNumberGenerator;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
/**
* @author XWT
* @site www.Xiao.com
* @company 卓京
* @create 2019-11-30 20:30
*/
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);
}
}