Jwt生成的token令牌概述
1.有状态登陆和无状态登陆
- 有状态服务,即服务端需要记录每次会话的客户端信息,从而识别客户端身份,根据用户身份进行请求的处理,如tomcat中的session
- 无状态尤其使用在微服务对外提供restful风接口
- 服务端不保存任何客户端请求者信息
- 客户端的每次请求必须具备自描述信息,通过这些信息识别客户端身份
2.为什莫不使用session
- 因为session只能针对一台服务器
3.jwt生成的token的组成
- 载荷包含了:令牌的发出者 存储的属性 过期时间等
- 签名是为了验证该令牌是否有效
4.对称与非对称加密
- 对称加密,如AES
- 优势:算法公开、计算量小、加密速度快、加密效率高
- 缺陷:双方都使用同样密钥,安全性得不到保证
- 非对称加密,如RSA
- 优点:安全,难以破解
- 缺点:算法比较耗时
- 不可逆加密,如MD5,SHA
- jwt生成token时将采用非对称加密 用私钥生成令牌 公钥去解密 因为一旦私钥泄露 就很容易伪造token
一.准备工作
1.依赖
<!--jwt的依赖-->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.0</version>
</dependency>
<!--在设置jwt参数时解析当前时间的工具类-->
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
</dependency>
2.jwt生成的token中载荷要包含的属性 将其封装成一个实体类
/**
* 载荷对象
*/
public class UserInfo {
private Long id;
private String username;
public UserInfo() {
}
public UserInfo(Long id, String username) {
this.id = id;
this.username = username;
}
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
二.工具类
1.JwtConstans
- jwt的配置 改配置属性的值和载荷实体类的属性名字相同
public abstract class JwtConstans {
public static final String JWT_KEY_ID = "id";
public static final String JWT_KEY_USER_NAME = "username";
}
2.RsaUtils
- 生成公钥和私钥的工具类
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
public class RsaUtils {
/**
* 从文件中读取公钥
*
* @param filename 公钥保存路径,相对于classpath
* @return 公钥对象
* @throws Exception
*/
public static PublicKey getPublicKey(String filename) throws Exception {
byte[] bytes = readFile(filename);
return getPublicKey(bytes);
}
/**
* 从文件中读取密钥
*
* @param filename 私钥保存路径,相对于classpath
* @return 私钥对象
* @throws Exception
*/
public static PrivateKey getPrivateKey(String filename) throws Exception {
byte[] bytes = readFile(filename);
return getPrivateKey(bytes);
}
/**
* 获取公钥
*
* @param bytes 公钥的字节形式
* @return
* @throws Exception
*/
public static PublicKey getPublicKey(byte[] bytes) throws Exception {
X509EncodedKeySpec spec = new X509EncodedKeySpec(bytes);
KeyFactory factory = KeyFactory.getInstance("RSA");
return factory.generatePublic(spec);
}
/**
* 获取密钥
*
* @param bytes 私钥的字节形式
* @return
* @throws Exception
*/
public static PrivateKey getPrivateKey(byte[] bytes) throws Exception {
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(bytes);
KeyFactory factory = KeyFactory.getInstance("RSA");
return factory.generatePrivate(spec);
}
/**
* 根据密文,生存rsa公钥和私钥,并写入指定文件
*
* @param publicKeyFilename 公钥文件路径
* @param privateKeyFilename 私钥文件路径
* @param secret 生成密钥的密文
* @throws IOException
* @throws NoSuchAlgorithmException
*/
public static void generateKey(String publicKeyFilename, String privateKeyFilename, String secret) throws Exception {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
SecureRandom secureRandom = new SecureRandom(secret.getBytes());
keyPairGenerator.initialize(1024, secureRandom);
KeyPair keyPair = keyPairGenerator.genKeyPair();
// 获取公钥并写出
byte[] publicKeyBytes = keyPair.getPublic().getEncoded();
writeFile(publicKeyFilename, publicKeyBytes);
// 获取私钥并写出
byte[] privateKeyBytes = keyPair.getPrivate().getEncoded();
writeFile(privateKeyFilename, privateKeyBytes);
}
private static byte[] readFile(String fileName) throws Exception {
return Files.readAllBytes(new File(fileName).toPath());
}
private static void writeFile(String destPath, byte[] bytes) throws IOException {
File dest = new File(destPath);
if (!dest.exists()) {
dest.createNewFile();
}
Files.write(dest.toPath(), bytes);
}
}
3.JwtUtils
- 生成和解析jwt生成的token
import com.yzx.shop.auth.entity.UserInfo;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.joda.time.DateTime;
import java.security.PrivateKey;
import java.security.PublicKey;
public class JwtUtils {
/**
* 私钥加密token
*
* @param userInfo 载荷中的数据
* @param privateKey 私钥
* @param expireMinutes 过期时间,单位秒
* @return
* @throws Exception
*/
public static String generateToken(UserInfo userInfo, PrivateKey privateKey, int expireMinutes) throws Exception {
return Jwts.builder()
.claim(JwtConstans.JWT_KEY_ID, userInfo.getId())
.claim(JwtConstans.JWT_KEY_USER_NAME, userInfo.getUsername())
.setExpiration(DateTime.now().plusMinutes(expireMinutes).toDate())
.signWith(SignatureAlgorithm.RS256, privateKey)
.compact();
}
/**
* 私钥加密token
*
* @param userInfo 载荷中的数据
* @param privateKey 私钥字节数组
* @param expireMinutes 过期时间,单位秒
* @return
* @throws Exception
*/
public static String generateToken(UserInfo userInfo, byte[] privateKey, int expireMinutes) throws Exception {
return Jwts.builder()
.claim(JwtConstans.JWT_KEY_ID, userInfo.getId())
.claim(JwtConstans.JWT_KEY_USER_NAME, userInfo.getUsername())
.setExpiration(DateTime.now().plusMinutes(expireMinutes).toDate())
.signWith(SignatureAlgorithm.RS256, RsaUtils.getPrivateKey(privateKey))
.compact();
}
/**
* 公钥解析token
*
* @param token 用户请求中的token
* @param publicKey 公钥
* @return
* @throws Exception
*/
private static Jws<Claims> parserToken(String token, PublicKey publicKey) {
return Jwts.parser().setSigningKey(publicKey).parseClaimsJws(token);
}
/**
* 公钥解析token
*
* @param token 用户请求中的token
* @param publicKey 公钥字节数组
* @return
* @throws Exception
*/
private static Jws<Claims> parserToken(String token, byte[] publicKey) throws Exception {
return Jwts.parser().setSigningKey(RsaUtils.getPublicKey(publicKey))
.parseClaimsJws(token);
}
/**
* 获取token中的用户信息
*
* @param token 用户请求中的令牌
* @param publicKey 公钥
* @return 用户信息
* @throws Exception
*/
public static UserInfo getInfoFromToken(String token, PublicKey publicKey) throws Exception {
Jws<Claims> claimsJws = parserToken(token, publicKey);
Claims body = claimsJws.getBody();
return new UserInfo(
ObjectUtils.toLong(body.get(JwtConstans.JWT_KEY_ID)),
ObjectUtils.toString(body.get(JwtConstans.JWT_KEY_USER_NAME))
);
}
/**
* 获取token中的用户信息
*
* @param token 用户请求中的令牌
* @param publicKey 公钥
* @return 用户信息
* @throws Exception
*/
public static UserInfo getInfoFromToken(String token, byte[] publicKey) throws Exception {
Jws<Claims> claimsJws = parserToken(token, publicKey);
Claims body = claimsJws.getBody();
return new UserInfo(
ObjectUtils.toLong(body.get(JwtConstans.JWT_KEY_ID)),
ObjectUtils.toString(body.get(JwtConstans.JWT_KEY_USER_NAME))
);
}
}
4.CookieUtils
- 读取和写入cookie里存的token
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
/**
*
* Cookie 工具类
*
*/
public final class CookieUtils {
static final Logger logger = LoggerFactory.getLogger(CookieUtils.class);
/**
* 得到Cookie的值, 不编码
*
* @param request
* @param cookieName
* @return
*/
public static String getCookieValue(HttpServletRequest request, String cookieName) {
return getCookieValue(request, cookieName, false);
}
/**
* 得到Cookie的值,
*
* @param request
* @param cookieName
* @return
*/
public static String getCookieValue(HttpServletRequest request, String cookieName, boolean isDecoder) {
Cookie[] cookieList = request.getCookies();
if (cookieList == null || cookieName == null){
return null;
}
String retValue = null;
try {
for (int i = 0; i < cookieList.length; i++) {
if (cookieList[i].getName().equals(cookieName)) {
if (isDecoder) {
retValue = URLDecoder.decode(cookieList[i].getValue(), "UTF-8");
} else {
retValue = cookieList[i].getValue();
}
break;
}
}
} catch (UnsupportedEncodingException e) {
logger.error("Cookie Decode Error.", e);
}
return retValue;
}
/**
* 得到Cookie的值,
*
* @param request
* @param cookieName
* @return
*/
public static String getCookieValue(HttpServletRequest request, String cookieName, String encodeString) {
Cookie[] cookieList = request.getCookies();
if (cookieList == null || cookieName == null){
return null;
}
String retValue = null;
try {
for (int i = 0; i < cookieList.length; i++) {
if (cookieList[i].getName().equals(cookieName)) {
retValue = URLDecoder.decode(cookieList[i].getValue(), encodeString);
break;
}
}
} catch (UnsupportedEncodingException e) {
logger.error("Cookie Decode Error.", e);
}
return retValue;
}
/**
* 生成cookie,并指定编码
* @param request 请求
* @param response 响应
* @param cookieName name
* @param cookieValue value
* @param encodeString 编码
*/
public static final void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName, String cookieValue, String encodeString) {
setCookie(request,response,cookieName,cookieValue,null,encodeString, null);
}
/**
* 生成cookie,并指定生存时间
* @param request 请求
* @param response 响应
* @param cookieName name
* @param cookieValue value
* @param cookieMaxAge 生存时间
*/
public static final void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName, String cookieValue, Integer cookieMaxAge) {
setCookie(request,response,cookieName,cookieValue,cookieMaxAge,null, null);
}
/**
* 设置cookie,不指定httpOnly属性
*/
public static final void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName, String cookieValue, Integer cookieMaxAge, String encodeString) {
setCookie(request,response,cookieName,cookieValue,cookieMaxAge,encodeString, null);
}
/**
* 设置Cookie的值,并使其在指定时间内生效
*
* @param cookieMaxAge
* cookie生效的最大秒数
*/
public static final void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName, String cookieValue, Integer cookieMaxAge, String encodeString, Boolean httpOnly) {
try {
if(StringUtils.isBlank(encodeString)) {
encodeString = "utf-8";
}
if (cookieValue == null) {
cookieValue = "";
} else {
cookieValue = URLEncoder.encode(cookieValue, encodeString);
}
Cookie cookie = new Cookie(cookieName, cookieValue);
if (cookieMaxAge != null && cookieMaxAge > 0)
cookie.setMaxAge(cookieMaxAge);
if (null != request)// 设置域名的cookie
cookie.setDomain(getDomainName(request));
cookie.setPath("/");
if(httpOnly != null) {
cookie.setHttpOnly(httpOnly);
}
response.addCookie(cookie);
} catch (Exception e) {
logger.error("Cookie Encode Error.", e);
}
}
/**
* 得到cookie的域名
*/
private static final String getDomainName(HttpServletRequest request) {
String domainName = null;
String serverName = request.getRequestURL().toString();
if (serverName == null || serverName.equals("")) {
domainName = "";
} else {
if(request.getMethod().toUpperCase().equals("GET")){
domainName=request.getHeader("Referer").split("/")[2];
}else {
domainName=request.getHeader("Origin").split("//")[1];
}
}
return domainName;
}
}
注意:以上几个工具类可以拿来直接使用
三.测试
1.生成公钥与私钥
@SpringBootTest
@RunWith(SpringRunner.class)
public class JwtTest {
//生成公钥的路径
private static final String pubKeyPath = "C:\\tmp\\rsa\\rsa.pub";
//生成私钥的路径
private static final String priKeyPath = "C:\\tmp\\rsa\\rsa.pri";
@Test
public void testRsa() throws Exception {
//生成公钥和私钥
//234指的时加密时的盐 越复杂越好
RsaUtils.generateKey(pubKeyPath, priKeyPath, "234");
}
}
2.测试获得刚才生成的公钥与私钥
@SpringBootTest
@RunWith(SpringRunner.class)
public class JwtTest {
//生成公钥的路径
private static final String pubKeyPath = "C:\\tmp\\rsa\\rsa.pub";
//生成私钥的路径
private static final String priKeyPath = "C:\\tmp\\rsa\\rsa.pri";
//生成的公钥
private PublicKey publicKey;
//生成的私钥
private PrivateKey privateKey;
@Test
public void testGetRsa() throws Exception {
//获得公钥和私钥
this.publicKey = RsaUtils.getPublicKey(pubKeyPath);
this.privateKey = RsaUtils.getPrivateKey(priKeyPath);
}
}
3.测试生成token
@SpringBootTest
@RunWith(SpringRunner.class)
public class JwtTest {
//生成公钥的路径
private static final String pubKeyPath = "C:\\tmp\\rsa\\rsa.pub";
//生成私钥的路径
private static final String priKeyPath = "C:\\tmp\\rsa\\rsa.pri";
//生成的公钥
private PublicKey publicKey;
//生成的私钥
private PrivateKey privateKey;
@Before
public void testGetRsa() throws Exception {
//获得公钥和私钥
this.publicKey = RsaUtils.getPublicKey(pubKeyPath);
this.privateKey = RsaUtils.getPrivateKey(priKeyPath);
}
@Test
public void testGenerateToken() throws Exception {
// 生成token
String token = JwtUtils.generateToken(new UserInfo(20L, "jack"), privateKey, 5);
System.out.println("token = " + token);
/*
* 一般在登陆后或者每次刷新访问都会重新会写入cookie 因为是test所有没有HttpservletRequest和HttpservletRespone 所以就没写这步
* CookieUtils.setCookie(request,response,"Cookie名字",token,过期时间,"utf-8",true);
*/
}
}
4.测试解析token
@SpringBootTest
@RunWith(SpringRunner.class)
public class JwtTest {
//生成公钥的路径
private static final String pubKeyPath = "C:\\tmp\\rsa\\rsa.pub";
//生成私钥的路径
private static final String priKeyPath = "C:\\tmp\\rsa\\rsa.pri";
//生成的公钥
private PublicKey publicKey;
//生成的私钥
private PrivateKey privateKey;
@Before
public void testGetRsa() throws Exception {
//获得公钥和私钥
this.publicKey = RsaUtils.getPublicKey(pubKeyPath);
this.privateKey = RsaUtils.getPrivateKey(priKeyPath);
}
@Test
public void testParseToken() throws Exception {
/*
* 一般在要访问用户登陆后才可以访问的内容 都会去从cookie中取出token解析 因为是test所有没有HttpservletRequest和HttpservletRespone 所以就没写这步
* String token= CookieUtils.getCookieValue(request,"Cookie名称");
*/
//该token是刚才测试生成token打印的
String token = "eyJhbGciOiJSUzI1NiJ9.eyJpZCI6MjAsInVzZXJuYW1lIjoiamFjayIsImV4cCI6MTUzMzI4MjQ3N3 0.EPo35Vyg1IwZAtXvAx2TCWuOPnRwPclRNAM4ody5CHk8RF55wdfKKJxjeGh4H3zgruRed9mEOQzWy7 9iF1nGAnvbkraGlD6iM-9zDW8M1G9if4MX579Mv1x57lFewzEo-zKnPdFJgGlAPtNWDPv4iKvbKOk1- U7NUtRmMsF1Wcg";
// 解析token
UserInfo user = JwtUtils.getInfoFromToken(token, publicKey);
System.out.println("id: " + user.getId());
System.out.println("userName: " + user.getUsername());
/*
* 验证成功一般还会用JwtUtil重新生成cookie 再用CookieUtil存入cookie 来刷新过期时间
*
* jwtProperties是把jwt的这些信息写入了配置文件 然后用@ConfigurationProperties读取成一个配置实体类
* 再用@EnableConfigurationProperties注解要注入该配置的类 然后才可以用@Autowired注入该配置实体类
* String newToken = JwtUtils.generateToken(userInfo, jwtProperties.getPrivateKey(), jwtProperties.getExpire());
*
* CookieUtils.setCookie(request,response,jwtProperties.getCookieName(),newToken,jwtProperties.getExpire(),"utf-8",true);
*/
}
}
注意问题:解决cookie写入问题
- domain:标识访问哪些接口的时候可以携带该cookie 从而保证安全性(否则可能A应用就会访问B应用的数据)
- domain的值:接口的域名或者父域名
- 设置cookie时domain的要求:
- 必须是当前接口的域名或者父域名(如接口为www.test.yzx.com/api,那么domain设置时必须为test.yzx.com或者.yzx.com)
- 必须是origin的域名或者orgin的父域名(如在www.aa.com调用www.bb.com的接口设置cookie 一定不会成功的,或者aa.com:8080调用aa.com:8081设置cookie也不会成功)
- 域名和域名对应的ip 虽然都可以访问到同一个资源 但是对于domain来说是不同的
注意问题:跨域
- 服务端
- 服务的响应头中需要携带Access-Control-Allow-Credentials并且为true,即允许携带cookie。
- 响应头中的Access-Control-Allow-Origin一定不能为*,必须是指定的域名,不然无法携带cookie
- 前端
- 浏览器发起ajax需要指定withCredentials 为true,才可以携带cookie
注意问题:使用nginx代理前端
- 如果前端使用nginx代理 那么后端也要使用nginx代理 不然可能设置不上cookie
- 那么使用nginx代理后端 会自动将请求转发至指定ip 导致host改变
- 解决:proxy_set_header Host $host;
注意问题:后端使用SpringCloud
- 问题一:请求到达我们的网关Zuul,Zuul就会根据路径匹配,根据规则被转发到指定微服务,刀子和host丢失
- 解决维妮塔一:zuul.add-host-header: true
- 问题二:Zuul内部有默认的过滤器,会过滤掉SensitiveHeaders中信息,然后对请求和响应头信息进行重组
- 解决问题二:zuul.sensitive-headers: #把SensitiveHeaders的值设置为空
cookie也是有域的限制,一个网页,只能操作当前域名下的cookie,所以有nginx和zuul网关时要进行设置 保留请求时的host