From: 刘洪青 Date: Thu, 10 Oct 2019 14:05:10 +0000 (+0800) Subject: refactor: 优化GlobalFilter 代码逻辑 X-Git-Tag: v0.0.1^2~2 X-Git-Url: https://source.supwisdom.com/gerrit/gitweb?a=commitdiff_plain;h=efb62d5cdbcd3c4ea8e99174d10096b295be8e55;p=institute%2Fsw-backend.git refactor: 优化GlobalFilter 代码逻辑 --- diff --git a/gateway/src/main/java/com/supwisdom/institute/backend/gateway/filter/AccessControlGlobalFilter.java b/gateway/src/main/java/com/supwisdom/institute/backend/gateway/filter/AccessControlGlobalFilter.java index 6ef6b7e..7784615 100644 --- a/gateway/src/main/java/com/supwisdom/institute/backend/gateway/filter/AccessControlGlobalFilter.java +++ b/gateway/src/main/java/com/supwisdom/institute/backend/gateway/filter/AccessControlGlobalFilter.java @@ -6,6 +6,7 @@ import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import lombok.AllArgsConstructor; @@ -22,7 +23,6 @@ import org.springframework.http.server.reactive.ServerHttpRequest; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.security.access.ConfigAttribute; import org.springframework.security.access.SecurityConfig; -import org.springframework.security.core.Authentication; import org.springframework.security.core.context.ReactiveSecurityContextHolder; import org.springframework.security.core.context.SecurityContext; import org.springframework.util.AntPathMatcher; @@ -56,6 +56,7 @@ public class AccessControlGlobalFilter implements GlobalFilter, Ordered { // 判断 该资源 是否需要登录才能访问 if (configAttributes == null || configAttributes.size() <= 0) { + return chain.filter(exchange); // FIXME: } @@ -64,17 +65,30 @@ public class AccessControlGlobalFilter implements GlobalFilter, Ordered { // FIXME: 判断 登录用户 是否可以访问 该资源 return ReactiveSecurityContextHolder.getContext() - .filter(c -> { - return c.getAuthentication() != null && c.getAuthentication().isAuthenticated() && c.getAuthentication().getPrincipal() instanceof InfrasUser; + .filter(sc -> { + return sc.getAuthentication() != null && sc.getAuthentication().isAuthenticated(); }) - .map(SecurityContext::getAuthentication) - .map(Authentication::getPrincipal) - .cast(InfrasUser.class) - .map(infrasUser -> { - log.debug("infrasUser's roles is {}", infrasUser.getRoles()); + .flatMap(sc -> Mono.just(Optional.of(sc))) + .defaultIfEmpty(Optional.empty()) + .flatMap(scOptional -> { + List roles = null; - boolean hasPermission = false; + if (scOptional.isPresent()) { + SecurityContext sc = scOptional.get(); + if (sc.getAuthentication().getPrincipal() instanceof InfrasUser) { + InfrasUser infrasUser = (InfrasUser) sc.getAuthentication().getPrincipal(); + log.debug("infrasUser's roles is {}", infrasUser.getRoles()); + + roles = infrasUser.getRoles(); + } else { + roles = new ArrayList(); + } + } else { + roles = new ArrayList(); + } + boolean hasPermission = false; + ConfigAttribute ca; String needRole; for (Iterator iter = configAttributes.iterator(); iter.hasNext();) { @@ -101,7 +115,7 @@ public class AccessControlGlobalFilter implements GlobalFilter, Ordered { break; } - hasPermission = infrasUser.getRoles().contains(ca.getAttribute()); + hasPermission = roles.contains(ca.getAttribute()); if (hasPermission) { log.debug("match attribute is {}", ca.getAttribute()); break; @@ -112,7 +126,7 @@ public class AccessControlGlobalFilter implements GlobalFilter, Ordered { throw new RuntimeException("no right"); } - return exchange; + return Mono.just(exchange); }) .flatMap(ex -> chain.filter(ex)); } @@ -137,10 +151,10 @@ public class AccessControlGlobalFilter implements GlobalFilter, Ordered { private void loadRequestMap() { if (requestMap.isEmpty()) { -// AntPathRequestMatcher requestMatcher0 = new AntPathRequestMatcher("/api/**"); -// Collection attributes0 = new ArrayList(); -// attributes0.add(new SecurityConfig("user")); -// requestMap.put(requestMatcher0, attributes0); + AntPathRequestMatcher requestMatcher0 = new AntPathRequestMatcher("/api/*/v*/open/**"); + Collection attributes0 = new ArrayList(); + attributes0.add(new SecurityConfig("ACCESS_"+ResourceRoleSet.ACCESS_PERMIT_ALL)); + requestMap.put(requestMatcher0, attributes0); // 从 后端接口 加载 List resourceRoleSets = authnService.resourceRoleSets(); diff --git a/gateway/src/main/java/com/supwisdom/institute/backend/gateway/filter/SimpleUserTransmitGlobalFilter.java b/gateway/src/main/java/com/supwisdom/institute/backend/gateway/filter/SimpleUserTransmitGlobalFilter.java index 7c3af6f..0a8b606 100644 --- a/gateway/src/main/java/com/supwisdom/institute/backend/gateway/filter/SimpleUserTransmitGlobalFilter.java +++ b/gateway/src/main/java/com/supwisdom/institute/backend/gateway/filter/SimpleUserTransmitGlobalFilter.java @@ -1,5 +1,7 @@ package com.supwisdom.institute.backend.gateway.filter; +import java.util.Optional; + import lombok.extern.slf4j.Slf4j; import org.apache.commons.codec.binary.Base64; @@ -29,34 +31,46 @@ public class SimpleUserTransmitGlobalFilter implements GlobalFilter, Ordered { @Override public Mono filter(ServerWebExchange exchange, GatewayFilterChain chain) { + log.debug("SimpleUserTransmitGlobalFilter.filter"); return ReactiveSecurityContextHolder.getContext() .filter(c -> { return c.getAuthentication() != null && c.getAuthentication().isAuthenticated() && c.getAuthentication().getPrincipal() instanceof InfrasUser; }) - .map(SecurityContext::getAuthentication) - .map(Authentication::getPrincipal) - .cast(InfrasUser.class) - .map(infrasUser -> { - try { - User user = new User(infrasUser.getUsername(), infrasUser.getRoles(), infrasUser.getAttributes()); - - String jsonUser = JSONObject.toJSONString(user); - log.debug(jsonUser); - - //String headerValue = new String(URLDecoder.decode(jsonUser,"UTF-8")); - String headerValue = Base64.encodeBase64URLSafeString(jsonUser.getBytes("UTF-8")); - log.debug(headerValue); + .flatMap(sc -> Mono.just(Optional.of(sc))) + .defaultIfEmpty(Optional.empty()) + .flatMap(scOptional -> { + if (scOptional.isPresent()) { + SecurityContext sc = scOptional.get(); - ServerHttpRequest request = exchange.getRequest().mutate() - .header(UserContext.KEY_USER_IN_HTTP_HEADER, headerValue) - .build(); - log.debug("User set to gateway header: ok"); - return exchange.mutate().request(request).build(); - } catch (Exception e) { - log.warn("User set to gateway header: error", e); + return Mono.just(sc) + .map(SecurityContext::getAuthentication) + .map(Authentication::getPrincipal) + .cast(InfrasUser.class) + .map(infrasUser -> { + try { + User user = new User(infrasUser.getUsername(), infrasUser.getRoles(), infrasUser.getAttributes()); + + String jsonUser = JSONObject.toJSONString(user); + log.debug(jsonUser); + + //String headerValue = new String(URLDecoder.decode(jsonUser,"UTF-8")); + String headerValue = Base64.encodeBase64URLSafeString(jsonUser.getBytes("UTF-8")); + log.debug(headerValue); + + ServerHttpRequest request = exchange.getRequest().mutate() + .header(UserContext.KEY_USER_IN_HTTP_HEADER, headerValue) + .build(); + log.debug("User set to gateway header: ok"); + return exchange.mutate().request(request).build(); + } catch (Exception e) { + log.warn("User set to gateway header: error", e); + } + return exchange; + }); } - return exchange; + + return Mono.just(exchange); }) .flatMap(ex -> chain.filter(ex)) ;