13
src/main/java/dev/mars3142/fhq/Application.java
Normal file
13
src/main/java/dev/mars3142/fhq/Application.java
Normal file
@@ -0,0 +1,13 @@
|
||||
package dev.mars3142.fhq;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
public class Application {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(Application.class, args);
|
||||
}
|
||||
|
||||
}
|
||||
59
src/main/java/dev/mars3142/fhq/edge/GCPGatewayFilter.java
Normal file
59
src/main/java/dev/mars3142/fhq/edge/GCPGatewayFilter.java
Normal file
@@ -0,0 +1,59 @@
|
||||
package dev.mars3142.fhq.edge;
|
||||
|
||||
import com.google.auth.oauth2.GoogleCredentials;
|
||||
import com.google.auth.oauth2.IdTokenCredentials;
|
||||
import com.google.auth.oauth2.IdTokenProvider;
|
||||
import java.io.IOException;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import lombok.val;
|
||||
import org.springframework.cloud.gateway.filter.GatewayFilter;
|
||||
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
@Slf4j
|
||||
public class GCPGatewayFilter extends AbstractGatewayFilterFactory<GCPGatewayFilter.Config> {
|
||||
|
||||
public GCPGatewayFilter() {
|
||||
super(Config.class);
|
||||
}
|
||||
|
||||
@Override
|
||||
public GatewayFilter apply(Config config) {
|
||||
return (exchange, chain) -> {
|
||||
try {
|
||||
val token = getAuthToken(config);
|
||||
exchange.getRequest()
|
||||
.mutate()
|
||||
.header("X-Serverless-Authorization", "Bearer " + token);
|
||||
return chain.filter(exchange);
|
||||
} catch (Exception e) {
|
||||
log.error("Error getting token", e);
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private String getAuthToken(Config config) throws IOException {
|
||||
val credentials = GoogleCredentials.getApplicationDefault();
|
||||
if (!(credentials instanceof IdTokenProvider)) {
|
||||
throw new IllegalArgumentException("Credentials are not an instance of IdTokenProvider.");
|
||||
}
|
||||
val tokenCredential =
|
||||
IdTokenCredentials.newBuilder()
|
||||
.setIdTokenProvider((IdTokenProvider) credentials)
|
||||
.setTargetAudience(config.getAudience())
|
||||
.build();
|
||||
|
||||
return tokenCredential.refreshAccessToken().getTokenValue();
|
||||
}
|
||||
|
||||
@Setter
|
||||
@Getter
|
||||
public static class Config {
|
||||
|
||||
private String audience;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user