Pub/Sub: Publishing messages to a specific region

I want to publish messages to a specific region as I want to leverage message ordering.

I am using the following dependencies:

<dependency>
 <groupId>com.google.cloud</groupId>
 <artifactId>spring-cloud-gcp-starter</artifactId>
</dependency>
<dependency>
 <groupId>com.google.cloud</groupId>
 <artifactId>spring-cloud-gcp-starter-pubsub</artifactId>
</dependency>

<dependencyManagement>
 <dependencies>
  <dependency>
   <groupId>com.google.cloud</groupId>
   <artifactId>spring-cloud-gcp-dependencies</artifactId>
   <version>3.5.0</version>
   <type>pom</type>
   <scope>import</scope>
  </dependency>
 </dependencies>
</dependencyManagement>

I am using the following property to set the regional endpoint:

spring.cloud.gcp.pubsub.publisher.endpoint=asia-east1-pubsub.googleapis.com:443

However, while publishing the messages using PubSubTemplate, I get the below error.

com.google.api.gax.rpc.UnauthenticatedException: io.grpc.StatusRuntimeException: UNAUTHENTICATED: Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential.

Whereas, on not using the regional endpoint (and using the global one) I am able to publish the messages successfully.

What am I doing wrong here?

Posting this query on Pub/Sub forum would be great to get the required help in this case

https://www.googlecloudcommunity.com/gc/forums/filteredbylabelpage/board-id/cloud-data-analytics/label-name/cloud%20pubsub

Hello @rishabh-rastogi ,

I have seen your response in the same inquiry in StackOverflow, stating that you have found the answer while reviewing other threads. Quoting your solution here for the community’s visibility.

I have found the solution while referring to other threads and GitHub issues.> > The credentials provider does not have the necessary scopes to publish a message to a regional endpoint. We need to add the necessary scopes explicitly. See below.

@Bean
  public CredentialsProvider credentialsProvider() {
    return () ->
        ServiceAccountCredentials.fromStream(Files.newInputStream(Paths.get(credentialsFilePath)))
            .createScoped(PublisherStubSettings.getDefaultServiceScopes());
  }

Reference> Google Pub/Sub API gets OAUTH2 authentication failure when trying to connect to a specific endpoint> https://github.com/googleapis/java-pubsub/issues/930

Thank you for your contributions.