添加了拦截器和Token的初步方案

master
张韬 2022-06-28 20:18:45 +08:00
parent 59c56b886f
commit ac10fe63e7
6 changed files with 213 additions and 0 deletions

View File

@ -105,6 +105,11 @@
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.19.2</version>
</dependency>
</dependencies>
<build>

View File

@ -0,0 +1,39 @@
package cn.edu.hfut.rmdjzz.projectmanagement.config;
import cn.edu.hfut.rmdjzz.projectmanagement.interceptor.CorsInterceptor;
import cn.edu.hfut.rmdjzz.projectmanagement.interceptor.TokenInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import javax.annotation.Resource;
/**
* @author
* created at 2022/6/28 19:44
*/
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Resource
private CorsInterceptor corsInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(corsInterceptor).addPathPatterns("/**");
registry.addInterceptor(new TokenInterceptor())
.addPathPatterns("/**")
.excludePathPatterns("/api/login");
}
/*
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOriginPatterns("*")
.allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS")
.allowedHeaders("token")
.allowCredentials(true)
.maxAge(3600)
.allowedHeaders("*");
}
*/
}

View File

@ -0,0 +1,27 @@
package cn.edu.hfut.rmdjzz.projectmanagement.entity;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Data;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
/**
* @author
* created at 2022/6/28 18:32
*/
@Data
public class Response implements Serializable {
private int code;
private String msg;
Map<String,Object> data = new HashMap<>();
public void put(String key,Object value){
data.put(key,value);
}
public String JsonString() throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.writeValueAsString(this);
}
}

View File

@ -0,0 +1,32 @@
package cn.edu.hfut.rmdjzz.projectmanagement.interceptor;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @author
* created at 2022/6/28 18:13
*/
@Component
public class CorsInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "*");
response.setHeader("Access-Control-Allow-Headers", "content-type,token");
response.setHeader("Content-Type", "application/json;charset=utf-8");
response.setHeader("Access-Control-Allow-Credentials","false");
// 如果是OPTIONS则结束请求
if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
response.setStatus(200);
return false;
}
return true;
}
}

View File

@ -0,0 +1,46 @@
package cn.edu.hfut.rmdjzz.projectmanagement.interceptor;
import cn.edu.hfut.rmdjzz.projectmanagement.entity.Response;
import cn.edu.hfut.rmdjzz.projectmanagement.utils.TokenUtils;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @author
* created at 2022/6/28 18:16
*/
@Component
public class TokenInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception {
System.out.println(httpServletRequest.getRequestURL()+" "+httpServletRequest.getMethod());
if (!(object instanceof HandlerMethod)) {
return false;
}
String token = httpServletRequest.getHeader("token");
if (null == token || "".equals(token.trim())) {
Response res=new Response();
res.setMsg("缺少Token");
res.setCode(HttpStatus.UNAUTHORIZED.value());
httpServletResponse.getWriter().print(res.JsonString());
return false;
}
if(token.charAt(0)=='"'||token.charAt(0)=='\'')
token=token.substring(1,token.length()-1);
System.out.println(token);
if(!TokenUtils.checkToken(token)){
Response res=new Response();
res.setMsg("无效的Token");
res.setCode(HttpStatus.UNAUTHORIZED.value());
httpServletResponse.getWriter().print(res.JsonString());
return false;
}
httpServletRequest.setAttribute("token", TokenUtils.autoRequire(token));
return true;
}
}

View File

@ -0,0 +1,64 @@
package cn.edu.hfut.rmdjzz.projectmanagement.utils;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import java.util.Date;
/**
* @author
* created at 2022/6/28 18:20
*/
public final class TokenUtils {
public final static String pvKey="SignedByRMDJZZ";
public static String getToken(String username){
return JWT.create()
.withClaim("username", username)
.withIssuedAt(new Date())
.withExpiresAt(new Date(System.currentTimeMillis() + 5*60*60*1000))
.sign(Algorithm.HMAC256(pvKey));
}
public static boolean checkToken(String token) {
JWTVerifier verifier = JWT.require(Algorithm.HMAC256(pvKey)).build();
try {
verifier.verify(token);
return true;
} catch (JWTVerificationException e) {
e.printStackTrace();
return false;
}
}
public static boolean checkTimeOut(String token){
if(!checkToken(token))
return true;
return JWT.decode(token).getClaim("exp").asLong()<(System.currentTimeMillis()/1000);
}
public static String getUsername(String token){
if(!checkToken(token))
return "";
return JWT.decode(token).getClaim("username").asString();
}
public static String refreshToken(String token) {
return getToken(getUsername(token));
}
public static String autoRequire(String token) {
boolean check = checkToken(token);
if (check) {
DecodedJWT jwt = JWT.decode(token);
long current = System.currentTimeMillis() / 1000;
Long start = jwt.getClaim("iat").asLong();
Long end = jwt.getClaim("exp").asLong();
if ((current - start) * 1.0 / (end - start) > 0.8) {
return refreshToken(token);
} else {
return token;
}
} else {
return "";
}
}
}