没有为请求设置标头

Posted

技术标签:

【中文标题】没有为请求设置标头【英文标题】:Not setting headers for request 【发布时间】:2019-10-13 08:04:40 【问题描述】:

我有一个 Angular 7 应用程序和一个带有 JTW 的 Java Spring API。应用程序必须在 API 中的每个请求时发送令牌,但这不会发生,因此所有请求都会返回 401 错误。

应用模块

     ...

        @NgModule

(
      declarations: [
        AppComponent,
        PatientComponent,
        HeaderComponent,
        FooterComponent,
        AlertComponent,
        NotFoundComponent,
        UserRegisterComponent,
        LoginComponent,
        AuthGuardComponent
      ],
      imports: [
        BrowserModule,
        FormsModule,
        NgSelectModule, 
        ReactiveFormsModule,
        HttpClientModule,
        AppRoutingModule,
        NgbModule,
      ],
      providers: [
        
          provide : HTTP_INTERCEPTORS,
          useClass: AuthInterceptor,
          multi   : true,
        ,
      ],
      bootstrap: [AppComponent]
    )

    export class AppModule 

    

AuthInterceptor

import  HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpHeaders  from '@angular/common/http';
import  Injectable  from '@angular/core';
import  GeneralService  from '../_service/general.service';
import  Observable  from 'rxjs';

@Injectable()
export class AuthInterceptor implements HttpInterceptor 
    constructor(private generalService: GeneralService) 

    

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> 
        req = req.clone(
            setHeaders: 
                Authorization: 'Bearer eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1c2VyIiwic2NvcGVzIjpbeyJhdXRob3JpdHkiOiJTeXN0ZW0gVXNlciJ9XSwiaXNzIjoiaHR0cHM6Ly9hcGkubmVvZ3JpZC5jb20vIiwiaWF0IjoxNTU4OTgwOTAxLCJleHAiOjE1NTg5OTg5MDF9.vZByXryTI-1wGLYY1bU8DurOF15qlxA7QkdMW5UeM8c')
            
        );

       console.log(req);
       return next.handle(req);
    

请求

listAll() 
     return this.http.get('http://localhost:8080/api/listAll');


async get() 
    let error = null;

    let response = await this.listAll()
    .toPromise()
    .catch(error => error = error);

    console.log(response);
  

console.log(req) 的结果;

看起来不错,授权和令牌都在那里

请求

不要在这里传递令牌:c

错误

OPTIONS 401 访问 XMLHttpRequest at'http://localhost:4200' 已被 CORS 策略阻止:响应 预检请求未通过访问控制检查:它没有 HTTP 正常状态。

我对 insonmia 做了同样的请求(通过了授权和令牌),一切都很好,问题出在角度请求上。

【问题讨论】:

你能解释一下吗? 可能服务器设置不正确,因此拒绝了选项请求,但我们无法从您发布的内容中判断。参见例如***.com/a/40723041/3001761 请求中没有发送token的angular是不是有问题? 我对 insonmia 做了同样的请求(通过了授权和令牌),一切都很好,问题出在角度请求上。 您阅读了链接吗?预检选项请求不应包含凭据。除非您完成了整个 CORS 周期并从失眠症中提出了选项请求,否则您对问题所在的位置是错误的。 【参考方案1】:

首先,如果您还没有这样做,您需要在根模块中提供拦截器。将此添加到providers-字段:

 provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true 

其次,这可能与this issue 有关。确保您在整个应用程序中只有一个 HttpClientModule 导入。

还可以从 Angular 存储库的问题中查看 this discussion。如果您从导入HttpClientModule 的第三方包中导入某些模块,也会发生相同的行为。

【讨论】:

我觉得还可以,我把这段代码放在问题里,看那里。【参考方案2】:

感谢 cmets,我能够制定解决方案,我修改了我的 WebSecurityConfig.java api 文件,问题不在于角度请求。 谢谢大家。

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)

public class WebSecurityConfig extends WebSecurityConfigurerAdapter 
    @Autowired
    private ParametersProperties parameters;

    @Resource(name = "userService")
    private UserDetailsService userDetailsService;

    @Autowired
    private JwtAuthenticationEntryPoint unauthorizedHandler;

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception 
        return super.authenticationManagerBean();
    

    @Autowired
    public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception 
        auth.userDetailsService(userDetailsService)
                .passwordEncoder(encoder());
    

    @Bean
    public JwtAuthenticationFilter authenticationTokenFilterBean() 
        return new JwtAuthenticationFilter();
    

    @Override
    protected void configure(HttpSecurity http) throws Exception 
        http.cors().and().csrf().disable().
                authorizeRequests()
                .antMatchers(
                         "/swagger-resources/**",
                         "/swagger-ui.html",
                         "/webjars/**",
                         "/h2/**",
                         "/auth/signin",
                ).permitAll()
                /* the saver is the line below*/ 
                .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
                .anyRequest().authenticated()
                .and()
                .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        http
                .addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class)
                .headers().frameOptions().sameOrigin();
    

    @Bean
    public BCryptPasswordEncoder encoder()
        return new BCryptPasswordEncoder();
    

【讨论】:

以上是关于没有为请求设置标头的主要内容,如果未能解决你的问题,请参考以下文章

Jersey:如何将 MediaType 设置为 javax.ws.rs.core.Response,如果真正的“物理”响应标头没有任何相关信息

为啥 Spring Security 没有为带有请求标头的 GET 请求添加 Access-Control-Allow-Origin?

AFHTTPSessionManager 标头

有没有办法将 Authorize 属性与没有身份验证标头的请求一起使用?

使用cors包和设置Access-Control标头都没有运气

将请求特定的 HTTP 标头与 RestKit 一起使用