Survive by day and develop by night.
talk for import biz , show your perfect code,full busy,skip hardness,make a better result,wait for change,challenge Survive.
happy for hardess to solve denpendies.
目录
概述
需求:
我们知道token 就是个字符串之类的,所以我们采用如下生成:
1.增加依赖
2. 代码编写
3. 测试
设计思路
实现思路分析
1.增加依赖
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.4.0</version>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-core</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>javax.activation</groupId>
<artifactId>activation</artifactId>
<version>1.1.1</version>
</dependency>
2.代码编写
package entity;
public class UserEntity {
private String name;
private String id;
private String phone;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
public String getToken(UserEntity userEntity ) {
//设置算法为HS256
SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
Date now = new Date(System.currentTimeMillis());
JwtBuilder builder = Jwts.builder()
//设置header
.setHeaderParam("typ", "JWT")
.setHeaderParam("alg", "HS256")
//设置iat
.setIssuedAt(now)
//设置payload的键值对
.claim("name", userEntity.getName())
.claim("id", userEntity.getId())
.claim("phone", userEntity.getPhone())
.setIssuer("AuroraLove")
//签名,需要算法和key
.signWith(signatureAlgorithm, SECRET_KEY);
String jwt = builder.compact();
return jwt;
}
3.测试
@Test
public void genTOken(){
SsoServer ssoServer=new SsoServer();
UserEntity userEntity=new UserEntity();
userEntity.setId("1");
userEntity.setName("2");
userEntity.setPhone("3");
System.out.println( ssoServer.getToken(userEntity));
}
参考资料和推荐阅读
参考资料
官方文档
开源社区
博客文章
书籍推荐
- 暂无
欢迎阅读,各位老铁,如果对你有帮助,点个赞加个关注呗!同时,期望各位大佬的批评指正~