How to make an OAuth2 client call from Spring Cloud Gateway with Spring Security?

How do I properly make a OAuth2 request from the gateway when the incoming request is not authenticated and doesn’t have an access token or the access token wouldn’t work for the downstream request?

I need to make OAuth2 client from the gateway service that’s using Spring Cloud Gateway and Spring Security. Let’s say for /permit-endpoint in the gateway, I need to call another service that’s authenticated with OAuth2 and return that response. The endpoint /permit-endpoint is permitted without authentication for now in the gateway (the gateway should also act as a resource server in the future). Also, even if the incoming request did have the access token it wouldn’t work for the downstream OAuth2 call as those would two different configurations. So, I need to make a call to the token endpoint with correct credentials from the gateway, get the access token, attach it to the request and then call the other service and return back the response. My configuration looks like this:

security:
  oauth2:
    resourceserver:
      jwt:
        issuer-uri: <issuer-uri>
        jwk-set-uri: <jwk-set-uri>
    client:
      registration:
        sample-client:
          client-id: <client-id>
          client-secret: <client-secret>
          authorization-grant-type: client_credentials
          scope: <scope>
      provider:
        sample-client:
          token-uri: <token-uri>
cloud:
  gateway:
    default-filters:
      - DedupeResponseHeader=Access-Control-Allow-Credentials Access-Control-Allow-Origin
      - AddResponseHeader=Access-Control-Allow-Origin, *
    routes:
      - id: getObjects
        uri: https://sample.url.com
        predicates:
          - Path=/getObjects/**
        filters:
          - RewritePath=/getObjects(?<segment>.*), /sample-api/sampleurl/sampleservice${segment}
          - TokenRelay=sample-client

This gives me an error from the downstream service saying * You are not authorized to access this API.* which probably means that the token is not getting added properly to the downstream request. I saw that token relay doesn’t work if there’s no token in the incoming request so I made a filter to make the token call and mutate the request to add the token as an Authorization header. I modified the above configuration as follows:

filters:
  - RewritePath=/getObjects(?<segment>.*), /sample-api/sampleurl/sampleservice${segment}
  - OAuth2GatewayFilter

OAuth2GatewayFilter:

@Component
public class Oauth2GatewayFilter extends AbstractGatewayFilterFactory<Oauth2GatewayFilter.Config> {

    private final ReactiveOAuth2AuthorizedClientManager authorizedClientManager;

    public Oauth2GatewayFilter(ReactiveOAuth2AuthorizedClientManager authorizedClientManager) {
        super(Config.class);
        this.authorizedClientManager = authorizedClientManager;
    }

    @Override
    public GatewayFilter apply(Config config) {
        return (exchange, chain) -> {
            OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId("sample-client")
                .principal("dummy")
                .build();

            return authorizedClientManager.authorize(authorizeRequest)
                .flatMap(client -> {
                    ServerHttpRequest request = exchange.getRequest().mutate()
                        .header("Authorization", "Bearer " + client.getAccessToken().getTokenValue())
                        .build();
                    return chain.filter(exchange.mutate().request(request).build());
                });
        };
    }

    public static class Config {
    }
}

This doesn’t work as well as it just gives me 200 OK with no response. I am getting a null authorizedClient.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật