package com.gl.gl_blog2.controller;
import com.gl.gl_blog2.entity.jwtBean;
import io.jsonwebtoken.*;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.Date;
import java.util.UUID;
@RestController
public class JwtController {
private long time = 10000; //毫秒为单位 1秒=1000毫秒
private String signature = "admin";
@CrossOrigin(origins = "*")
@PostMapping("/generalToken")
public String generalToken(@RequestBody jwtBean jwtBean){
System.out.println(jwtBean);
JwtBuilder jwtBuilder = Jwts.builder();
String jwtToken = jwtBuilder
.setHeaderParam("typ","JWT")
.setHeaderParam("alg","HS256")
.claim("username",jwtBean.getUsername())
.claim("nickname",jwtBean.getNickname())
.claim("quanxian","Teacher")
.setSubject("admin-test")
.setExpiration(new Date(System.currentTimeMillis()+time))
.setId(UUID.randomUUID().toString())
//signature
.signWith(SignatureAlgorithm.HS256,signature)
.compact();
System.out.println(jwtToken);
return jwtToken;
}
@CrossOrigin(origins = "*")
@PostMapping("/jwtCheck")
private String jwtCheck(@RequestBody String token){
JwtParser jwtParser = Jwts.parser();
Jws<Claims> claimsJws = jwtParser.setSigningKey(signature).parseClaimsJws(token);
Claims clamins = claimsJws.getBody();
System.out.println(clamins);
System.out.println("用户名:"+clamins.get("username"));
System.out.println("昵称:"+clamins.get("nickname"));
System.out.println("权限:"+clamins.get("quanxian"));
System.out.println("token-ID:"+clamins.getId());
System.out.println(clamins.getSubject());
System.out.println("生成时间:"+clamins.getExpiration());
return clamins.toString();
}
}
相关依赖:
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.1</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>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
当前只是使用postman测试jwt的生成、解码、获取其中信息
若前端要使用:
进入页面时触发mounted 发送jwt进行校验 校验通过就获得用户数据
jwt通过localstrange永久存储在浏览器。因为jwt中有时间戳会自动过期,所以不用担心
前端进行api连接时可以在headers头部信息中加入存储在浏览器的token,校验通过就允许操作
后端获得token后去redis中查询,如果有相同token,就返回确认信息。后端获得redis的确认信息后,对token进行解码,再以json格式返回前端。至此前端通过jwt校验,并获得该token的用户信息数据。