我正在使用ReactSpring前端在后端中使用Spring Boot。 我正在尝试从前端调用终点,如下所示:
testOktaTokenAtRest(data) {
var oauth=JSON.parse(localStorage.getItem('okta-token-storage'))
console.log("toekn is: ==> "+oauth.accessToken.tokenType +
oauth.accessToken.accessToken)
console.log("toekn received from action is inside this obj: ",data)
var searchCriteria = JSON.stringify(data.data)
console.log("searchCriteria data -------: " , searchCriteria)
let _headerForSearch={
auth : 'Bearer ' + oauth.accessToken.accessToken
}
$.ajax({
method: "post",
url: "http://localhost:8000/ckcapp/api/posttest",
contentType: "application/json",
dataType: "json",
data:searchCriteria,
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", _headerForSearch.auth);
},
success: function(response) {
console.log("response from okta enabled get api is: ",response)
},
error: function(xhr, status, error) {
console.log("error from okta enabled get api is: ",xhr.responseText
+ " " +status + " " + error );
}
});
}
我提出请求时,出现以下错误:-
在以下位置访问XMLHttpRequest 'http://localhost:8000/ckcapp/api/posttest' 来自来源“ http://localhost:3000”的信息已被CORS政策阻止: 对预检请求的响应未通过访问控制检查:否 请求中存在“ Access-Control-Allow-Origin”标头 资源。
我的spring-boot应用程序具有以下配置:
CORSFilter
public class CORSFilter implements Filter {
private static final String ONE_HOUR = "3600";
@Override
public void init(FilterConfig filterConfig) throws ServletException
{
}
@Override
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin",
"http://localhost:3000");
response.setHeader("Access-Control-Allow-Methods", "POST, PUT,
GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", ONE_HOUR);
response.setHeader("Access-Control-Request-Headers",
"authorization,content-type");
response.setHeader("Access-Control-Allow-Headers", "X-Requested-
With,Origin,Content-Type, Accept, x-device-user-agent, Content-Type");
if (req instanceof HttpServletRequest) {
HttpServletRequest httpServletRequest = (HttpServletRequest)
req;
if (httpServletRequest.getHeader(HttpHeaders.ORIGIN) != null
&&
httpServletRequest.getMethod().equals(HttpMethod.OPTIONS.name())
&&
httpServletRequest.getHeader(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD)
!=
null) {
return;
}
}
chain.doFilter(req, res);
}
@Override
public void destroy() {
}
}
我将端点称为:
@RestController
@CrossOrigin(origins = "http://localhost:3000")
public class CkcOktaController {
@PostMapping("/api/posttest")
@PreAuthorize("hasAuthority('SCOPE_email')")
public String setString(@RequestBody CustomerDetailsNew
customerDetails) {
System.out.println("In post method ");
System.out.println("text :" + customerDetails.toString());
System.out.println("text :" + customerDetails.getEntityId());
return "Success";
}
}
我想我缺少一些配置。
该应用受OKTA保护。
答案 0 :(得分:2)
我在Spring JWT上使用React遇到了类似的问题,这被CORS政策阻止。
在我的SecurityConfigurer类中添加了http.cors()
来解决
@EnableWebSecurity
public class SecurityConfigurer extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and().csrf().disable().......
}
}
@CrossOrigin(origins = {"http://localhost:3000"})
@RestController
答案 1 :(得分:0)
我通常使用bean来配置我的CORS设置。这来自recent blog post:
class FormView(NamedUrlSessionWizardView,):
form_list = ( //static one
("step-one", FormStepOne),
("step-two", FormStepTwo),
("step-three", FormStepThree),
)
def get_form_list(self): //updates form_list according to some logic
self.form_list = OrderedDict()
self.form_list["step-one"] =
self.integration_class.step_one_form_class
self.form_list["step-two"] =
self.integration_class.step_two_form_class
self.form_list["step-three"] =
self.integration_class.step_three_form_class
return super().get_form_list()