jwt技术
package com.xiang.util;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.xiang.pojo.User;
import com.xiang.service.UserServiceImpl;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.util.StringUtils;
public class JwtToken {
public static final String SECRET = "JKKLJOoasdlfj";
public static final int calendarField = Calendar.DATE;
public static final int calendarInterval = 10;
public static String createToken(String user_id) throws Exception {
Date iatDate = new Date();
Calendar nowTime = Calendar.getInstance();
nowTime.add(calendarField, calendarInterval);
Date expiresDate = nowTime.getTime();
Map<String, Object> map = new HashMap<>();
map.put("alg", "HS256");
map.put("typ", "JWT");
String token = JWT.create().withHeader(map)
.withClaim("iss", "Service")
.withClaim("aud", "APP").withClaim("user_id", null == user_id ? null : user_id)
.withIssuedAt(iatDate)
.withExpiresAt(expiresDate)
.sign(Algorithm.HMAC256(SECRET));
return token;
}
public static Map<String, Claim> verifyToken(String token) {
DecodedJWT jwt = null;
try {
JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
jwt = verifier.verify(token);
} catch (Exception e) {
e.printStackTrace();
}
return jwt.getClaims();
}
public static String getAppUID(String token) {
Map<String, Claim> claims = verifyToken(token);
Claim user_id_claim = claims.get("user_id");
if (null == user_id_claim || StringUtils.isEmpty(user_id_claim.asString())) {
}
return user_id_claim.asString();
}
public static boolean isUser(String token){
ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
UserServiceImpl userService=context.getBean("UserServiceImpl",UserServiceImpl.class);
System.out.println("===============================>"+token);
if(token==null||token.equals("null")){
return false;
}
String id=JwtToken.getAppUID(token);
Map<String,Object> map=new HashMap<>();
map.put("id",id);
User user= userService.selectUser(map);
if(user==null) {
return false;
}else {
return true;
}
}
}
需要导入依赖包 (maven)
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.15.0</version>
</dependency>