CORS 对我来说是个问题..
我在 http://localhost:8080 上使用 SPRING 创建了一个 REST API我曾经在 http://localhost 上的纯 JS 站点上使用此 API ,但是应用 OAuth2 后,以下错误开始困扰我。
Access to XMLHttpRequest at 'http://localhost:8080/oauth/token' from origin 'http://localhost' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status
在 OAuth 之前(使用 AJAX 和 POSTMAN),我可以访问 API,而不会出现 CORS 问题,在应用 OAuth 之后,我可以仅在 POSTMAN 上使用 API,但我无法使用 AJAX 执行相同的操作。
我的 AJAX 代码:
function pronta(){
var username = "postmain"; // yes, I wrote wrong
var password = "1234";
function make_base_auth(user, password) {
var tok = user + ':' + password;
var hash = btoa(tok);
return "Basic " + hash;
}
$.ajax
({
type: "POST",
url: "http://localhost:8080/oauth/token",
dataType: 'json',
data: {
'grant-type': 'password',
'username': 'Tiago',
'password': '123'
},
header:{'Authorization': make_base_auth(username, password)}, // I've tried on both manners. with header and with beforeSend
beforeSend: function (xhr){
xhr.setRequestHeader('Authorization', make_base_auth(username, password));
},
success: function (){
alert('done');
}
});
}
我的 CORS 过滤器(在 SPRING REST API 上)
@Component
public class SimpleCORSFilter implements Filter {
@Override
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-Methods", "POST, GET, PUT, OPTIONS, DELETE, PATCH");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
chain.doFilter(req, res);
}
@Override
public void init(FilterConfig filterConfig) {}
@Override
public void destroy() {}
}
过滤器在 OAuth 之前运行良好
一些想法发生了什么?
谢谢
最佳答案
我明白了.. 问题是每次我尝试发出请求时,之前都会提交预检请求(就像 REST 架构的设计初衷)。
考虑到这一点,我只是准备服务器以允许 OPTIONS 方法。
像这样..
@Order(-1)
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers(HttpMethod.OPTIONS, "/oauth/token").permitAll();
}
在类开始之前不要忘记@Configuration
注释。
关于javascript - REST API - CORS 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53889509/