登陆JWT验证 发表于 2020-03-12 JSON Web Token(JWT)是目前最流行的跨域身份验证解决方案 12345<dependency> <groupId>com.auth0</groupId> <artifactId>java-jwt</artifactId> <version>3.5.0</version></dependency> 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647public class JwtUtil { /** * 过期时间为一小时 */ private static final long EXPIRE_TIME = 60 * 60 * 1000; /** * 自定义token私钥 */ private static final String TOKEN_SECRET = "joijsdfjlsjfljfljl5135313135"; /** * 生成签名,60分钟后过期 * * @param username * @param userId * @return */ public static String sign(String username, String userId) { //过期时间 Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME); //私钥及加密算法 Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET); //设置头信息 HashMap<String, Object> header = new HashMap<>(2); header.put("typ", "JWT"); header.put("alg", "HS256"); //附带username和userID生成签名 return JWT.create().withHeader(header).withClaim("loginName", username) .withClaim("userId", userId).withExpiresAt(date).sign(algorithm); } public static DecodedJWT verity(String token) { try { Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET); JWTVerifier verifier = JWT.require(algorithm).build(); DecodedJWT jwt = verifier.verify(token); return jwt; } catch (IllegalArgumentException | JWTVerificationException e) { e.printStackTrace(); return null; } }} 赏个🍗吧 打赏 微信支付 支付宝 本文作者: Keeep 本文链接: http://Keeep.coding.me/blog/登陆JWT验证/ 版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 3.0 许可协议。转载请注明出处!