Selaa lähdekoodia

优化四种模式获取令牌

MrBird 6 vuotta sitten
vanhempi
commit
f76a804c4c
24 muutettua tiedostoa jossa 263 lisäystä ja 50 poistoa
  1. 14 2
      febs-auth/src/main/java/cc/mrbird/febs/auth/configure/FebsSecurityConfigure.java
  2. 11 2
      febs-auth/src/main/java/cc/mrbird/febs/auth/controller/SecurityController.java
  3. 1 1
      febs-auth/src/main/java/cc/mrbird/febs/auth/controller/SocialLoginController.java
  4. 1 3
      febs-auth/src/main/java/cc/mrbird/febs/auth/filter/ValidateCodeFilter.java
  5. 33 0
      febs-auth/src/main/java/cc/mrbird/febs/auth/handler/FebsWebLoginFailureHandler.java
  6. 53 0
      febs-auth/src/main/java/cc/mrbird/febs/auth/handler/FebsWebLoginSuccessHandler.java
  7. 19 4
      febs-auth/src/main/java/cc/mrbird/febs/auth/translator/FebsWebResponseExceptionTranslator.java
  8. 3 0
      febs-auth/src/main/resources/bootstrap.yml
  9. BIN
      febs-auth/src/main/resources/static/resource/favicon.ico
  10. 1 0
      febs-auth/src/main/resources/static/resource/jQuery-2.1.4.min.js
  11. 0 0
      febs-auth/src/main/resources/static/resource/login.min.css
  12. 1 0
      febs-auth/src/main/resources/static/resource/login.min.js
  13. 16 19
      febs-auth/src/main/resources/templates/fail.html
  14. 21 0
      febs-auth/src/main/resources/templates/login.html
  15. 1 0
      febs-auth/src/main/resources/templates/result.html
  16. 2 0
      febs-common/febs-common-core/src/main/java/cc/mrbird/febs/common/core/entity/constant/EndpointConstant.java
  17. 7 1
      febs-common/febs-common-core/src/main/java/cc/mrbird/febs/common/core/entity/constant/RegexpConstant.java
  18. 40 5
      febs-common/febs-common-core/src/main/java/cc/mrbird/febs/common/core/utils/FebsUtil.java
  19. 1 1
      febs-common/febs-common-core/src/main/java/cc/mrbird/febs/common/core/validator/MobileValidator.java
  20. 12 1
      febs-common/febs-common-security-starter/src/main/java/cc/mrbird/febs/common/security/starter/configure/FebsCloudSecurityInteceptorConfigure.java
  21. 1 4
      febs-common/febs-common-security-starter/src/main/java/cc/mrbird/febs/common/security/starter/handler/FebsAccessDeniedHandler.java
  22. 1 2
      febs-common/febs-common-security-starter/src/main/java/cc/mrbird/febs/common/security/starter/handler/FebsAuthExceptionEntryPoint.java
  23. 11 5
      febs-common/febs-common-security-starter/src/main/java/cc/mrbird/febs/common/security/starter/interceptor/FebsServerProtectInterceptor.java
  24. 13 0
      febs-common/febs-common-security-starter/src/main/java/cc/mrbird/febs/common/security/starter/properties/FebsCloudSecurityProperties.java

+ 14 - 2
febs-auth/src/main/java/cc/mrbird/febs/auth/configure/FebsSecurityConfigure.java

@@ -1,5 +1,7 @@
 package cc.mrbird.febs.auth.configure;
 
+import cc.mrbird.febs.auth.handler.FebsWebLoginFailureHandler;
+import cc.mrbird.febs.auth.handler.FebsWebLoginSuccessHandler;
 import cc.mrbird.febs.auth.filter.ValidateCodeFilter;
 import cc.mrbird.febs.common.core.entity.constant.EndpointConstant;
 import lombok.RequiredArgsConstructor;
