目录:
shiro认证,
盐加密
今天整合ssm和shiro,完成登录、注册的密码加密 首先一样需要导入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>
然后需要配置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>
ShiroUser
package com.liuxia.ssm.model;
import java.util.Date;
public class ShiroUser {
private Integer userid;
private String username;
private String password;
private String salt;
private Date createdate;
public ShiroUser(Integer userid, String username, String password, String salt, Date createdate) {
this.userid = userid;
this.username = username;
this.password = password;
this.salt = salt;
this.createdate = createdate;
}
public ShiroUser() {
super();
}
public Integer getUserid() {
return userid;
}
public void setUserid(Integer userid) {
this.userid = userid;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getSalt() {
return salt;
}
public void setSalt(String salt) {
this.salt = salt;
}
public Date getCreatedate() {
return createdate;
}
public void setCreatedate(Date createdate) {
this.createdate = createdate;
}
@Override
public String toString() {
return "ShiroUser{" +
"userid=" + userid +
", username='" + username + '\'' +
", password='" + password + '\'' +
", salt='" + salt + '\'' +
", createdate=" + createdate +
'}';
}
}
ShiroUserService
package com.liuxia.ssm.service;
import com.liuxia.ssm.model.ShiroUser;
import com.liuxia.ssm.model.ShiroUser;
import java.util.Set;
public interface ShiroUserService {
public ShiroUser queryByName(String userName);
}
ShiroUserServiceImpl
package com.liuxia.ssm.service.impl;
import com.liuxia.ssm.mapper.ShiroUserMapper;
import com.liuxia.ssm.model.ShiroUser;
import com.liuxia.ssm.service.ShiroUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Set;
@Service("shiroUserService")
public class ShiroUserServiceImpl implements ShiroUserService {
@Autowired
private ShiroUserMapper shiroUserMapper;
@Override
public ShiroUser queryByName(String userName) {
return shiroUserMapper.queryByName(userName);
}
}
PasswordHelper
package com.liuxia.ssm.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);
}
}
MyRealm
package com.liuxia.ssm.shiro;
import com.liuxia.ssm.model.ShiroUser;
import com.liuxia.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.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
/**
* MyRealm这个类替换掉了上堂课的ini文件,所有的身份数据源
*/
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 {
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;
}
}
ShiroUserController
package com.liuxia.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.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Controller
public class ShiroUserController {
@Autowired
private ShiroUserService shiroUserService;
@RequestMapping("/login")
public String login(HttpServletRequest req, HttpServletResponse resp){
Subject subject = SecurityUtils.getSubject();
String uname = req.getParameter("username");
String pwd = req.getParameter("password");
UsernamePasswordToken token = new UsernamePasswordToken(uname, pwd);
try {
subject.login(token);
req.setAttribute("uname",uname);
return "main";
}catch (Exception e){
req.setAttribute("message","用户名或密码错误");
return "login";
}
}
@RequestMapping("/logout")
public String logout(HttpServletRequest req, HttpServletResponse resp){
Subject subject = SecurityUtils.getSubject();
subject.logout();
return "login";
}
/**
* 把加密后的密码存入数据库中
* @param req
* @param resp
* @return
*/
@RequestMapping("/register")
public String register(HttpServletRequest req, HttpServletResponse resp){
String uname = req.getParameter("username");
String pwd = req.getParameter("password");
String salt = PasswordHelper.createSalt();
String credentials = PasswordHelper.createCredentials(pwd, salt);
ShiroUser shiroUser=new ShiroUser();
shiroUser.setUsername(uname);
shiroUser.setPassword(credentials);
shiroUser.setSalt(salt);
int insert = shiroUserService.insert(shiroUser);
if(insert>0){
req.setAttribute("message","注册成功");
return "login";
}
else{
req.setAttribute("message","注册失败");
return "login";
}
}
}
login.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<script type="text/javascript">
function register(){
}
</script>
<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="button" οnclick="location.href='${pageContext.request.contextPath}/register.jsp'" value="注册">
<input type="reset" value="重置">
</form>
</body>
</html>
register.jsp
<%--
Created by IntelliJ IDEA.
User: 234
Date: 2019/11/3
Time: 22:28
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>用户注册</title>
</head>
<body>
<h1>用户注册</h1>
<form action="${pageContext.request.contextPath}/register" method="post">
帐号:<input type="text" name="username"><br>
密码:<input type="password" name="password"><br>
<input type="submit" value="注册">
<input type="button" οnclick="location.href='${pageContext.request.contextPath}/login.jsp'" value="返回">
</form>
</body>
</html>