shiro认证
Pom依赖
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>${shiro.version}</version>
</dependency>
<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过滤器定义 -->
<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>逆向生产对应实体,mapper接口,*mapper.xml
<!--<table schema="" tableName="t_sys_role_permission" domainObjectName="SysRolePermission"-->
<!--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_sys_user" domainObjectName="SysUser"-->
<!--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_sys_role" domainObjectName="SysRole"-->
<!--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_sys_user_role" domainObjectName="SysUserRole"-->
<!--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_sys_permission" domainObjectName="SysPermission"-->
<!--enableCountByExample="false" enableDeleteByExample="false"-->
<!--enableSelectByExample="false" enableUpdateByExample="false">-->
<!--<!– 忽略列,不生成bean 字段 –>-->
<!--<!– <ignoreColumn column="FRED" /> –>-->
<!--<!– 指定列的java数据类型 –>-->
<!--<!– <columnOverride column="LONG_VARCHAR_FIELD" jdbcType="VARCHAR" /> –>-->
<!--</table>-->

SysUserMapper
package com.hmc.mapper;
import com.hmc.model.ShiroUser;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
@Repository
public interface SysUserMapper{
int deleteByPrimaryKey(Integer userid);
int insert(SysUser record);
int insertSelective(SysUser record);
ShiroUser selectByPrimaryKey(Integer userid);
int updateByPrimaryKeySelective(SysUser record);
int updateByPrimaryKey(SysUser record);
ShiroUser queryByName(@Param("username")String username); 2223 }SysUserMapper.xml
<select id="queryByName" resultType="com.hmc.model.ShiroUser" parameterType="java.lang.String" >
select
<include refid="Base_Column_List" />
from t_shiro_user
where username = #{uname}
</select>ISysUserService
package com.hmc.service;
import com.hmc.model.SysUser;
import org.apache.ibatis.annotations.Param;
public interface ISysUserService {
ShiroUser queryByName(@Param("username")String username);
int insert(SysUser record);
}IBookServiceImpl
@Service
public class SysUserServiceImpl implements ISysUserService {
@Autowired
private SysUserMapper sysUserMapper;
@Override
public SysUser queryByName(String username) { return sysUserMapper.userLogin(username); } }public class ShiroRealm extends AuthorizingRealm{
@Autowired
private ISysUserService sysUserService;
//授权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
}
//认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
String username = token.getPrincipal().toString();
String password = token.getPrincipal().toString();
//根据用户名获取对应的用户信息
SysUser sysUser = sysUserService.userLogin(username);
// if (null==sysUser){
// throw new UnknownAccountException();
// }
//密码多次校验
System.out.println(sysUser);
SimpleAuthenticationInfo simpleAuthenticationInfo=new SimpleAuthenticationInfo(
sysUser.getUsername(),
sysUser.getPassword(),
//盐
ByteSource.Util.bytes(sysUser.getSalt()),
this.getName()
);
return simpleAuthenticationInfo;
}
}spring-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.zking.ssm.shiro.ShiroRealm">
<!--配置Shiro明文密码如何进行加密-->
<!--注意:重要的事情说三次~~~~~~此处加密方式要与用户注册时的算法一致 -->
<!--注意:重要的事情说三次~~~~~~此处加密方式要与用户注册时的算法一致 -->
<!--注意:重要的事情说三次~~~~~~此处加密方式要与用户注册时的算法一致 -->
<!--以下三个配置告诉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="/home/index.shtml"/>-->
<!-- 身份验证成功,跳转到指定页面 -->
<!--<property name="successUrl" value="/index.jsp"/>-->
<!-- 权限验证失败,跳转到指定页面 -->
<!--<property name="unauthorizedUrl" value="/user/noauthorizeUrl"/>-->
<!-- Shiro连接约束配置,即过滤链的定义 -->
<!-- <property name="filterChainDefinitions">
</property>-->
</bean>
<!-- Shiro生命周期,保证实现了Shiro内部lifecycle函数的bean执行 -->
<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
</beans>UserController
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private ISysUserService sysUserService;
@RequestMapping("/userLogin")
public String userLogin(SysUser sysUser, Model moodel){
String username = sysUser.getUsername();
String password = sysUser.getPassword();
//获取主体
Subject subject= SecurityUtils.getSubject();
//创建用户密码token
UsernamePasswordToken token=new UsernamePasswordToken(
username,
password
);
String meassage=null;
try{
subject.login(token);
}catch (IncorrectCredentialsException e){
e.printStackTrace();
meassage="密码错误";
}catch (UnknownAccountException e){
e.printStackTrace();
meassage="账号错误";
}catch (Exception e){
e.printStackTrace();
meassage="账号或者密码错误";
}
if(null==meassage){
return "index";
}
else{
moodel.addAttribute("message",meassage);
return "login";
}
}
//退出登录
@RequestMapping("/logout")
public String logout(){
//关键代码
Subject subject=SecurityUtils.getSubject();
subject.logout();
return "login";
}
//用户注册
@RequestMapping("/register")
public String register(SysUser sysUser){
//盐
String salt = PasswordHelper.createSalt();
//加密后的密码
String credentials = PasswordHelper.createCredentials(sysUser.getPassword(), salt);
sysUser.setPassword(credentials);
sysUser.setSalt(salt);
System.out.println(sysUser);
sysUserService.InsetSysUser(sysUser);
return "login";
}
}盐加密的工具类
PasswordHelper
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);
//明文密码
//盐:23179a0d1d4cedf3e1e1f9bf2bf5984c 密文密码:43aedf85e33f2047efc4817bceaad5b5
}
}Jsp页面
login.jsp
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2019/11/2 0002
Time: 21:43
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<body>
</head>
<h1>用户登陆</h1>
<div style="color: red">${message}</div>
<form action="${pageContext.request.contextPath}/user/userLogin" method="post">
帐号:<input type="text" name="username"><br>
密码:<input type="password" name="password"><br>
<input type="submit" value="确定">
<input type="reset" value="重置">
</form>
<a href="${pageContext.request.contextPath}/register">注册</a>
</body>
</html>register.jsp
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2019/11/2 0002
Time: 21:43
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<body>
</head>
<h1>用户注册</h1>
<div style="color: red">${message}</div>
<form action="${pageContext.request.contextPath}/user/register" 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>main.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %><%@taglib prefix="t" uri="http://www.springframework.org/tags" %><%@taglib prefix="shiro" uri="http://shiro.apache.org/tags" %><html><head> <%@ include file="/common/head.jsp"%></head><body><h1></h1><%--index<a href="${ctx}/changeLocale?locale=zh">chinese</a><a href="${ctx}/changeLocale?locale=en">english</a>--%><br><a href="${ctx}/book/toAdd">书本新增</a><br><shiro:hasRole name="高级用户"><a href="${ctx}/book/list">书本查询</a><br></shiro:hasRole><a href="${ctx}/book/list1">查询书本列表,返回JSON数据格式</a><br><a href="${ctx}/book/list2">分页查询</a><br><a href="${ctx}/book/singleBook?bookid=2">查询单个对象</a><br><h1>用户管理</h1><ul> <shiro:hasPermission name="system:user:query"> <li>用户查询</li> </shiro:hasPermission><shiro:hasPermission name="system:user:add"> <li>用户新增</li></shiro:hasPermission><shiro:hasPermission name="system:user:edit"> <li>用户修改</li></shiro:hasPermission><shiro:hasPermission name="system:user:del"> <li>用户删除</li></shiro:hasPermission></ul><%--<img src="images/2.jpg"><div> <a href="/user/logout">安全退出</a></div>--%></body></html>

相关推荐
杜鲁门 2020-11-05
luckyxl0 2020-08-16
Dullonjiang 2020-08-09
xclxcl 2020-08-03
zmzmmf 2020-08-03
MicroBoy 2020-08-02
ganjing 2020-08-02
likesyour 2020-08-01
zmzmmf 2020-07-09
MicroBoy 2020-07-05
zzhao 2020-06-26
子云 2020-06-18
visionzheng 2020-06-07
neweastsun 2020-06-04
ErixHao 2020-06-03
GDreams0 2020-06-01
ganjing 2020-05-29
zmzmmf 2020-05-28
nullcy 2020-05-26