登录token
This commit is contained in:
120
src/main/java/com/lovenav/utils/RandomValidateCode.java
Normal file
120
src/main/java/com/lovenav/utils/RandomValidateCode.java
Normal file
@@ -0,0 +1,120 @@
|
||||
package com.lovenav.utils;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import javax.servlet.http.HttpSession;
|
||||
|
||||
import javax.imageio.ImageIO;
|
||||
import java.awt.*;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.util.Random;
|
||||
|
||||
/**
|
||||
* 工具类: 生成随机验证码
|
||||
*/
|
||||
public class RandomValidateCode {
|
||||
public static final String RANDOMVALIDATECODE = "RandomValidateCode";// 放到session中的key
|
||||
private Random random = new Random();
|
||||
private String randString = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";//随机产生的字符串
|
||||
private int width = 80;// 图片宽度
|
||||
private int height = 26;// 图片高度
|
||||
private int lineSize = 40;// 干扰线数量
|
||||
private int stringNum = 4;// 随机产生的字符数量
|
||||
|
||||
/**
|
||||
* 获得字体
|
||||
*/
|
||||
private Font getFont() {
|
||||
return new Font("Fixedsys", Font.CENTER_BASELINE, 18);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获得颜色
|
||||
*
|
||||
* @param bc
|
||||
* @param fc
|
||||
*/
|
||||
private Color getRandColor(int fc, int bc) {
|
||||
if (fc > 255)
|
||||
fc = 255;
|
||||
if (bc > 255)
|
||||
bc = 255;
|
||||
int r = fc + random.nextInt(bc - fc - 16);
|
||||
int g = fc + random.nextInt(bc - fc - 14);
|
||||
int b = fc + random.nextInt(bc - fc - 18);
|
||||
return new Color(r, g, b);
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成随机图片
|
||||
*
|
||||
* @param request
|
||||
* @param response
|
||||
*/
|
||||
public void getRandcode(HttpServletRequest request, HttpServletResponse response) {
|
||||
HttpSession session = request.getSession();
|
||||
// BufferedImage类是具有缓冲区的Image类,Image类是用于描述图像信息的类
|
||||
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
|
||||
Graphics g = image.getGraphics();// 产生Image对象的Graphics对象,该对象可以在图像上进行各种绘制操作
|
||||
g.fillRect(0, 0, width, height);
|
||||
g.setFont(new Font("Times New Roman", Font.ROMAN_BASELINE, 18));
|
||||
g.setColor(getRandColor(110, 133));
|
||||
// 绘制干扰线
|
||||
for (int i = 0; i <= lineSize; i++) {
|
||||
drowLine(g);
|
||||
}
|
||||
// 绘制随机字符
|
||||
String randomString = "";
|
||||
for (int i = 1; i <= stringNum; i++) {
|
||||
randomString = drowString(g, randomString, i);
|
||||
}
|
||||
request.getSession(true);
|
||||
session.removeAttribute(RANDOMVALIDATECODE);
|
||||
session.setAttribute(RANDOMVALIDATECODE, randomString);
|
||||
g.dispose();
|
||||
try {
|
||||
ImageIO.write(image, "JPEG", response.getOutputStream());// 将内存中的图片通过流动形式输出到客户端
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 绘制字符串
|
||||
*
|
||||
* @param g
|
||||
* @param randomString
|
||||
* @param i
|
||||
*/
|
||||
private String drowString(Graphics g, String randomString, int i) {
|
||||
g.setFont(getFont());
|
||||
g.setColor(new Color(random.nextInt(101), random.nextInt(111), random.nextInt(121)));
|
||||
String rand = getRandomString(random.nextInt(randString.length()));
|
||||
randomString += rand;
|
||||
g.translate(random.nextInt(3), random.nextInt(3));
|
||||
g.drawString(rand, 13 * i, 16);
|
||||
return randomString;
|
||||
}
|
||||
|
||||
/**
|
||||
* 绘制干扰线
|
||||
*
|
||||
* @param g
|
||||
*/
|
||||
private void drowLine(Graphics g) {
|
||||
int x = random.nextInt(width);
|
||||
int y = random.nextInt(height);
|
||||
int xl = random.nextInt(13);
|
||||
int yl = random.nextInt(15);
|
||||
g.drawLine(x, y, x + xl, y + yl);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取随机的字符
|
||||
*
|
||||
* @param num
|
||||
*/
|
||||
public String getRandomString(int num) {
|
||||
return String.valueOf(randString.charAt(num));
|
||||
}
|
||||
}
|
125
src/main/java/com/lovenav/utils/TokenUtils.java
Normal file
125
src/main/java/com/lovenav/utils/TokenUtils.java
Normal file
@@ -0,0 +1,125 @@
|
||||
package com.lovenav.utils;
|
||||
|
||||
import com.auth0.jwt.JWT;
|
||||
import com.auth0.jwt.JWTVerifier;
|
||||
import com.auth0.jwt.algorithms.Algorithm;
|
||||
import com.auth0.jwt.exceptions.JWTDecodeException;
|
||||
import com.auth0.jwt.interfaces.DecodedJWT;
|
||||
import com.lovenav.entity.User;
|
||||
import com.lovenav.service.UserService;
|
||||
|
||||
|
||||
|
||||
import io.jsonwebtoken.*;
|
||||
import org.apache.tomcat.util.codec.binary.Base64;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import javax.crypto.SecretKey;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
@Component
|
||||
public class TokenUtils {
|
||||
|
||||
private static final long EXPIRE_TIME = 60 * 1000; // 1分钟
|
||||
// private static final long EXPIRE_TIME = 15 * 60 * 1000; // 15分钟
|
||||
|
||||
// 加密密文,私钥
|
||||
private static final String TOKEN_SECRET = "jiamimiwen";
|
||||
|
||||
// 由字符串生成加密key
|
||||
public SecretKey generalKey() {
|
||||
System.out.println("进入由字符串生成加密key方法!");
|
||||
// 本地的密码解码
|
||||
byte[] encodedKey = Base64.decodeBase64(TOKEN_SECRET);
|
||||
// 根据给定的字节数组使用AES加密算法构造一个密钥
|
||||
SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
|
||||
return key;
|
||||
}
|
||||
|
||||
// 生成签名
|
||||
public String sign(User user) {
|
||||
System.out.println("生成签名方法开始执行!");
|
||||
try {
|
||||
// 设置过期时间,单位毫秒
|
||||
Date expTime = new Date(System.currentTimeMillis() + EXPIRE_TIME);
|
||||
// 私钥和加密算法
|
||||
Algorithm algorithm = Algorithm.HMAC256(user.getUserPassword()); //使用用户输入的密码
|
||||
// Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
|
||||
// 设置头部信息,也可以不用设置头部信息jwt会自动生成
|
||||
// Map<String, Object> header = new HashMap<String, Object>();
|
||||
// header.put("typ", "JWT");
|
||||
// header.put("alg", "HS256");
|
||||
// 或
|
||||
// header.put("Type", "JWT");
|
||||
// header.put("alg", "HS256");
|
||||
// 生成JWT的时间
|
||||
Date issuedAt = new Date(System.currentTimeMillis());
|
||||
// 返回token字符串
|
||||
System.out.println("生成签名方法结束执行!");
|
||||
return JWT.create() // 表示new一个Jwt,设置jwt的body
|
||||
// .withHeader(header) // 设置头部信息
|
||||
.withClaim("userLogin", user.getUserLogin()) // 数据库中用户的id
|
||||
.withClaim("email", user.getUserEmail()) // 前端输入的用户名
|
||||
.withIssuedAt(issuedAt) // jwt的签发时间
|
||||
.withExpiresAt(expTime) // jwt过期时间
|
||||
.sign(algorithm);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @Title: verify
|
||||
* @Description: 检验token是否正确
|
||||
* @param: @param token 密钥
|
||||
* @param: @param username 登录名
|
||||
* @param: @param password 密码
|
||||
* @param: @return
|
||||
* @return: boolean
|
||||
* @throws
|
||||
*/
|
||||
public boolean verify(String token, String username, String password) {
|
||||
System.out.println("进入检验token是否正确方法!");
|
||||
try {
|
||||
Algorithm algorithm = Algorithm.HMAC256(password); //使用用户输入的密码
|
||||
// Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
|
||||
JWTVerifier verifier = JWT.require(algorithm).withClaim("username", username).build();
|
||||
// JWTVerifier verifier = JWT.require(algorithm).build();
|
||||
verifier.verify(token);
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// 获取登录名
|
||||
public String getUsername(String token) {
|
||||
System.out.println("进入获取登录名方法!");
|
||||
try {
|
||||
DecodedJWT jwt = JWT.decode(token);
|
||||
return jwt.getClaim("username").asString();
|
||||
} catch (JWTDecodeException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// 解密jwt
|
||||
public Claims parseJWT(String jwt) throws Exception {
|
||||
System.out.println("进入解密jwt方法!");
|
||||
SecretKey key = generalKey(); // 签名秘钥,和生成的签名的秘钥一模一样
|
||||
Claims claims = Jwts.parser() // 得到DefaultJwtParser
|
||||
.setSigningKey(key) // 设置签名的秘钥
|
||||
.parseClaimsJws(jwt).getBody(); // 设置需要解析的jwt
|
||||
return claims;
|
||||
}
|
||||
|
||||
|
||||
}
|
Reference in New Issue
Block a user