Problem:
You are not configuring 'Access-Control-Allow-Origin'
correctly and your current configuration is simply ignored by the server.
Situation:
The Error stack trace says:
The value of the
'Access-Control-Allow-Origin'
header in the response must not be the wildcard'*'
when the request’s credentials mode is ‘include’. Origin ‘http://localhost:4200’ is therefore not allowed access.
It means that apart from the fact that you can’t set 'Access-Control-Allow-Origin'
to the wildcard "*"
, your domain 'http://localhost:4200'
is not allowed access too.
To answer your question:
How can I resolve this when I’ve already set the allowed origin in the WebSocketConfig to the client domain?
Solution:
I guess you don’t need to set the allowed origin in the WebSocketConfig
because it’s meant to configure WebSocket-style messaging in web applications as stated in WebSocket Support in Spring documentation, you will need to configure it in a CORSFilter
configuration class as it’s meant to configure Spring Filters for Web application access.
This is what you will need in your CORSFilter.java
configuration class:
public class CORSFilter implements Filter {
// This is to be replaced with a list of domains allowed to access the server
//You can include more than one origin here
private final List<String> allowedOrigins = Arrays.asList("http://localhost:4200");
public void destroy() {
}
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
// Lets make sure that we are working with HTTP (that is, against HttpServletRequest and HttpServletResponse objects)
if (req instanceof HttpServletRequest && res instanceof HttpServletResponse) {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
// Access-Control-Allow-Origin
String origin = request.getHeader("Origin");
response.setHeader("Access-Control-Allow-Origin", allowedOrigins.contains(origin) ? origin : "");
response.setHeader("Vary", "Origin");
// Access-Control-Max-Age
response.setHeader("Access-Control-Max-Age", "3600");
// Access-Control-Allow-Credentials
response.setHeader("Access-Control-Allow-Credentials", "true");
// Access-Control-Allow-Methods
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
// Access-Control-Allow-Headers
response.setHeader("Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept, " + "X-CSRF-TOKEN");
}
chain.doFilter(req, res);
}
public void init(FilterConfig filterConfig) {
}
}
You can see the use of :
private final List<String> allowedOrigins = Arrays.asList("http://localhost:4200");
To set the list of domains allowed to access the server.
References:
You may need to take a look at CORS support in Spring Framework and Enabling Cross Origin Requests for a RESTful Web Service for further reading about it.