@@ -27,6 +29,9 @@ public class FebsSecurityConfigure extends WebSecurityConfigurerAdapter {
     private final UserDetailsService userDetailService;
     private final ValidateCodeFilter validateCodeFilter;
     private final PasswordEncoder passwordEncoder;
+    private final FebsWebLoginSuccessHandler successHandler;
+    private final FebsWebLoginFailureHandler failureHandler;
+
 
     @Bean
     @Override
@@ -38,12 +43,19 @@ public class FebsSecurityConfigure extends WebSecurityConfigurerAdapter {
     protected void configure(HttpSecurity http) throws Exception {
         http.addFilterBefore(validateCodeFilter, UsernamePasswordAuthenticationFilter.class)
                 .requestMatchers()
-                .antMatchers(EndpointConstant.OAUTH_ALL)
+                .antMatchers(EndpointConstant.OAUTH_ALL, EndpointConstant.LOGIN)
                 .and()
                 .authorizeRequests()
                 .antMatchers(EndpointConstant.OAUTH_ALL).authenticated()
                 .and()
-                .csrf().disable();
+                .formLogin()
+                .loginPage(EndpointConstant.LOGIN)
+                .loginProcessingUrl(EndpointConstant.LOGIN)
+                .successHandler(successHandler)
+                .failureHandler(failureHandler)
+                .permitAll()
+                .and().csrf().disable()
+                .httpBasic().disable();
     }
 
     @Override

+ 11 - 2
febs-auth/src/main/java/cc/mrbird/febs/auth/controller/SecurityController.java

@@ -4,8 +4,10 @@ import cc.mrbird.febs.auth.manager.UserManager;
 import cc.mrbird.febs.auth.service.ValidateCodeService;
 import cc.mrbird.febs.common.core.exception.ValidateCodeException;
 import lombok.RequiredArgsConstructor;
+import org.springframework.stereotype.Controller;
 import org.springframework.web.bind.annotation.GetMapping;
-import org.springframework.web.bind.annotation.RestController;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.ResponseBody;
 
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
@@ -15,20 +17,27 @@ import java.security.Principal;
 /**
  * @author MrBird
  */
-@RestController
+@Controller
 @RequiredArgsConstructor
 public class SecurityController {
 
     private final ValidateCodeService validateCodeService;
     private final UserManager userManager;
 
+    @ResponseBody
     @GetMapping("user")
     public Principal currentUser(Principal principal) {
         return principal;
     }
 
+    @ResponseBody
     @GetMapping("captcha")
     public void captcha(HttpServletRequest request, HttpServletResponse response) throws IOException, ValidateCodeException {
         validateCodeService.create(request, response);
     }
+
+    @RequestMapping("login")
+    public String login() {
+        return "login";
+    }
 }

+ 1 - 1
febs-auth/src/main/java/cc/mrbird/febs/auth/controller/SocialLoginController.java

@@ -78,7 +78,7 @@ public class SocialLoginController {
         } catch (Exception e) {
             String errorMessage = FebsUtil.containChinese(e.getMessage()) ? e.getMessage() : "第三方登录失败";
             model.addAttribute("error", e.getMessage());
-            return "error";
+            return "fail";
         }
     }
 

+ 1 - 3
febs-auth/src/main/java/cc/mrbird/febs/auth/filter/ValidateCodeFilter.java

@@ -12,7 +12,6 @@ import lombok.extern.slf4j.Slf4j;
 import org.apache.commons.lang3.StringUtils;
 import org.springframework.http.HttpHeaders;
 import org.springframework.http.HttpMethod;
-import org.springframework.http.MediaType;
 import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
 import org.springframework.security.web.util.matcher.RequestMatcher;
 import org.springframework.stereotype.Component;
@@ -50,8 +49,7 @@ public class ValidateCodeFilter extends OncePerRequestFilter {
                 filterChain.doFilter(httpServletRequest, httpServletResponse);
             } catch (Exception e) {
                 FebsResponse febsResponse = new FebsResponse();
-                FebsUtil.makeResponse(httpServletResponse, MediaType.APPLICATION_JSON_VALUE,
-                        HttpServletResponse.SC_INTERNAL_SERVER_ERROR, febsResponse.message(e.getMessage()));
+                FebsUtil.makeFailureResponse(httpServletResponse, febsResponse.message(e.getMessage()));
                 log.error(e.getMessage(), e);
             }
         } else {

+ 33 - 0
febs-auth/src/main/java/cc/mrbird/febs/auth/handler/FebsWebLoginFailureHandler.java

@@ -0,0 +1,33 @@
+package cc.mrbird.febs.auth.handler;
+
+import cc.mrbird.febs.common.core.entity.FebsResponse;
+import cc.mrbird.febs.common.core.utils.FebsUtil;
+import org.springframework.security.authentication.BadCredentialsException;
+import org.springframework.security.authentication.LockedException;
+import org.springframework.security.core.AuthenticationException;
+import org.springframework.security.web.authentication.AuthenticationFailureHandler;
+import org.springframework.stereotype.Component;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+
+/**
+ * @author MrBird
+ */
+@Component
+public class FebsWebLoginFailureHandler implements AuthenticationFailureHandler {
+    @Override
+    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException exception) throws IOException {
+        String message;
+        if (exception instanceof BadCredentialsException) {
+            message = "用户名或密码错误!";
+        } else if (exception instanceof LockedException) {
+            message = "用户已被锁定!";
+        } else {
+            message = "认证失败,请联系网站管理员!";
+        }
+        FebsResponse febsResponse = new FebsResponse().message(message);
+        FebsUtil.makeFailureResponse(httpServletResponse, febsResponse);
+    }
+}

