0

我正在尝试将 GET 请求从我的 Angular 前端传递到我的 Spring Boot 后端。我正在使用 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 的请求标头中添加了令牌: 图片链接

后端也看不到它,因此返回 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 请求,这似乎工作得很好。有谁可以帮我离开这里吗?

4

1 回答 1

1

还覆盖cors映射或定义@Bean for CorsMapping,请定义您正确的前端原点,我相信它根据您的屏幕截图allowedOrigins("http://evil.com")

@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");
    }
}

或者在配置中定义 @Bean 或者你也可以定义 Filter

   @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**").allowedOrigins("your origin or * for allow all");
            }
        };
    }

方法2:

@CrossOrigin在控制器上

@CrossOrigin(origins = "http://example.com", maxAge = 3600)
@RestController
@RequestMapping("/account")
public class AccountController {
于 2018-10-18T11:16:50.917 回答