# Spring Gateway 集成权限管理

Spring Gateway 集成oauth2在网关层进行资源服务的访问控制,使用的是@EnableWebFluxSecurity注解

# 资源服务器配置

# 不配置访问控制

ResourceServerConfig.java

@AllArgsConstructor
@Configuration
@EnableWebFluxSecurity
public class ResourceServerConfig {
    private final AuthorizationManager authorizationManager;
    private final IgnoreUrlsConfig ignoreUrlsConfig;
    private final RestfulAccessDeniedHandler restfulAccessDeniedHandler;
    private final RestAuthenticationEntryPoint restAuthenticationEntryPoint;
    private final IgnoreUrlsRemoveJwtFilter ignoreUrlsRemoveJwtFilter;

    private final UrlJwtFilter urlJwtFilter;

    @Bean
    public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {

        http.cors().and().csrf().disable();
        // 增加自定义拦截器
        http.addFilterAt(new CorsFilter(), SecurityWebFiltersOrder.SECURITY_CONTEXT_SERVER_WEB_EXCHANGE);
        //自定义处理JWT请求头过期或签名错误的结果
        http.oauth2ResourceServer().authenticationEntryPoint(restAuthenticationEntryPoint);
        http.oauth2ResourceServer().jwt().jwtAuthenticationConverter(jwtAuthenticationConverter());
        //用于解决没办法设置Header的token
        http.addFilterBefore(urlJwtFilter, SecurityWebFiltersOrder.AUTHENTICATION);
        //对白名单路径,直接移除JWT请求头
        http.addFilterBefore(ignoreUrlsRemoveJwtFilter, SecurityWebFiltersOrder.AUTHENTICATION);
        http.authorizeExchange()
                .pathMatchers(ArrayUtil.toArray(ignoreUrlsConfig.getUrls(),String.class)).permitAll()//白名单配置
             .pathMatchers("/**").permitAll(); 放開所有請求,不攔截
        return http.build();
    }

