在pom.xml文件中导入maven依赖
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.6.0</version>
</dependency>
创建token的案例
package com.example.demo.create;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import java.util.Date;
public class CreateJwt {
public static void main(String[] args) {
JwtBuilder jwtBuilder = Jwts.builder()
.setId("6666")
.setSubject("userName")
.setIssuedAt(new Date())
.signWith(SignatureAlgorithm.HS256, "adams")
.setExpiration(new Date(new Date().getTime() + 3600000))
.claim("roles", "yangshiwen");
System.out.println(jwtBuilder.compact());
}
}
解析token的案例
package com.example.demo.parse;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import java.text.SimpleDateFormat;
public class ParseJwt {
public static void main(String[] args) {
Claims claims = Jwts.parser()
.setSigningKey("adams")
.parseClaimsJws("eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiIyNSIsInN1YiI6IuadqOS4luaWhyIsImlhdCI6MTU5NDgxOTgyNiwicm9sZXMiOiLlrabnlJ8m5byA5Y-RIiwiZXhwIjoxNTk0ODIzNDI2fQ._eBhU8pY3IMAN9MZs6ziW0Pc0dzKI9w1UPQko4qpO88")
.getBody();
System.out.println("用户id:" + claims.getId());
System.out.println("用户名:" + claims.getSubject());
System.out.println("登录时间:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(claims.getIssuedAt()));
System.out.println("有效时间:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(claims.getExpiration()));
System.out.println("角色:" + claims.get("roles"));
}
}
权限校验实战案例
token工具类
package com.example.demo.util;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.boot.context.properties.ConfigurationProperties;
import java.util.Date;
@ConfigurationProperties("jwt.config")
public class JwtUtil {
private String key;
private Long tt1;
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public Long getTt1() {
return tt1;
}
public void setTt1(Long tt1) {
this.tt1 = tt1;
}
public String createJWT(String id, String subject, String roles) {
Long nowMillis = System.currentTimeMillis();
Date now = new Date(nowMillis);
System.out.println("当前时间:" + now);
JwtBuilder jwtBuilder = Jwts.builder()
.setId(id)
.setSubject(subject)
.setIssuedAt(now)
.signWith(SignatureAlgorithm.HS256, key)
.claim("roles", roles);
if (tt1 > 0) {
jwtBuilder.setExpiration(new Date(nowMillis + tt1));
}
return jwtBuilder.compact();
}
public Claims parseJWT(String jwtStr) {
return Jwts.parser()
.setSigningKey(key)
.parseClaimsJws(jwtStr)
.getBody();
}
}
yml文件
jwt:
config:
key: adams
tt1: 3600000
server:
port: 8080
servlet:
context-path: /jwt
启动文件放一个token工具类的bean进去
package com.example.demo;
import com.example.demo.util.JwtUtil;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Bean
public JwtUtil jwtUtil() {
return new JwtUtil();
}
}
controller层
package com.example.demo.controller;
import com.example.demo.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
@RestController
@RequestMapping("/admin")
public class AdminController {
@Autowired
private JwtUtil jwtUtil;
@Autowired
private HttpServletRequest request;
@GetMapping("/login")
public Map login(String id, String subject, String roles){
String token = jwtUtil.createJWT(id, subject, roles);
Map<String, Object> map = new HashMap<>();
map.put("token", token);
map.put("roles", roles);
return map;
}
@GetMapping("/isAdmin")
public String isAdmin(){
String header = request.getHeader("Authorization");
if (header == null || "".equals(header)) {
return "权限不足";
}
if (!header.startsWith("Bearer ")) {
return "权限不足";
}
String token = header.substring(7);
try {
Claims claims = jwtUtil.parseJWT(token);
String roles = (String) claims.get("roles");
if (!"admin".equals(roles) || roles == null) {
return "权限不足";
}
} catch (Exception e) {
return "权限不足";
}
return "是管理员";
}
@GetMapping("/isAdminBetter")
public String isAdminBetter(){
String header = request.getHeader("token");
if (header == null || "".equals(header)) {
return "权限不足";
}
String token = header;
try {
Claims claims = jwtUtil.parseJWT(token);
String roles = (String) claims.get("roles");
if (!"admin".equals(roles) || roles == null) {
return "权限不足";
}
} catch (Exception e) {
return "权限不足";
}
return "是管理员";
}
}
请求方式:
第一种:
第二种:
校验成功