@Provider
public class CorsFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
final HttpServletResponse httpResponse = (HttpServletResponse) response;
httpResponse.addHeader("Access-Control-Allow-Origin", "http://localhost:3000"); // React running on port 3000
httpResponse.addHeader("Access-Control-Allow-Credentials", "true");
httpResponse.addHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
chain.doFilter(request, response);
}
}
在React前端我有
return fetch('http://localhost:8080/user/login', {
method: 'POST',
credentials: 'include',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
username: username,
password: password
})
})
当我检查浏览器中是否有cookie时,它们没有设置。任何知道为什么不呢?
您似乎缺少该过程的巨大部分。您不想将用户名和密码作为
JSON
对象传递。您想要一个编码的字符串,将其设置在
Authorization
标题中:
const auth = btoa(`${username}:${password}`);
fetch('/' + route, {
method: 'POST',
headers: {
'Authorization': `Basic ${auth}`
}
}
在您的后端,您需要一个
BasicAuth
oAuth
Checker。
我建议阅读