Skip to content

Instantly share code, notes, and snippets.

@gamee1910
Created July 19, 2025 15:24
Show Gist options
  • Select an option

  • Save gamee1910/09c692368dd63214c54aefd0b1d7484b to your computer and use it in GitHub Desktop.

Select an option

Save gamee1910/09c692368dd63214c54aefd0b1d7484b to your computer and use it in GitHub Desktop.
Authentication microservice
@Component
public class AuthenticationFilter implements GlobalFilter, Ordered {
private static final String[] PUBLIC_ENDPOINTS = {
"/account/login", "/account/verify", "/blindbox"
};
private static final Logger log = LoggerFactory.getLogger(AuthenticationFilter.class);
private final ObjectMapper objectMapper;
private final AccountService accountService;
public AuthenticationFilter(ObjectMapper objectMapper, AccountService accountService) {
this.objectMapper = objectMapper;
this.accountService = accountService;
}
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
if (isPublicEndpoint(exchange.getRequest())) {
return chain.filter(exchange);
}
List<String> authHeader = exchange.getRequest().getHeaders().get(HttpHeaders.AUTHORIZATION);
if (CollectionUtils.isEmpty(authHeader))
return unauthenticated(exchange.getResponse());
String token = authHeader.getFirst().replace("Bearer ", "");
return accountService.verify(new VerifyRequest(token)).flatMap(
response -> {
if (response != null && response.isValid()) {
return processWithUserID(response.getUserId(), exchange, chain);
} else {
return unauthenticated(exchange.getResponse());
}
}
).onErrorResume(throwable -> {
log.error("Authentication failed ", throwable);
return unauthenticated(exchange.getResponse());
});
}
@Override
public int getOrder() {
return -1;
}
private boolean isPublicEndpoint(ServerHttpRequest request) {
return Arrays.stream(PUBLIC_ENDPOINTS)
.anyMatch(s -> request.getURI().getPath().matches(s));
}
private Mono<Void> processWithUserID(int userId, ServerWebExchange exchange, GatewayFilterChain chain) {
ServerHttpRequest serverHttpRequest = exchange.getRequest()
.mutate()
.header("X-USER-ID", String.valueOf(userId))
.build();
System.out.println("USER" + userId);
return chain.filter(exchange.mutate().request(serverHttpRequest).build());
}
private Mono<Void> unauthenticated(ServerHttpResponse response) {
ResponseError responseError = new ResponseError(HttpStatus.UNAUTHORIZED.value(), "Unauthorized");
String body = null;
try {
body = objectMapper.writeValueAsString(responseError);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
response.setStatusCode(HttpStatus.UNAUTHORIZED);
response.getHeaders().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
return response.writeWith(
Mono.just(response.bufferFactory().wrap(body.getBytes())));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment