Przeglądaj źródła

Merge branch 'master' of http://47.101.143.145:8090/77975466/pco

qzyReal 3 lat temu
rodzic
commit
8d8ad245a7

+ 7 - 1
sp-server/pom.xml

@@ -117,7 +117,13 @@
         	<artifactId>spring-boot-configuration-processor</artifactId>
         	<optional>true</optional>
         </dependency>
-        
+        <!--jwt-->
+        <dependency>
+            <groupId>com.auth0</groupId>
+            <artifactId>java-jwt</artifactId>
+            <version>3.3.0</version>
+        </dependency>
+
 	</dependencies>
 
 

+ 2 - 0
sp-server/src/main/java/com/pj/SpServerApplication.java

@@ -2,6 +2,7 @@ package com.pj;
 
 import org.springframework.boot.SpringApplication;
 import org.springframework.boot.autoconfigure.SpringBootApplication;
+import org.springframework.boot.web.servlet.ServletComponentScan;
 import org.springframework.cache.annotation.EnableCaching;
 import org.springframework.scheduling.annotation.EnableScheduling;
 import org.springframework.transaction.annotation.EnableTransactionManagement;
@@ -14,6 +15,7 @@ import org.springframework.transaction.annotation.EnableTransactionManagement;
 @EnableScheduling // 启动定时任务
 @SpringBootApplication // springboot本尊
 @EnableTransactionManagement // 启动注解事务管理
