initial commit

Signed-off-by: Peter Siegmund <developer@mars3142.org>
This commit is contained in:
2024-08-18 00:16:34 +02:00
commit 52c64f5d5d
17 changed files with 672 additions and 0 deletions

View 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);
}
}

View 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;
}
}