我正在尝试在Spring MVC应用程序中添加OAuth 2.0。用户应该经过身份验证才能获得api调用。我已经在spring mvc控制器中将标头设置为:
@RequestMapping(value = "/admin-api/get-all-order", method = RequestMethod.GET)
public ResponseEntity getAllOrders(@RequestHeader("Authorization") String bearerToken) {
try {
List<OrderModel> order = orderService.getAllOrders();
return new ResponseEntity(order, HttpStatus.OK);
} catch (HibernateException e) {
return new ResponseEntity(e.getMessage(), HttpStatus.BAD_REQUEST);
}
}
对于请求api,我使用了angular5。我用angular进行了api调用:
return this.http.get<T>(this.getAllOrderUrl, {
headers: {
"Authorization": "bearer " + JSON.parse(localStorage.getItem("token"))["value"],
"Content-type": "application/json"
}
}).catch(error => {
return this.auth.handleError(error);
})
我已经为“ localhost:4200”启用了CORS。 CORS过滤可以在其他请求上正常工作。
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
HttpServletRequest request = (HttpServletRequest) req;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods",
"ACL, CANCELUPLOAD, CHECKIN, CHECKOUT, COPY, DELETE, GET, HEAD, LOCK, MKCALENDAR, MKCOL, MOVE, OPTIONS, POST, PROPFIND, PROPPATCH, PUT, REPORT, SEARCH, UNCHECKOUT, UNLOCK, UPDATE, VERSION-CONTROL");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers",
"X-PINGOTHER,Content-Type,X-Requested-With,Accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers,Authorization,Key");
if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
response.setStatus(HttpServletResponse.SC_OK);
} else {
chain.doFilter(req, res);
}
}
我在做什么错?请帮帮我。希望得到积极的回应!
答案 0 :(得分:0)
如果要在不使用过滤器或配置文件的情况下启用CORS,只需添加
@CrossOrigin
到您的控制器顶部即可使用。