概述
- 将JWTUtils放入Utils包中
- 代码如下
JWTUtils
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import java.util.Calendar;
import java.util.Map;
public class JWTUtils {
private static final String SING="";//这里写上自己的令牌
/**
* 生成token
* @param map
* @return
*/
public static String getToken(Map<String,String> map){
Calendar instance = Calendar.getInstance();
instance.add(Calendar.DATE,7);//默认7天过期
JWTCreator.Builder builder = JWT.create();
map.forEach((k,v)->{
builder.withClaim(k,v);
});
String token = builder.withExpiresAt(instance.getTime())
.sign(Algorithm.HMAC384(SING));
return token;
}
/**
* 验证token合法性
* @param token
*/
public static void verify(String token){
JWT.require(Algorithm.HMAC384(SING)).build().verify(token);
}
/**
* 返回JWT错误信息
* @param token
* @return
*/
public static DecodedJWT getTokenInfo(String token){
DecodedJWT verify = JWT.require(Algorithm.HMAC384(SING)).build().verify(token);
return verify;
}
}
JWTInterceptor
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import tk.shindebonair.lisan.common.CommonResponse;
import tk.shindebonair.lisan.utils.JWTUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
public class JWTInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
CommonResponse commonResponse;
String token = request.getHeader("token");//请求头中的token
try{
JWTUtils.verify(token);
//commonResponse = CommonResponse.createForSuccess("请求成功",token);
return true;
}catch (Exception e){
commonResponse = CommonResponse.createForError("token无效");
}
String json = new ObjectMapper().writeValueAsString(commonResponse);
response.setContentType("application/json;charset=UTF-8");
response.getWriter().println(json);
return false;
}
}
InterceptorConfig
package tk.shindebonair.lisan.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import tk.shindebonair.lisan.interceptors.JWTInterceptor;
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new JWTInterceptor())
.addPathPatterns("/**")
.excludePathPatterns("/user/**");
}
}
最后
以上就是魔幻纸飞机为你收集整理的Springboot封装JWT工具类,实现拦截器的全部内容,希望文章能够帮你解决Springboot封装JWT工具类,实现拦截器所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复