I have created an application based on microservices architecture , So from postman its working fine, I have created gateway and authentication service and I am registering user and signin user by providing him JWT token . All is working fine but when I am hitting from my angular application through gateway its showing error:
signup:1 Access to fetch at ‘http://localhost:8080/auth/register’ from origin ‘http://localhost:4200’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. If an opaque response serves your needs, set the request’s mode to ‘no-cors’ to fetch the resource with CORS disabled.
But when I am hitting the service directly from angular page without gateway its working fine and user is also registered
So what can be the issue?
My gateway code:
private final RouteValidator validator;
private final JWTValidation jwtValidation;
@Override
public GatewayFilter apply(Config config) {
return (exchange, chain) -> {
var request = exchange.getRequest();
if (validator.isSecured.test(request)) {
if (!request.getHeaders().containsKey(HttpHeaders.AUTHORIZATION)) {
throw new TokenMissingException("Token is not present");
}
String authHeader = request.getHeaders().getFirst(HttpHeaders.AUTHORIZATION);
if (authHeader != null && authHeader.startsWith("Bearer ")) {
authHeader = authHeader.substring(7);
}
try {
jwtValidation.validateToken(authHeader);
} catch (Exception ex) {
throw new TokenMissingException("Not authorized to access the request");
}
}
return chain.filter(exchange);
};
}
package com.socials.Gateway.filter;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.function.Predicate;
@Component
public class RouteValidator {
public static final List<String> apiList = List.of(
"/auth/register",
"/auth/getToken",
"/auth/verify-account",
"/auth/forgotPass",
"/auth/resetPass",
"/auth/refreshToken",
"/eureka"
);
public Predicate<ServerHttpRequest> isSecured = serverHttpRequest ->
apiList.stream().noneMatch(uri -> serverHttpRequest.getURI().getPath().contains(uri));
}
private static final String SECRET = "43d7640272c961817cbe57f9811a776dfde782048b35644ac1732778ea958806";
public void validateToken(final String token) {
Jwts.parserBuilder().setSigningKey(getSigningKey()).build().parseClaimsJws(token);
}
private SecretKey getSigningKey() {
byte[] key = Decoders.BASE64.decode(SECRET);
return Keys.hmacShaKeyFor(key);
}
}
avar mittal is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.