@Component @Slf4j public class AuthorizationHeaderFilter extends AbstractGatewayFilterFactory<AuthorizationHeaderFilter.Config> { private Environment env;
public AuthorizationHeaderFilter(Environment env){ super(Config.class); this.env = env; }
@Override public GatewayFilter apply(Config config) { return ((exchange, chain) -> { ServerHttpRequest request = exchange.getRequest();
if(!request.getHeaders().containsKey(HttpHeaders.AUTHORIZATION)){ return onError(exchange, "No Authorization Header", HttpStatus.UNAUTHORIZED); }
String authorizationHeader = request.getHeaders().get(HttpHeaders.AUTHORIZATION).get(0); String jwt = authorizationHeader.replace("Bearer ", "");
if(!isJwtValid(jwt)){ return onError(exchange, "JWT token is not valid", HttpStatus.UNAUTHORIZED); }
return chain.filter(exchange); }); }
private boolean isJwtValid(String jwt){ boolean returnValue = true;
String subject = null; String key = env.getProperty("token.secret");
try { subject = Jwts.parser() .setSigningKey(env.getProperty("token.secret")) .parseClaimsJws(jwt).getBody() .getSubject(); } catch (Exception ex){ returnValue = false; }
if(subject == null || subject.isEmpty()){ returnValue = false; }
return returnValue; }
private Mono<Void> onError(ServerWebExchange exchange, String error, HttpStatus httpStatus) { ServerHttpResponse response = exchange.getResponse(); response.setStatusCode(httpStatus);
log.error(error); return response.setComplete(); }
public static class Config{
} }
|