我正在尝试将GET请求从Angular前端传递到我的Spring引导后端。我正在使用JWT对所有内容进行身份验证,并且正在使用HTTP拦截器将令牌添加到请求标头中,如下所示:
@Injectable()
export class Interceptor implements HttpInterceptor {
constructor(public auth: AuthService) { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const token: string = this.auth.getToken();
if(this.auth.isAuthenticated()) {
request = request.clone({
setHeaders : { Authorization : `${this.auth.getToken()}`,}
});
}
return next.handle(request);
}
}
我看不到chrome的请求标头中添加了令牌: image link
并且后端也看不到它,因此返回403。我怀疑这与CORS有关(我将前端和后端托管在同一台计算机上,而我正在使用Chrome + CORS插件)。
所以我尝试允许CORS请求到我的后端:
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.cors().disable()
.authorizeRequests()
.antMatchers("/login").permitAll()
.antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
.anyRequest().authenticated().and().addFilterBefore(new JwTokenFilter(jwTokenProvider), UsernamePasswordAuthenticationFilter.class);
}
这似乎仍然行不通。我也尝试使用Postman来执行相同的GET请求,这似乎很好用。有人可以帮我吗?
答案 0 :(得分:1)
也请覆盖cors映射或定义"@angular/core": "^7.0.0-rc.0"
,请根据屏幕截图@Bean for CorsMapping
定义正确的前端原点
allowedOrigins("http://evil.com")
或在配置中定义@Bean,也可以定义过滤器
@Configuration
public class MvcConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowCredentials(true).allowedOrigins("http://evil.com")
.allowedHeaders("Authorization", "Cache-Control", "Content-Type", "Accept", "X-Requested-With", "Access-Control-Allow-Origin", "Access-Control-Allow-Headers", "Origin")
.exposedHeaders("Access-Control-Expose-Headers", "Authorization", "Cache-Control", "Content-Type", "Access-Control-Allow-Origin", "Access-Control-Allow-Headers", "Origin")
.allowedMethods("GET", "OPTIONS", "POST", "PUT", "DELETE", "PATCH");
}
}
方法2:
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("your origin or * for allow all");
}
};
}
在控制器上
@CrossOrigin