说明
使用 jose4j 实现 JWT
添加依赖
<dependency>
<groupId>org.bitbucket.b_c</groupId>
<artifactId>jose4j</artifactId>
<version>0.6.3</version>
</dependency>
JWT实现-jose4j
工具类
ResponseUtil 工具类
JsonResult
登录拦截器(关键)
package com.stdspringboot.interceptor;
import com.stdspringboot.util.JWTUtil;
import com.stdspringboot.util.ResponseUtil;
import com.stdspringboot.vo.JsonResult;
import com.stdspringboot.vo.UserInfoJWT;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
public class LoginInter implements HandlerInterceptor {
//方法controller前,先经过该方法
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String auth=request.getHeader("auth");
System.out.println("auth:"+auth);
String method=request.getMethod();
//跨域会发送 OPTIONS 请求,该请求header中没有auth,直接放行
if("OPTIONS".equals(method)){
return true;
}
//发请求时,没携带 JWT,给出提示信息
if(auth==null || "".equals(auth)){
JsonResult jr=JsonResult.fail(JsonResult.CODE_NO_LOGIN,"请先登录!");
ResponseUtil.write(response,jr.toJSON());
return false;
}
try {
//解析
UserInfoJWT uij = JWTUtil.parse(auth, UserInfoJWT.class);//校验 JWT,并解析数据
}catch (Exception e){
e.printStackTrace();
//验证、解析失败,说明携带 JWT 数据不正确,给出提示信息
JsonResult jr=JsonResult.fail(JsonResult.CODE_NO_LOGIN,"请先登录!");
ResponseUtil.write(response,jr.toJSON());
return false;
}
//校验登录通过
return true;
}
}
配置拦截器、跨域
package com.stdspringboot.config;
import com.stdspringboot.interceptor.LoginInter;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import javax.annotation.Resource;
//配置类必须加此注解,否则不生效
@Configuration
public class SpringBootConfig implements WebMvcConfigurer {
@Resource
private LoginInter loginInter;
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(loginInter)
.addPathPatterns("/**") // 拦截所有路径
.excludePathPatterns( //白名单
"/login",
"/reg"
);
}
//跨域
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("GET","HEAD","POST","PUT","DELETE","OPTIONS")
.allowCredentials(true)
.maxAge(3600)
.allowedHeaders("*");
}
}