【发布时间】:2021-05-30 22:53:41
【问题描述】:
我使用 Spring 4 作为我的 Angular 应用程序的后端。当 Angular 应用程序向 Spring 应用程序发出请求时,我收到错误
Access to **XMLHttpRequest at 'http://localhost:8080/AdminController/allAdmins' 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.**
我正在使用自定义过滤器来验证每个用户请求 我的过滤器代码是:
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest httpReq = (HttpServletRequest) request;
HttpServletResponse httpResp = (HttpServletResponse) response;
// Ignoring the request URLs
if (Utils.ignoreURLs(IGNORE_URLS, httpReq.getRequestURI()) == true) {
filterChain.doFilter(request, response);
return;
}
// Fetching all the header params from request
HttpServletRequest httpRequest = (HttpServletRequest) httpReq;
Enumeration<String> headerNames = httpRequest.getHeaderNames();
String loggedUserId = null;
String authToken = null;
if (headerNames != null) {
while (headerNames.nextElement() != null && headerNames.hasMoreElements()) {
loggedUserId = httpRequest.getHeader(Constants.LOGGED_USER_ID);
authToken = httpRequest.getHeader(Constants.AUTH_TOKEN);
}
}
if (Utils.isBlank(loggedUserId) == true || Utils.isBlank(authToken) == true) {
httpResp.setContentType(MediaType.APPLICATION_JSON_VALUE);
mapper.writeValue(httpResp.getWriter(), getErrorDetailsMap());
return;
}
ApplicationContext appContext = AppContextConfig.getApplicationContext();
AccessManager accessManager = (AccessManager) appContext.getBean(AccessManager.class);
// I am validating authentication token here
if(accessManager.isValidToken(loggedUserId, authToken) == false) {
httpResp.setContentType(MediaType.APPLICATION_JSON_VALUE);
mapper.writeValue(httpResp.getWriter(), getErrorDetailsMap());
return;
}
filterChain.doFilter(request, response);
}
【问题讨论】:
标签: spring httprequest cross-origin-read-blocking