Using angular and Spring Boot we\'re trying to add authentication to our service but for some reason we can\'t \'open\' and fetch data from an url we know works
Angu
You have mentioned in your comments that by using postman you can get the response as expected. That is a good starting point. I suspect that by using the curl command curl -i -X URL
from the terminal also returns the correct response.
If postman works correctly, you have to be aware by the fact that right before making a request angular sends another request, called pre-flight request, which does a minimal check to the endpoint at the server side.
This request is an OPTIONS type request.
First, you have to make sure that your dispatcherServlet accepts OPTIONS requests. You can achieve this either by specifying it in a *.properties
configuration file , such as:
spring.mvc.dispatch-options-request=true
or by configuring web.xml
dispatchOptionsRequest
true
After you have configured it to accept OPTIONS requests, create a Filter.java
and configure a CORS filter.
You can guide by the following example:
public class CorsFilter implements Filter{
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain filterChain) throws IOException, ServletException {
if(response instanceof HttpServletResponse){
HttpServletResponse alteredResponse = ((HttpServletResponse)response);
addCorsHeader(alteredResponse);
}
filterChain.doFilter(request, response);
}
private void addCorsHeader(HttpServletResponse response){
//TODO: externalize the Allow-Origin
response.addHeader("Access-Control-Allow-Origin", "*");
response.addHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, HEAD");
response.addHeader("Access-Control-Allow-Headers", "Authorization, X-PINGOTHER, Origin, X-Requested-With, Content-Type, Accept");
response.addHeader("Access-Control-Max-Age", "1728000");
}
@Override
public void destroy() {}
@Override
public void init(FilterConfig filterConfig)throws ServletException{}
}
In the end, don't forget to add this filter in web.xml
along with the following init-params.
cors-filter
ai.surge.usrmngmtservice.util.cors.CorsFilter
cors.allowed.origins
*
cors.allowed.methods
GET,POST,OPTIONS,PUT
cors.exposed.headers
Authorization,Access-Control-Allow-Origin,Access-Control-Allow-Credentials
You should be ready to go now.