gpt4 book ai didi

java - 使用 basicauth 的 Ajax CORS 请求在浏览器上给出 401 错误

转载 作者:行者123 更新时间:2023-11-30 06:16:46 30 4
gpt4 key购买 nike

我知道有很多关于同一问题的帖子,但都没有解决我的问题。

我有一个带有以下 API 的 springboot 微服务应用程序

@RestController
@RequestMapping({ "/sample" })
public class SampleController {


@CrossOrigin(origins = "http://192.168.0.31:8080", allowCredentials = "false", allowedHeaders = "*")
//@CrossOrigin//(allowCredentials = "false")
@RequestMapping(value="/welcome" , method=RequestMethod.POST, produces={"application/json"})
public JSONObject getWelcomeResponse(@RequestParam Map<String,String> request){
JSONObject response=new JSONObject();

response.put("response", "Welcome user");
System.out.println("Complterd ****");
return response;
}
}

属性文件

server.port=8081
security.user.name=test
security.user.password=test123
#security.basic.enabled=false

我的客户端代码是

 $(document).ready(function(){
$.ajax({
url: "http://192.168.0.31:8081/sample/welcome",
type : "POST",
crossDomain:true,
crossOrigin:true,

beforeSend: function (xhr) {
// Use BASIC Authentication
xhr.setRequestHeader ("Authorization", "Basic " + btoa("test:test123"));
},
error: function(xhr, status, errorThrown) {
alert(status, errorThrown);
// Error block
console.log("xhr: " + xhr);
console.log("status: " + status);
console.log("errorThrown: " + errorThrown);
}
})
.then(function(data, status, xhr) {
alert(data);
console.log("xhr: " + xhr);
console.log("status: " + status);
console.log("data: "+ data);

$('.message').append(JSON.stringify(data));

});
});

当我禁用基本身份验证时,cors 请求工作正常。但如果启用,则会出现 401 预检请求错误。

我也尝试过默认和自定义方式的@CrossOrigin。但遇到同样的错误。还尝试使用如下所示的过滤器类。

@EnableWebMvc
public class MyAppConfigurations implements Filter {

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)

throws IOException, ServletException {

HttpServletResponse httpResponse = (HttpServletResponse) response;

HttpServletRequest httpRequest = (HttpServletRequest) request;

if("OPTIONS".equalsIgnoreCase(httpRequest.getMethod())) {

httpResponse.setStatus(HttpServletResponse.SC_OK);
System.out.println("filterde response");

} else {

chain.doFilter(request, response);

}
}
}

有人可以帮我弄清楚我在这段代码中缺少什么吗?

最佳答案

您必须为您的Spring MicroService创建CORS FILTER

import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CorsFilter implements Filter {

@Override
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain filterChain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
HttpServletRequest request = (HttpServletRequest) req;

if (response instanceof HttpServletResponse) {
addCorsHeader(response);
if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
response.setStatus(HttpServletResponse.SC_OK);
} else {
filterChain.doFilter(req, res);
}
}
}

private void addCorsHeader(HttpServletResponse response) {
response.addHeader("Access-Control-Allow-Origin", "http://localhost:4200"); // Update with yours
response.addHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, HEAD");
response.addHeader("Access-Control-Allow-Credentials", "true");
response.addHeader("Access-Control-Allow-Headers", "Authorization, X-PINGOTHER, Origin, X-Requested-With, Content-Type, Accept");
response.addHeader("Access-Control-Max-Age", "1728000");
}

@Override
public void destroy() {
}

@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
}

关于java - 使用 basicauth 的 Ajax CORS 请求在浏览器上给出 401 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49022443/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com