一.什么是jwt
JWT(JSON Web Token)是一种用于身份验证和授权的开放标准。它是由JSON格式组成的安全令牌,可以被简单方便地传递给不同的应用程序和服务,能够对数据进行加密和验证,从而实现无状态的分布式Web应用程序的安全访问。JWT由三部分组成,分别是头部、载荷和签名。其中,头部存储加密算法的类型、载荷保存相关的信息(如过期时间、权限等),签名用于验证令牌的有效性。通过使用JWT,接口之间无需共享用户信息或会话状态,从而提高了系统的可靠性,在微服务和云计算等场景下具有广泛的应用。
二.代码结构图
三.依赖包导入
<!-- gst-->
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.18.2</version>
</dependency>
<!-- -->
四.代码部分
TokenService代码
package com.example.jwtlogin1.service;
import java.util.Map;
public interface TokenService {
//获取token字符串 Mao封装加密信息 比如用户名或者用户账号
public String getToken(Map<Object,Object> map);
//验证toekn map封装解析的信息 比如用户名 或者用户账号
public Map<Object,Object> tokenAnalyze(String token);
}
UserTokenServiceImpl代码
package com.example.jwtlogin1.serviceImpl;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.example.jwtlogin1.service.TokenService;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
@Slf4j
@Service
public class UserTokenServiceImpl implements TokenService {
//设置加密字符串 生成token与验证token需要使用同一个字符串
private static final String SING="!@#$%ADJSAD@#hasdasldjlkkas^HYGJ";
//根据加密字符串与加密类型进行加密 生成token与验证token需要使用同一个
private static Algorithm ENCRYPTION_TYPE= Algorithm.HMAC256(SING);
//设置过期时间 单位秒
private static int DEAT_LINE=120;
@Override
public String getToken(Map<Object, Object> map) {
Calendar instance=Calendar.getInstance();
instance.add(Calendar.SECOND,DEAT_LINE);
// instance.add(Calendar.DATE,7); //七天时间过期
JWTCreator.Builder builder= JWT.create(); //创建jwt builder
map.forEach((k,v)->{ //payload
builder.withClaim(String.valueOf(k),String.valueOf(v));
System.out.println("key:"+String.valueOf(k)+" value:"+String.valueOf(v));
});
String token=builder.withExpiresAt(instance.getTime())//指定令牌过期时间
.sign(ENCRYPTION_TYPE);//sign
return token;
}
@Override
public Map<Object, Object> tokenAnalyze(String token) { //验证通过 返回验证信息 及用户信息
System.out.println("token:"+token);
Map<Object,Object> map=new HashMap<>();
JWTVerifier jwtVerifier=JWT.require(ENCRYPTION_TYPE).build(); //创建验证对象
DecodedJWT verify;
try { //如果验证失败 则会抛出异常
verify=jwtVerifier.verify(token);
map.put("username",verify.getClaim("username").asString());
map.put("过期时间",verify.getExpiresAt());
map.put("验证信息","已经通过");
}catch (Exception e)
{
map.put("验证信息","已过期");
return map;
}
return map;
}
}
五.测试代码
package com.example.jwtlogin1;
import com.example.jwtlogin1.serviceImpl.UserTokenServiceImpl;
import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class Jwtlogin1ApplicationTests {
@Autowired
private UserTokenServiceImpl userTokenService;
@Test
void contextLoads() {
Map<Object, Object> map=new HashMap<>();
map.put("username","超维编程");
String token=userTokenService.getToken(map);
Map<Object,Object> map1=userTokenService.tokenAnalyze(token);
System.out.println("解析token为"+map1);
}
}
六.总结
需要注意token生成的时候最好选择用字典封装加密属性数值。