+@ServletComponentScan
 public class SpServerApplication {
 
 	public static void main(String[] args) {

+ 10 - 0
sp-server/src/main/java/com/pj/api/ApiController.java

@@ -1,4 +1,14 @@
 package com.pj.api;
 
+
+import com.pj.utils.sg.AjaxJson;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+@RequestMapping(value = "/api")
+@RestController
+@Slf4j
 public class ApiController {
+
 }

+ 84 - 0
sp-server/src/main/java/com/pj/api/filter/ApiFilter.java

@@ -0,0 +1,84 @@
+package com.pj.api.filter;
+
+import cn.hutool.core.util.StrUtil;
+import com.alibaba.fastjson.JSONObject;
+import com.pj.utils.cache.RedisUtil;
+import com.pj.utils.sg.AjaxJson;
+import lombok.extern.slf4j.Slf4j;
+
+import javax.servlet.*;
+import javax.servlet.annotation.WebFilter;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+@Slf4j
+@WebFilter(filterName = "apiFilter", urlPatterns = "/api/*")
+public class ApiFilter implements Filter {
+
+    private static final List<String> urls = new ArrayList<String>() {{
+        add("/api/login");
+    }};
+
+    @Override
+    public void init(FilterConfig filterConfig) throws ServletException {
+
+    }
+
+    @Override
+    public void doFilter(ServletRequest servletRequest,
+                         ServletResponse servletResponse,
+                         FilterChain filterChain) throws IOException, ServletException {
+        HttpServletRequest request = (HttpServletRequest) servletRequest;
+        HttpServletResponse response = (HttpServletResponse) servletResponse;
+        response.setContentType("application/json;charset=utf-8");
+        response.setHeader("Access-Control-Allow-Origin", "*");
+        String uri = request.getRequestURI();
+        Map<String, String[]> m = new HashMap<>(request.getParameterMap());
+        RequestWrapper wrapper = new RequestWrapper(request, m);
+        if (urls.contains(uri)) {
+            filterChain.doFilter(wrapper, response);
+            return;
+        }
+        String token = request.getHeader("token");
+
+        if (StrUtil.isEmpty(token)) {
+            errorToken(response);
+            return;
+        }
+        Long userId = ApiJwtHelper.getUserId(token);
+        String type = ApiJwtHelper.getUserType(token);
+        String name = ApiJwtHelper.getName(token);
+        if (userId == null || StrUtil.isEmpty(type) || StrUtil.isEmpty(name)) {
+            errorToken(response);
+            return;
+        }
+        String cacheToken = RedisUtil.get("app:token:" + userId);
+        if (!ApiJwtHelper.verify(cacheToken, userId, name, type)) {
+            errorToken(response);
+            return;
+        }
+        wrapper.addParameter("loginId", userId);
+        wrapper.addParameter("loginName", name);
+        wrapper.addParameter("loginType", type);
+        filterChain.doFilter(wrapper, response);
+    }
+
+    private void errorToken(HttpServletResponse response) throws IOException {
+        PrintWriter writer = response.getWriter();
+        AjaxJson json = AjaxJson.getError("无效令牌",401);
+        String errorToken = JSONObject.toJSONString(json);
+        writer.print(errorToken);
+        writer.close();
+    }
+
+    @Override
+    public void destroy() {
+
+    }
+}

+ 88 - 0
sp-server/src/main/java/com/pj/api/filter/ApiJwtHelper.java

@@ -0,0 +1,88 @@
+package com.pj.api.filter;
+
+import com.auth0.jwt.JWT;
+import com.auth0.jwt.JWTVerifier;
+import com.auth0.jwt.algorithms.Algorithm;
+import com.auth0.jwt.exceptions.JWTDecodeException;
+import com.auth0.jwt.interfaces.DecodedJWT;
+
+import java.util.Date;
+import java.util.HashMap;
+import java.util.Map;
+
+public class ApiJwtHelper {
+    static final String SECRET = "level-one-api-Token";
+    static final String ISSUSER = "LEVEL-ONE";
+    static final String SUBJECT = "api token";
+    static final String AUDIENCE = "FJSFDSufdsk43267sdksdfhks";
+
+
+    public static String createUserToken(Long userId, String name, String type) {
+        try {
+            Algorithm algorithm = Algorithm.HMAC256(SECRET);
+            Map<String, Object> map = new HashMap<String, Object>();
+            Date nowDate = new Date();
+            map.put("alg", "HS256");
+            map.put("typ", "JWT");
+            return JWT.create()
+                    // 设置头部信息 Header
+                    .withHeader(map)
+                    // 设置 载荷 Payload
+                    .withClaim("id", userId)
+                    .withClaim("name", name)
+                    .withClaim("type", type)
+                    .withIssuer(ISSUSER)
+                    .withSubject(SUBJECT)
+                    .withAudience(AUDIENCE)
+                    // 生成签名的时间
+                    .withIssuedAt(nowDate)
+                    // 签名 Signature
+                    .sign(algorithm);
+        } catch (Exception exception) {
+            exception.printStackTrace();
+        }
+        return null;
+    }
+
+    public static Long getUserId(String token) {
+        try {
+            DecodedJWT jwt = JWT.decode(token);
+            return jwt.getClaim("id").asLong();
+        } catch (JWTDecodeException e) {
+            return 0L;
+        }
+    }
+
+    public static String getName(String token) {
+        try {
+            DecodedJWT jwt = JWT.decode(token);
+            return jwt.getClaim("name").asString();
+        } catch (JWTDecodeException e) {
+            return null;
+        }
+    }
+
+    public static String getUserType(String token) {
+        try {
+            DecodedJWT jwt = JWT.decode(token);
+            return jwt.getClaim("type").asString();
+        } catch (JWTDecodeException e) {
+            return "";
+        }
+    }
+
+    public static boolean verify(String token, Long userId, String name, String type) {
+        try {
+            Algorithm algorithm = Algorithm.HMAC256(SECRET);
+            JWTVerifier verifier = JWT.require(algorithm)
+                    .withClaim("id", userId)
+                    .withClaim("name", name)
+                    .withClaim("type", type)
+                    .build();
+            verifier.verify(token);
+            return true;
+        } catch (Exception exception) {
+            return false;
+        }
+    }
+}

+ 60 - 0
sp-server/src/main/java/com/pj/api/filter/RequestWrapper.java

@@ -0,0 +1,60 @@
+package com.pj.api.filter;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletRequestWrapper;
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.Map;
+
+public class RequestWrapper extends HttpServletRequestWrapper {
+    private Map<String , String[]> params = new HashMap<>();
+
+    public RequestWrapper(HttpServletRequest request) throws IOException {
+        super(request);
+        this.params.putAll(request.getParameterMap());
+    }
+
+    /**
+     * 重载一个构造方法
+     * @param request
+     * @param extendParams
+     */
+    public RequestWrapper(HttpServletRequest request , Map<String , String[]> extendParams) throws IOException {
+        this(request);
+        addAllParameters(extendParams);
+    }
+
+    @Override
+    public String getParameter(String name) {
+        String[]values = params.get(name);
+        if(values == null || values.length == 0) {
+            return null;
+        }
+        return values[0];
+    }
+
+    @Override
+    public String[] getParameterValues(String name) {
+        return params.get(name);
+    }
+
+    public void addAllParameters(Map<String , String[]>otherParams) {
+        for(Map.Entry<String , String[]>entry : otherParams.entrySet()) {
+            addParameter(entry.getKey() , entry.getValue());
+        }
+    }
+
+
+    public void addParameter(String name , Object value) {
+        if(value != null) {
+            if(value instanceof String[]) {
+                params.put(name , (String[])value);
+            }else if(value instanceof String) {
+                params.put(name , new String[] {(String)value});
+            }else {
+                params.put(name , new String[] {String.valueOf(value)});
+            }
+        }
+    }
+
+}

+ 3 - 1
sp-server/src/main/java/com/pj/utils/sg/AjaxJson.java

@@ -165,7 +165,9 @@ public class AjaxJson extends LinkedHashMap<String, Object> implements Serializa
 	public static AjaxJson getError(String msg) {
 		return new AjaxJson(CODE_ERROR, msg, null, null);
 	}
-	
+    public static AjaxJson getError(String msg,int code) {
+        return new AjaxJson(code, msg, null, null);
+    }
 	/** 返回警告  */
 	public static AjaxJson getWarning() {
 		return new AjaxJson(CODE_ERROR, "warning", null, null);