    @Bean
    public Converter<Jwt, ? extends Mono<? extends AbstractAuthenticationToken>> jwtAuthenticationConverter() {
        JwtGrantedAuthoritiesConverter jwtGrantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter();
        jwtGrantedAuthoritiesConverter.setAuthorityPrefix(AuthConstant.AUTHORITY_PREFIX);
        jwtGrantedAuthoritiesConverter.setAuthoritiesClaimName(AuthConstant.AUTHORITY_CLAIM_NAME);
        JwtAuthenticationConverter jwtAuthenticationConverter = new JwtAuthenticationConverter();
        jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(jwtGrantedAuthoritiesConverter);
        return new ReactiveJwtAuthenticationConverterAdapter(jwtAuthenticationConverter);
    }

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42

# 配置访问控制

@Bean
public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {  
http.cors().and().csrf().disable();
    // 增加自定义拦截器
    http.addFilterAt(new CorsFilter(), SecurityWebFiltersOrder.SECURITY_CONTEXT_SERVER_WEB_EXCHANGE);
    //自定义处理JWT请求头过期或签名错误的结果
    http.oauth2ResourceServer().authenticationEntryPoint(restAuthenticationEntryPoint);
    http.oauth2ResourceServer().jwt().jwtAuthenticationConverter(jwtAuthenticationConverter());
    //用于解决没办法设置Header的token
    http.addFilterBefore(urlJwtFilter, SecurityWebFiltersOrder.AUTHENTICATION);
    //对白名单路径,直接移除JWT请求头
    http.addFilterBefore(ignoreUrlsRemoveJwtFilter, SecurityWebFiltersOrder.AUTHENTICATION);
        http.authorizeExchange()
                .pathMatchers(ArrayUtil.toArray(ignoreUrlsConfig.getUrls(),String.class)).permitAll()//白名单配置
                .anyExchange().access(authorizationManager)//鉴权管理器配置
                .and().exceptionHandling()
                .accessDeniedHandler(restfulAccessDeniedHandler)//处理未授权
                .authenticationEntryPoint(restAuthenticationEntryPoint);//处理未认证
    return http.build();
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

# 问题

项目技术架构: 前端:vue 后端:springcloud h版 1、网关:gateway ( 1)作为所有资源的统一访问入口,需要支持跨域 (2)依赖oauth2,使用resource相关api,同时作为资源服务器,进行权限认证

当写好接口后,本机使用postman测试,接口都正常返回,但配合前端测试时,一直出现下面两个问题,而前端使用proxy代理,也仍然无法解决。

# springcloud gateway + oauth2引起的跨域问题
# 问题一
Access to XMLHttpRequest at 'http://ip:port/userInfo' from origin 'http://localhost:8081' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
1

不论是自己写跨域过滤器,还是调整yml的配置,都得不到解决。

1、百度后,有人说要关掉weblfux的跨域,但不知道如何关。 2、后来发现,浏览器在发起options 探测请求时,一直被网关阻止,出现了401错误,怀疑可能是oauth2引起的。结合1中的提法,尝试引入oauth2的跨域配置,引入自定义跨域过滤器,问题得到解决。

解决办法:关掉ResourceServerConfig的跨域配置,并且引入自定义的跨域过滤器

SecurityWebFilterChain配置

 @Bean
    public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
        // 关掉跨域
        http.cors().and().csrf().disable();
      // 增加自定义拦截器
        http.addFilterAt(new CorsFilter(), SecurityWebFiltersOrder.SECURITY_CONTEXT_SERVER_WEB_EXCHANGE);
        http.oauth2ResourceServer().jwt()
                .jwtAuthenticationConverter(jwtAuthenticationConverter());
        // 如果是token过期了,需要加到oauth2ResourceServer上,才会起作用,下面不知道为什么不起作用
        http.oauth2ResourceServer().authenticationEntryPoint(restAuthenticationEntryPoint);
        http.authorizeExchange()
                .pathMatchers(ArrayUtil.toArray(ignoreUrlsConfig.getUrls(), String.class)).permitAll()//白名单配置
                .pathMatchers("/login", "/new/login", "/webjars/**",
                        "/js/**", "/config/**", "/images/**", "/css/**", "/commonlib/**", "/thirdlibs/**",
                        "/favicon.ico", "/loginServer/**", "/randCodeImage/**",
                        "/oauth/**", "*.js", "/**/*.json", "/**/*.css", "/**/*.js", "/portal/**", "/**/*.map", "/**/*.html",
                        "/**/*.png", "uum/region/enum/**").permitAll()
                .anyExchange().access(authorizationManager)//鉴权管理器配置
                .and().exceptionHandling()
                .accessDeniedHandler(restfulAccessDeniedHandler)//处理未授权
                .authenticationEntryPoint(restAuthenticationEntryPoint)//处理未认证
                .and().headers().frameOptions().disable() //允许iframe
        ;

        return http.build();
    }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

CorsFilter定义:

@Configuration
public class CorsFilter implements WebFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange ctx, WebFilterChain chain) {
        ServerHttpRequest request = ctx.getRequest();
        if (CorsUtils.isCorsRequest(request)) {
            ServerHttpResponse response = ctx.getResponse();
            HttpHeaders headers = response.getHeaders();
            headers.set(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "*");
            headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, "*");
            headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "");
            headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "false");
            headers.add(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, "*");
            headers.add(HttpHeaders.ACCESS_CONTROL_MAX_AGE, "3600");
            if (request.getMethod() == HttpMethod.OPTIONS) {
                response.setStatusCode(HttpStatus.OK);
                return Mono.empty();
            }
        }
        return chain.filter(ctx);
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# 问题二
访问XMLHttpRequest at'http://ip:port/randCodeImage?_method=get'来源'http://localhost:8081'已被CORS策略阻止:'Access Control Allow Origin'标头包含多个值“,”,但只允许一个值。
1
spring:
  cloud:
    gateway:
      globalcors:
        corsConfigurations:
          '[/**]':
            # 允许携带认证信息
            allow-credentials: true
            # 允许跨域的源(网站域名/ip),设置*为全部
            allowedOrigins: "*"
            # 允许跨域的method, 默认为GET和OPTIONS,设置*为全部
            allowedMethods: "*"
            # 允许跨域请求里的head字段,设置*为全部
            allowedHeaders: "*"
      default-filters:
      #相同header多个值时的处理方式,三种规则可选(RETAIN_FIRST|RETAIN_UNIQUE|RETAIN_LAST)
        - DedupeResponseHeader=Access-Control-Allow-Origin Access-Control-Allow-Credentials, RETAIN_FIRST
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
DedupeResponseHeader的源码见:org.springframework.cloud.gateway.filter.factory.DedupeResponseHeaderGatewayFilterFactory
1
# 网关报413
  1. Request header fields too large(header超过限制)
  2. Request Entity Too Large(params超过限制)

参考地址:

https://blog.csdn.net/weixin_40502536/article/details/115536751

解决方法:

修改Netty配置文件

新建NettyConfiguration文件

package com.sun.gateway.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.embedded.netty.NettyReactiveWebServerFactory;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.stereotype.Component;

/**
 * @author sungang
 * @date 2021/9/13 7:01 下午
 *
 */

@Component
public class NettyConfiguration implements WebServerFactoryCustomizer<NettyReactiveWebServerFactory> {

    @Value("${server.max-initial-line-length:1000485760}")
    private int maxInitialLingLength;

    @Override
    public void customize(NettyReactiveWebServerFactory container) {
        //處理Params中傳遞數據過大問題(但好像和header不能同時修改,過大的參數推薦用json處理)
        container.addServerCustomizers(
                httpServer -> httpServer.httpRequestDecoder(
                        httpRequestDecoderSpec -> httpRequestDecoderSpec.maxInitialLineLength(maxInitialLingLength)
                )
        );
        //處理Header中 token參數過大問題
        container.addServerCustomizers(
                httpServer -> httpServer.httpRequestDecoder(
                        httpRequestDecoderSpec -> httpRequestDecoderSpec.maxHeaderSize(1000485760)
                )
        );
    }

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36

# 解决问题

# header头传递token过大

权限控制问题,spring gateway +oauth2.0 ,JWT token过大

上次更新时间: 2024年2月14日星期三上午10点24分