如何解决CORS策略已阻止从来源“ http:// localhost:4200”访问“ http:// localhost:8080 / api / auth / userdetails”处的XMLHttpRequest
我已经创建了一个REST服务进行身份验证,并且成功。
在邮递员中工作正常。
我正试图从Angular调用它。
登录表单工作正常。
loginURL: string = 'localhost:8080/authenticate';
this.http.post(this.loginURL,{
username: 'headoffice',password: 'guest'
}).subscribe((successResp) => {
resolve(successResp);
},(errorResp) => {
resolve(errorResp);
}
);
但是当我呼叫localhost:8080 / api / auth / userdetails
userDetailsURL: string = 'localhost:8080/api/auth/userdetails';
token: string = '.....';
this.http.post(this.userDetailsURL,null,{
headers: new HttpHeaders({
'Authorization': 'Bearer ' + token
})
}).subscribe((successResp) => {
resolve(successResp);
},(errorResp) => {
resolve(errorResp);
}
);
我遇到类似的错误
Access to XMLHttpRequest at 'http://localhost:8080/api/auth/userdetails' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
zone-evergreen.js:2845 POST http://localhost:8080/api/auth/userdetails net::ERR_Failed
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity.csrf().disable().authorizeRequests()
.antMatchers("/authenticate").permitAll().anyRequest()
.authenticated().and().exceptionHandling()
.authenticationEntryPoint(jwtAuthenticationEntryPoint)
.and().sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.addFilterBefore(customJwtAuthenticationFilter,UsernamePasswordAuthenticationFilter.class);
}
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedMethods("GET","POST","PUT","PATCH","DELETE","OPTIONS","HEAD","TRACE","CONNECT")
.allowedOrigins("http://localhost:4200");
}
请帮帮我。
为什么它在邮递员中工作而不在Angular中工作。
我想念什么?
解决方法
将CORS与Spring Security结合使用时,您必须在安全性配置中再执行一步,以使其生效。这是因为必须先处理CORS。
https://www.baeldung.com/spring-cors#cors-with-spring-security
在安全配置中,必须先调用cors,然后再进行其他逻辑操作
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity.cors().and()...
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。