Merge branch '25-cors-configuration-does-not-allow-authorization-header' into 'dev'

Resolve "CORS configuration does not allow Authorization header"

Closes #25

See merge request sa4-2020/the-sanmarinoes/backend!31
This commit is contained in:
Claudio Maggioni 2020-03-10 15:04:03 +01:00
commit 046010d1d8
2 changed files with 27 additions and 6 deletions

View file

@ -1,6 +1,7 @@
package ch.usi.inf.sa4.sanmarinoes.smarthut.config; package ch.usi.inf.sa4.sanmarinoes.smarthut.config;
import java.io.IOException; import java.io.IOException;
import java.util.List;
import javax.servlet.*; import javax.servlet.*;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
@ -13,16 +14,32 @@ import org.springframework.stereotype.Component;
@Component @Component
public class CORSFilter implements Filter { public class CORSFilter implements Filter {
@Override static void setCORSHeaders(HttpServletResponse response) {
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "HEAD, PUT, POST, GET, OPTIONS, DELETE"); response.setHeader("Access-Control-Allow-Methods", "HEAD, PUT, POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600"); response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader( response.setHeader(
"Access-Control-Allow-Headers", "Access-Control-Allow-Headers",
"Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers"); String.join(
",",
List.of(
"Access-Control-Allow-Headers",
"Origin",
"Accept",
"X-Requested-With",
"Authorization",
"Content-Type",
"Access-Control-Request-Method",
"Access-Control-Request-Headers")));
}
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
final HttpServletResponse response = (HttpServletResponse) res;
setCORSHeaders(response);
chain.doFilter(req, res); chain.doFilter(req, res);
} }

View file

@ -16,6 +16,10 @@ public class JWTAuthenticationEntryPoint implements AuthenticationEntryPoint {
HttpServletResponse response, HttpServletResponse response,
AuthenticationException authException) AuthenticationException authException)
throws IOException { throws IOException {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized"); if (!"OPTIONS".equals(request.getMethod())) {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
} else {
CORSFilter.setCORSHeaders(response);
}
} }
} }