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
<servlet>
<!--content eluded for clarity-->
<init-param>
<param-name>dispatchOptionsRequest</param-name>
<param-value>true</param-value>
</init-param>
</servlet>
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.
<filter>
<filter-name>cors-filter</filter-name>
<filter-class>ai.surge.usrmngmtservice.util.cors.CorsFilter</filter-class>
<init-param>
<param-name>cors.allowed.origins</param-name>
<param-value>*</param-value>
</init-param>
<init-param>
<param-name>cors.allowed.methods</param-name>
<param-value>GET,POST,OPTIONS,PUT</param-value>
</init-param>
<init-param>
<param-name>cors.exposed.headers</param-name>
<param-value>Authorization,Access-Control-Allow-Origin,Access-Control-Allow-Credentials</param-value>
</init-param>
<!--<init-param>-->
<!--<param-name>cors.preflight.maxage</param-name>-->
<!--<param-value>1800</param-value>-->
<!--</init-param>-->
</filter>
You should be ready to go now.