|
|
@@ -0,0 +1,52 @@
|
|
|
+package com.inspur.smsb.gateway.config;
|
|
|
+
|
|
|
+import lombok.AllArgsConstructor;
|
|
|
+import lombok.extern.slf4j.Slf4j;
|
|
|
+import org.springframework.http.server.reactive.ServerHttpRequest;
|
|
|
+import org.springframework.security.authorization.AuthorizationDecision;
|
|
|
+import org.springframework.security.authorization.ReactiveAuthorizationManager;
|
|
|
+import org.springframework.security.core.Authentication;
|
|
|
+import org.springframework.security.core.GrantedAuthority;
|
|
|
+import org.springframework.security.web.server.authorization.AuthorizationContext;
|
|
|
+import org.springframework.stereotype.Component;
|
|
|
+import org.springframework.util.AntPathMatcher;
|
|
|
+import org.springframework.util.PathMatcher;
|
|
|
+import reactor.core.publisher.Mono;
|
|
|
+
|
|
|
+import java.util.*;
|
|
|
+
|
|
|
+/**
|
|
|
+ * 鉴权管理器
|
|
|
+ */
|
|
|
+@Component
|
|
|
+@AllArgsConstructor
|
|
|
+@Slf4j
|
|
|
+public class AuthorizationManager implements ReactiveAuthorizationManager<AuthorizationContext> {
|
|
|
+ @Override
|
|
|
+ public Mono<AuthorizationDecision> check(Mono<Authentication> mono, AuthorizationContext authorizationContext) {
|
|
|
+ ServerHttpRequest request = authorizationContext.getExchange().getRequest();
|
|
|
+ String path = request.getURI().getPath();
|
|
|
+ PathMatcher pathMatcher = new AntPathMatcher();
|
|
|
+ // todo 资源权限角色关系列表,需要初始化到容器中
|
|
|
+ Map<String, List<String>> resourceRolesMap = new HashMap<>();
|
|
|
+ List<String> authorities = new ArrayList<>();
|
|
|
+ resourceRolesMap.put("/token/**",Collections.singletonList("force"));
|
|
|
+ resourceRolesMap.forEach((resource, roles) -> {
|
|
|
+ if (pathMatcher.match(resource, path)) {
|
|
|
+ authorities.addAll(roles);
|
|
|
+ }
|
|
|
+ });
|
|
|
+ return mono
|
|
|
+ .filter(Authentication::isAuthenticated)
|
|
|
+ .flatMapIterable(Authentication::getAuthorities)
|
|
|
+ .map(GrantedAuthority::getAuthority)
|
|
|
+ .any(roleId -> {
|
|
|
+ log.info("访问路径:{}", path);
|
|
|
+ log.info("用户角色roleId:{}", roleId);
|
|
|
+ log.info("资源需要权限authorities:{}", authorities);
|
|
|
+ return authorities.contains(roleId);
|
|
|
+ })
|
|
|
+ .map(AuthorizationDecision::new)
|
|
|
+ .defaultIfEmpty(new AuthorizationDecision(false));
|
|
|
+ }
|
|
|
+}
|