Springboot Jwt
安装JWT依赖 1 2 3 4 5 <dependency> <groupId>com.auth0</groupId> <artifactId>java-jwt</artifactId> <version>4.5.0</version> </dependency> 定义Jwt工具类 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 package com.example.demo.utils; import com.auth0.jwt.JWT; import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.exceptions.JWTVerificationException; import com.auth0.jwt.exceptions.SignatureVerificationException; import com.auth0.jwt.exceptions.TokenExpiredException; import com.auth0.jwt.interfaces.DecodedJWT; import com.auth0.jwt.interfaces.JWTVerifier; import org.springframework.stereotype.Component; import java.util.Collections; import java.util.Date; import java.util.Map; @Component public class JwtUtils { private static final String SECRET_KEY = "Pxiv0oevyL8rT3an11QKL208vYlkvAmt"; private static final String ISSUER = "admin_service"; private static final long EXPIRATION_TIME = 3600000; public static String generateToken(Map<String, Object> claims) { // 定义密钥 Algorithm algorithm = Algorithm.HMAC256(SECRET_KEY); // 获取当前时间 Date now = new Date(); // 设置过期时间 Date expiration = new Date(now.getTime() + EXPIRATION_TIME); // 构建JWT并添加所有自定义claim com.auth0.jwt.JWTCreator.Builder tokenBuilder = JWT.create() .withIssuer(ISSUER) .withIssuedAt(now) .withExpiresAt(expiration); // 遍历添加每个自定义claim if (claims != null && !claims.isEmpty()) { for (Map.Entry<String, Object> entry : claims.entrySet()) { String key = entry.getKey(); Object value = entry.getValue(); // 根据值类型选择对应的 withClaim 方法重载 if (value instanceof String) { tokenBuilder.withClaim(key, (String) value); } else if (value instanceof Integer) { tokenBuilder.withClaim(key, (Integer) value); } else if (value instanceof Long) { tokenBuilder.withClaim(key, (Long) value); } else if (value instanceof Boolean) { tokenBuilder.withClaim(key, (Boolean) value); } else if (value instanceof Double) { tokenBuilder.withClaim(key, (Double) value); } else if (value instanceof Float) { tokenBuilder.withClaim(key, Collections.singletonList((Float) value)); } else if (value instanceof Short) { tokenBuilder.withClaim(key, Collections.singletonList((Short) value)); } else if (value instanceof Byte) { tokenBuilder.withClaim(key, Collections.singletonList((Byte) value)); } else if (value instanceof Enum<?>) { tokenBuilder.withClaim(key, (Map<String, ?>) value); } } } return tokenBuilder.sign(algorithm); } public static Object validateToken(String token) { try { Algorithm algorithm = Algorithm.HMAC256(SECRET_KEY); JWTVerifier verifier = JWT.require(algorithm) .withIssuer(ISSUER) .build(); DecodedJWT jwt = verifier.verify(token); return "success"; } catch (SignatureVerificationException e) { return "签名验证失败"; } catch (TokenExpiredException e) { return "Token已过期"; } catch (JWTVerificationException e) { return e.getLocalizedMessage(); } } } 定义JwtInterceptor 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 package com.example.demo.config; import cn.hutool.json.JSONUtil; import com.example.demo.utils.JwtUtils; import org.springframework.web.servlet.HandlerInterceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class JwtInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { String token = request.getHeader("Authorization"); if (token == null || "".equals(token)) { response.setCharacterEncoding("UTF-8"); response.getWriter().write(JSONUtil.toJsonStr("未登录")); return false; } Object result = JwtUtils.validateToken(token); if ("success".equals(result)) { return true; } else { response.setCharacterEncoding("UTF-8"); response.getWriter().write(JSONUtil.toJsonStr(result)); return false; } } } 配置拦截器 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 package com.example.demo.config; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class WebAppConfig implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new JwtInterceptor()) .addPathPatterns("/**") // 拦截所有请求,可根据实际需求调整路径模式 .excludePathPatterns("/login"); // 排除登录接口 } } 使用JWT生成Token 1 2 3 4 5 6 7 Map<String, Object> claims = new HashMap<>(); claims.put("userId", userId); claims.put("username", username); // 其他自定义claim... String token = JwtUtils.generateToken(claims); return JSONUtil.toJsonStr(token); 这样你就完成了Spring Boot项目中JWT的集成和使用。记得根据你的项目实际情况对代码进行适当修改和扩展。 ...