SpringBoot 整合JWT
2021-03-05 08:27
标签:build 进入 handler type obj void 配置 control 算法 1、依赖 2、JWT工具类生成 3、JWT拦截器 5、mvc配置 6、controller登录测试 7、postman测试下即可,我这边token是在请求头里面! SpringBoot 整合JWT 标签:build 进入 handler type obj void 配置 control 算法 原文地址:https://www.cnblogs.com/JunHello/p/14328197.html
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 {
public static final String SING="asdasdadada";
//生成token
public static String getToken(Map
import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.example.vuetest01.library.entity.Userregister;
import com.example.vuetest01.library.utils.Consts;
import com.example.vuetest01.library.utils.JWTUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
public class JWTIntercepter implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String token = request.getHeader("token");
JSONObject jsonObject=new JSONObject();
try {
DecodedJWT verify = JWTUtils.verify(token);//验证令牌
return true;//-------直接放行
} catch (SignatureVerificationException e) {
e.printStackTrace();
jsonObject.put(Consts.MSG,"无效签名");
}catch (TokenExpiredException e){
jsonObject.put(Consts.MSG,"tiken过期");
}catch (AlgorithmMismatchException e){
jsonObject.put(Consts.MSG,"token算法不一致");
}catch (Exception e){
jsonObject.put(Consts.MSG,"token无效");
}
jsonObject.put("state",false);//-----设置状态
response.setContentType("application/json;charset=UTF-8");
response.getWriter().println(jsonObject);
return false;
}
}
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 InterceptorConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new JWTIntercepter())
.addPathPatterns("/user/**")
.excludePathPatterns("/**");//所有的用户都放行
}
}
@GetMapping("/login")
@ResponseBody
//@CrossOrigin @RequestBody @Validated
public Object login( Userregister userregister){
// session.setAttribute(Consts.NAME,userregister.getUsername());
System.out.println("进入login...");
JSONObject jsonObject=new JSONObject();
Map
下一篇:希尔排序