簡體   English   中英

Angular 攔截器:請求中添加的標頭未正確設置,無法從 API 獲取它們

[英]Angular Interceptor: headers added in the request not set properly, can't fetch them from the API

我正在嘗試在我的 angular 攔截器中添加一些自定義標頭,如下所示:

@Injectable()
export class HttpJwtAuthInterceptor implements HttpInterceptor {

  constructor() {}

  intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
    localStorage.setItem('token', 'qsdfqsdfqsdfqsdf');
    if (localStorage.getItem('cuid') && localStorage.getItem('token')) {
      request = request.clone({
        setHeaders: {
          'sm_universalid':'blablabla',
          Authorization: `Bearer ${localStorage.getItem('token')}`,
        },
      });
    }



    return next.handle(request);
  }
}

上面的攔截器被添加到app.module.ts的 providers 屬性中:

  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: HttpJwtAuthInterceptor,
      multi: true,
    },
    { provide: BASE_PATH, useValue: environment.apiUrl },
  ],

在我的 spring 啟動應用程序中,我添加了一個過濾器來檢查是否收到了標頭,如果沒有則拋出異常:

String cuid = request.getHeader(SM_UNIVERSAL_ID);
if (cuid == null || cuid.isEmpty()) {
    log.error("Failed authentication: cuid header not found in the request or it is empty");
    throw new FailedAuthenticationException("cuid header not found in the request or it is empty:"+cuid);
}

不幸的是,過濾器找不到添加的標頭,我嘗試記錄收到的標頭列表,我發現它們被添加為access-control-request-headers header 的值: 在此處輸入圖像描述

如何分別獲取這些標題? 以及為什么將它們添加到訪問控制請求標頭header 中?

下面是我的 spring 安全 class 配置的快照(此處應用了 header 過濾器):

 @Configuration
@EnableWebSecurity
@Slf4j
@RequiredArgsConstructor
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    private final HeaderVerificationFilter headerVerificationFilter;
    private final JwtAuthorizationFilter jwtAuthorizationFilter;
    private final JwtAuthEntryPoint jwtAuthenticationEntryPoint;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //csrf is disabled because we are not using cookies
        http.csrf().disable();

        // No session will be created or used by spring security
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        //Entry points
        http.formLogin().loginProcessingUrl("/api/login").permitAll()
                //Disallow everything else
                .and().authorizeRequests().anyRequest().authenticated();

        //if a user try to access a resource without having enough permissions
        http.exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint);

        // Apply Header and JWT filters
        http.apply(new JwtTokenFilterConfigurer(headerVerificationFilter, jwtAuthorizationFilter, jwtAuthenticationEntryPoint));
    }


    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder(12);
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        // Allow swagger to be accessed without authentication
        web.ignoring().antMatchers("/v2/api-docs")//
                .antMatchers("/swagger-resources/**")//
                .antMatchers("/swagger-ui.html")//
                .antMatchers("/configuration/**")//
                .antMatchers("/webjars/**")//
                .antMatchers("/public");
    }

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return authenticationManager();
    }
}

試試這個方法:

const authReq = req.clone({
    headers: new HttpHeaders({
      'sm_universalid':  'blablabla',
      'Authorization': `Bearer ${localStorage.getItem('token')}`
    })
  });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM