import com.alibaba.druid.util.StringUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import java.util.Date;
import java.util.Map;
public class JwtUtils {
private static final int TOKEN_TIME_OUT = 600;
private static String TOKEN_SECRET = null;
public static String getToken(Map params){
long currentTime = System.currentTimeMillis();
return Jwts.builder()
.signWith(SignatureAlgorithm.HS256, TOKEN_SECRET)
.setExpiration(new Date(currentTime + TOKEN_TIME_OUT * 1000))
.addClaims(params)
.compact();
}
public static Claims getClaims(String token) {
return Jwts.parser()
.setSigningKey(TOKEN_SECRET)
.parseClaimsJws(token).getBody();
}
public static boolean verifyToken(String token) {
if(StringUtils.isEmpty(token)) {
return false;
}
try {
Claims claims = Jwts.parser()
.setSigningKey(TOKEN_SECRET)
.parseClaimsJws(token)
.getBody();
}catch (Exception e) {
return false;
}
return true;
}
}
import com.it.singlelogin.common.UserThrealocal;
import com.it.singlelogin.entity.User;
import io.jsonwebtoken.Claims;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class TokenIterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String token = request.getHeader("sfbi-sso-code");
Claims claims = JwtUtils.getClaims(token );
Integer userId = (Integer) claims.get("id");
String name = (String) claims.get("name");
User user = new User();
user.setId(userId);
user.setName(name);
UserThrealocal.set(user);
return true;
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
UserThrealocal.remove();
}
}
package com.it.singlelogin.common;
import com.it.singlelogin.entity.User;
public class UserThrealocal {
private static ThreadLocal<User> threadLocal = new ThreadLocal<>();
public static void set(User user) {
threadLocal.set(user);
}
public static User get(){
return threadLocal.get();
}
public static Integer getId(){
return threadLocal.get().getId();
}
public static String getMobile() {
return threadLocal.get().getName();
}
public static void remove(){
threadLocal.remove();
}
}