+ 53 - 0
febs-auth/src/main/java/cc/mrbird/febs/auth/handler/FebsWebLoginSuccessHandler.java

@@ -0,0 +1,53 @@
+package cc.mrbird.febs.auth.handler;
+
+import cc.mrbird.febs.common.core.entity.FebsResponse;
+import cc.mrbird.febs.common.core.utils.FebsUtil;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.security.core.Authentication;
+import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
+import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
+import org.springframework.security.web.savedrequest.RequestCache;
+import org.springframework.security.web.savedrequest.SavedRequest;
+import org.springframework.stereotype.Component;
+
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.servlet.http.HttpSession;
+import java.io.IOException;
+
+/**
+ * @author MrBird
+ */
+@Slf4j
+@Component
+public class FebsWebLoginSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
+
+    private final RequestCache requestCache = new HttpSessionRequestCache();
+
+    @Override
+    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException {
+        SavedRequest savedRequest = requestCache.getRequest(request, response);
+        HttpSession session = request.getSession(false);
+        if (session != null) {
+            Object attribute = session.getAttribute("SPRING_SECURITY_SAVED_REQUEST");
+            log.info("跳转到登录页的地址为: {}", attribute);
+        }
+        if (FebsUtil.isAjaxRequest(request)) {
+            FebsResponse data = new FebsResponse();
+            if (savedRequest == null) {
+                FebsUtil.makeFailureResponse(response, data.message("请通过授权码模式跳转到该页面"));
+                return;
+            }
+            data.data(savedRequest.getRedirectUrl());
+            FebsUtil.makeSuccessResponse(response, data);
+        } else {
+            if (savedRequest == null) {
+                super.onAuthenticationSuccess(request, response, authentication);
+                return;
+            }
+            clearAuthenticationAttributes(request);
+            getRedirectStrategy().sendRedirect(request, response, savedRequest.getRedirectUrl());
+        }
+    }
+}

+ 19 - 4
febs-auth/src/main/java/cc/mrbird/febs/auth/translator/FebsWebResponseExceptionTranslator.java

@@ -5,10 +5,7 @@ import lombok.extern.slf4j.Slf4j;
 import org.apache.commons.lang3.StringUtils;
 import org.springframework.http.HttpStatus;
 import org.springframework.http.ResponseEntity;
-import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
-import org.springframework.security.oauth2.common.exceptions.InvalidScopeException;
-import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
-import org.springframework.security.oauth2.common.exceptions.UnsupportedGrantTypeException;
+import org.springframework.security.oauth2.common.exceptions.*;
 import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;
 import org.springframework.stereotype.Component;
 
@@ -41,11 +38,29 @@ public class FebsWebResponseExceptionTranslator implements WebResponseExceptionT
             message = "不是有效的scope值";
             return status.body(response.message(message));
         }
+        if (e instanceof RedirectMismatchException) {
+            message = "redirect_uri值不正确";
+            return status.body(response.message(message));
+        }
+        if (e instanceof BadClientCredentialsException) {
+            message = "client值不合法";
+            return status.body(response.message(message));
+        }
+        if (e instanceof UnsupportedResponseTypeException) {
+            String code = StringUtils.substringBetween(e.getMessage(), "[", "]");
+            message = code + "不是合法的response_type值";
+            return status.body(response.message(message));
+        }
         if (e instanceof InvalidGrantException) {
             if (StringUtils.containsIgnoreCase(e.getMessage(), "Invalid refresh token")) {
                 message = "refresh token无效";
                 return status.body(response.message(message));
             }
+            if (StringUtils.containsIgnoreCase(e.getMessage(), "Invalid authorization code")) {
+                String code = StringUtils.substringAfterLast(e.getMessage(), ": ");
+                message = "授权码" + code + "不合法";
+                return status.body(response.message(message));
+            }
             if (StringUtils.containsIgnoreCase(e.getMessage(), "locked")) {
                 message = "用户已被锁定,请联系管理员";
                 return status.body(response.message(message));

+ 3 - 0
febs-auth/src/main/resources/bootstrap.yml

@@ -10,6 +10,9 @@ spring:
         file-extension: yaml
       discovery:
         server-addr: ${nacos.url}:8001
+  thymeleaf:
+    cache: false
+
 logging:
   level:
     org:

BIN
febs-auth/src/main/resources/static/resource/favicon.ico


Tiedoston diff-näkymää rajattu, sillä se on liian suuri
+ 1 - 0
febs-auth/src/main/resources/static/resource/jQuery-2.1.4.min.js


Tiedoston diff-näkymää rajattu, sillä se on liian suuri
+ 0 - 0
febs-auth/src/main/resources/static/resource/login.min.css


+ 1 - 0
febs-auth/src/main/resources/static/resource/login.min.js

@@ -0,0 +1 @@
+$(function(){var a=$("#username"),b=$("#password");$("#login").on("click",function(c){var d,e;return c.preventDefault(),d=a.val().trim(),e=b.val().trim(),""===d?(alert("用户名不能为空"),void 0):""===e?(alert("密码不能为空"),void 0):($.post(ctx+"login",{username:d,password:e},function(a){window.location.href=a.data}).error(function(a){console.error(a),alert(a.responseJSON.message)}),void 0)})});

+ 16 - 19
febs-auth/src/main/resources/templates/error.html → febs-auth/src/main/resources/templates/fail.html

@@ -1,20 +1,17 @@
-<!DOCTYPE html>
-<html lang="ch">
-<head>
-    <meta charset="UTF-8">
-    <meta content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"
-          name="viewport">
-    <meta content="ie=edge" http-equiv="X-UA-Compatible">
-    <title>第三方登录失败</title>
-</head>
-<style>
-    span {
-        font-size: .9rem;
-        font-weight: bold;
-        color: #42b983;
-    }
-</style>
-<body>
-<span>[[${error}]]</span>
-</body>
+<!DOCTYPE html>
+<html lang="ch"  xmlns:th="http://www.thymeleaf.org">
+<head>
+    <meta charset="UTF-8">
+    <meta content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"
+          name="viewport">
+    <meta content="ie=edge" http-equiv="X-UA-Compatible">
+    <link rel="icon" th:href="@{resource/favicon.ico}" type="image/x-icon"/>
+    <title>第三方登录失败</title>
+</head>
+<style>
+    span{font-size:.9rem;font-weight:bold;color:#42b983}
+</style>
+<body>
+<span>[[${error}]]</span>
+</body>
 </html>

+ 21 - 0
febs-auth/src/main/resources/templates/login.html

@@ -0,0 +1,21 @@
+<!DOCTYPE html>
+<html lang="ch" xmlns:th="http://www.thymeleaf.org">
+<head>
+    <meta charset="UTF-8">
+    <meta content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"
+          name="viewport">
+    <meta name="description" content="FEBS Cloud授权码模式登录页面">
+    <meta name="author" content="MrBird">
+    <link rel="stylesheet" th:href="@{resource/login.min.css}" media="all">
+    <script th:src="@{resource/jQuery-2.1.4.min.js}"></script>
+    <link rel="icon" th:href="@{resource/favicon.ico}" type="image/x-icon"/>
+    <title>FEBS系统登录</title>
+</head>
+<body>
+<div class="wrapper"><div class="container"><h1>FEBS 系统登录</h1><form class="form"><input type="text" placeholder="用户名" id="username"><input type="password" placeholder="密码" id="password"><button type="submit" id="login">登录</button></form></div><ul class="bg-bubbles"><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li><li></li></ul></div>
+</body>
+<script th:inline="javascript">
+    var ctx = [[@{/}]];
+</script>
+<script th:src="@{resource/login.min.js}"></script>
+</html>

+ 1 - 0
febs-auth/src/main/resources/templates/result.html

@@ -5,6 +5,7 @@
     <meta content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"
           name="viewport">
     <meta content="ie=edge" http-equiv="X-UA-Compatible">
+    <link rel="icon" th:href="@{resource/favicon.ico}" type="image/x-icon"/>
     <title>登录跳转中</title>
 </head>
 <body>

+ 2 - 0
febs-common/febs-common-core/src/main/java/cc/mrbird/febs/common/core/entity/constant/EndpointConstant.java

@@ -24,4 +24,6 @@ public interface EndpointConstant {
     String OAUTH_ERROR = "/oauth/error";
 
     String ACTUATOR_ALL = "/actuator/**";
+
+    String LOGIN = "/login";
 }

+ 7 - 1
febs-common/febs-common-core/src/main/java/cc/mrbird/febs/common/core/entity/constant/RegexpConstant.java

@@ -1,5 +1,7 @@
 package cc.mrbird.febs.common.core.entity.constant;
 
+import java.util.regex.Pattern;
+
 /**
  * 正则常量
  *
@@ -10,6 +12,10 @@ public interface RegexpConstant {
     /**
      * 简单手机号正则(这里只是简单校验是否为 11位,实际规则更复杂)
      */
-    String MOBILE_REG = "[1]\\d{10}";
+    String MOBILE = "[1]\\d{10}";
+    /**
+     * 中文正则
+     */
+    Pattern CHINESE = Pattern.compile("[\u4e00-\u9fa5]");
 
 }

+ 40 - 5
febs-common/febs-common-core/src/main/java/cc/mrbird/febs/common/core/utils/FebsUtil.java

@@ -3,6 +3,7 @@ package cc.mrbird.febs.common.core.utils;
 import cc.mrbird.febs.common.core.entity.CurrentUser;
 import cc.mrbird.febs.common.core.entity.FebsAuthUser;
 import cc.mrbird.febs.common.core.entity.constant.PageConstant;
+import cc.mrbird.febs.common.core.entity.constant.RegexpConstant;
 import com.alibaba.fastjson.JSONObject;
 import com.baomidou.mybatisplus.core.metadata.IPage;
 import com.fasterxml.jackson.databind.ObjectMapper;
@@ -12,6 +13,7 @@ import org.springframework.core.env.Environment;
 import org.springframework.core.io.buffer.DataBuffer;
 import org.springframework.http.HttpHeaders;
 import org.springframework.http.HttpStatus;
+import org.springframework.http.MediaType;
 import org.springframework.http.server.reactive.ServerHttpRequest;
 import org.springframework.http.server.reactive.ServerHttpResponse;
 import org.springframework.security.core.Authentication;
@@ -40,7 +42,6 @@ import java.util.stream.IntStream;
 @Slf4j
 public class FebsUtil {
 
-    private static final Pattern CHINESE_PATTERN = Pattern.compile("[\u4e00-\u9fa5]");
     private static final String UNKNOW = "unknown";
 
     /**
@@ -91,7 +92,7 @@ public class FebsUtil {
      */
     public static boolean isAjaxRequest(HttpServletRequest request) {
         return (request.getHeader("X-Requested-With") != null
-                && "XMLHttpRequest".equals(request.getHeader("X-Requested-With")));
+                && "XMLHttpRequest" .equals(request.getHeader("X-Requested-With")));
     }
 
     /**
@@ -123,6 +124,40 @@ public class FebsUtil {
         response.getOutputStream().write(JSONObject.toJSONString(value).getBytes());
     }
 
+    /**
+     * 设置成功响应
+     *
+     * @param response HttpServletResponse
+     * @param value    响应内容
+     * @throws IOException IOException
+     */
+    public static void makeSuccessResponse(HttpServletResponse response, Object value) throws IOException {
+        makeResponse(response, MediaType.APPLICATION_JSON_VALUE, HttpServletResponse.SC_OK, value);
+    }
+
+    /**
+     * 设置失败响应
+     *
+     * @param response HttpServletResponse
+     * @param value    响应内容
+     * @throws IOException IOException
+     */
+    public static void makeFailureResponse(HttpServletResponse response, Object value) throws IOException {
+        makeResponse(response, MediaType.APPLICATION_JSON_VALUE, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, value);
+    }
+
+    /**
+     * 设置JSON类型响应
+     *
+     * @param response HttpServletResponse
+     * @param status   http状态码
+     * @param value    响应内容
+     * @throws IOException IOException
+     */
+    public static void makeJsonResponse(HttpServletResponse response, int status, Object value) throws IOException {
+        makeResponse(response, MediaType.APPLICATION_JSON_VALUE, status, value);
+    }
+
     /**
      * 设置webflux模型响应
      *
@@ -179,7 +214,7 @@ public class FebsUtil {
         if (ip == null || ip.length() == 0 || UNKNOW.equalsIgnoreCase(ip)) {
             ip = request.getRemoteAddr();
         }
-        return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip;
+        return "0:0:0:0:0:0:0:1" .equals(ip) ? "127.0.0.1" : ip;
     }
 
     /**
@@ -214,7 +249,7 @@ public class FebsUtil {
         if (ip == null || ip.length() == 0 || UNKNOW.equalsIgnoreCase(ip)) {
             ip = Objects.requireNonNull(request.getRemoteAddress()).getAddress().getHostAddress();
         }
-        return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip;
+        return "0:0:0:0:0:0:0:1" .equals(ip) ? "127.0.0.1" : ip;
     }
 
     /**
@@ -227,7 +262,7 @@ public class FebsUtil {
         if (StringUtils.isBlank(value)) {
             return Boolean.FALSE;
         }
-        Matcher matcher = CHINESE_PATTERN.matcher(value);
+        Matcher matcher = RegexpConstant.CHINESE.matcher(value);
         return matcher.find();
     }
 

+ 1 - 1
febs-common/febs-common-core/src/main/java/cc/mrbird/febs/common/core/validator/MobileValidator.java

@@ -25,7 +25,7 @@ public class MobileValidator implements ConstraintValidator<IsMobile, String> {
             if (StringUtils.isBlank(s)) {
                 return true;
             } else {
-                String regex = RegexpConstant.MOBILE_REG;
+                String regex = RegexpConstant.MOBILE;
                 return FebsUtil.match(regex, s);
             }
         } catch (Exception e) {

+ 12 - 1
febs-common/febs-common-security-starter/src/main/java/cc/mrbird/febs/common/security/starter/configure/FebsCloudSecurityInteceptorConfigure.java

@@ -1,6 +1,8 @@
 package cc.mrbird.febs.common.security.starter.configure;
 
 import cc.mrbird.febs.common.security.starter.interceptor.FebsServerProtectInterceptor;
+import cc.mrbird.febs.common.security.starter.properties.FebsCloudSecurityProperties;
+import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.context.annotation.Bean;
 import org.springframework.web.servlet.HandlerInterceptor;
 import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
@@ -11,9 +13,18 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
  */
 public class FebsCloudSecurityInteceptorConfigure implements WebMvcConfigurer {
 
+    private FebsCloudSecurityProperties properties;
+
+    @Autowired
+    public void setProperties(FebsCloudSecurityProperties properties) {
+        this.properties = properties;
+    }
+
     @Bean
     public HandlerInterceptor febsServerProtectInterceptor() {
-        return new FebsServerProtectInterceptor();
+        FebsServerProtectInterceptor febsServerProtectInterceptor = new FebsServerProtectInterceptor();
+        febsServerProtectInterceptor.setProperties(properties);
+        return febsServerProtectInterceptor;
     }
 
     @Override

+ 1 - 4
febs-common/febs-common-security-starter/src/main/java/cc/mrbird/febs/common/security/starter/handler/FebsAccessDeniedHandler.java

@@ -2,7 +2,6 @@ package cc.mrbird.febs.common.security.starter.handler;
 
 import cc.mrbird.febs.common.core.entity.FebsResponse;
 import cc.mrbird.febs.common.core.utils.FebsUtil;
-import org.springframework.http.MediaType;
 import org.springframework.security.access.AccessDeniedException;
 import org.springframework.security.web.access.AccessDeniedHandler;
 
@@ -18,8 +17,6 @@ public class FebsAccessDeniedHandler implements AccessDeniedHandler {
     @Override
     public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException {
         FebsResponse febsResponse = new FebsResponse();
-        FebsUtil.makeResponse(
-                response, MediaType.APPLICATION_JSON_VALUE,
-                HttpServletResponse.SC_FORBIDDEN, febsResponse.message("没有权限访问该资源"));
+        FebsUtil.makeJsonResponse(response, HttpServletResponse.SC_FORBIDDEN, febsResponse.message("没有权限访问该资源"));
     }
 }

+ 1 - 2
febs-common/febs-common-security-starter/src/main/java/cc/mrbird/febs/common/security/starter/handler/FebsAuthExceptionEntryPoint.java

@@ -3,7 +3,6 @@ package cc.mrbird.febs.common.security.starter.handler;
 import cc.mrbird.febs.common.core.entity.FebsResponse;
 import cc.mrbird.febs.common.core.utils.FebsUtil;
 import lombok.extern.slf4j.Slf4j;
-import org.springframework.http.MediaType;
 import org.springframework.security.core.AuthenticationException;
 import org.springframework.security.web.AuthenticationEntryPoint;
 
@@ -24,6 +23,6 @@ public class FebsAuthExceptionEntryPoint implements AuthenticationEntryPoint {
         int status = HttpServletResponse.SC_UNAUTHORIZED;
         String message = "访问令牌不合法";
         log.error("客户端访问{}请求失败: {}", requestUri, message, authException);
-        FebsUtil.makeResponse(response, MediaType.APPLICATION_JSON_VALUE, status, new FebsResponse().message(message));
+        FebsUtil.makeJsonResponse(response, status, new FebsResponse().message(message));
     }
 }

+ 11 - 5
febs-common/febs-common-security-starter/src/main/java/cc/mrbird/febs/common/security/starter/interceptor/FebsServerProtectInterceptor.java

@@ -3,8 +3,8 @@ package cc.mrbird.febs.common.security.starter.interceptor;
 import cc.mrbird.febs.common.core.entity.FebsResponse;
 import cc.mrbird.febs.common.core.entity.constant.FebsConstant;
 import cc.mrbird.febs.common.core.utils.FebsUtil;
+import cc.mrbird.febs.common.security.starter.properties.FebsCloudSecurityProperties;
 import org.apache.commons.lang3.StringUtils;
-import org.springframework.http.MediaType;
 import org.springframework.util.Base64Utils;
 import org.springframework.web.servlet.HandlerInterceptor;
 
@@ -17,19 +17,25 @@ import java.io.IOException;
  */
 public class FebsServerProtectInterceptor implements HandlerInterceptor {
 
+    private FebsCloudSecurityProperties properties;
+
     @Override
     public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
-        // 从请求头中获取 Gateway Token
+        if (!properties.getOnlyFetchByGateway()) {
+            return true;
+        }
         String token = request.getHeader(FebsConstant.GATEWAY_TOKEN_HEADER);
         String gatewayToken = new String(Base64Utils.encode(FebsConstant.GATEWAY_TOKEN_VALUE.getBytes()));
-        // 校验 Gateway Token的正确性
         if (StringUtils.equals(gatewayToken, token)) {
             return true;
         } else {
             FebsResponse febsResponse = new FebsResponse();
-            FebsUtil.makeResponse(response, MediaType.APPLICATION_JSON_VALUE,
-                    HttpServletResponse.SC_FORBIDDEN, febsResponse.message("请通过网关获取资源"));
+            FebsUtil.makeJsonResponse(response, HttpServletResponse.SC_FORBIDDEN, febsResponse.message("请通过网关获取资源"));
             return false;
         }
     }
+
+    public void setProperties(FebsCloudSecurityProperties properties) {
+        this.properties = properties;
+    }
 }

+ 13 - 0
febs-common/febs-common-security-starter/src/main/java/cc/mrbird/febs/common/security/starter/properties/FebsCloudSecurityProperties.java

@@ -22,6 +22,10 @@ public class FebsCloudSecurityProperties {
      * 多个值时使用逗号分隔
      */
     private String anonUris;
+    /**
+     * 是否只能通过网关获取资源
+     */
+    private Boolean onlyFetchByGateway = Boolean.TRUE;
 
     public Boolean getEnable() {
         return enable;
@@ -47,12 +51,21 @@ public class FebsCloudSecurityProperties {
         this.anonUris = anonUris;
     }
 
+    public Boolean getOnlyFetchByGateway() {
+        return onlyFetchByGateway;
+    }
+
+    public void setOnlyFetchByGateway(Boolean onlyFetchByGateway) {
+        this.onlyFetchByGateway = onlyFetchByGateway;
+    }
+
     @Override
     public String toString() {
         return "FebsCloudSecurityProperties{" +
                 "enable=" + enable +
                 ", authUri='" + authUri + '\'' +
                 ", anonUris='" + anonUris + '\'' +
+                ", onlyFetchByGateway=" + onlyFetchByGateway +
                 '}';
     }
 }

Kaikkia tiedostoja ei voida näyttää, sillä liian monta tiedostoa muuttui tässä diffissä