没有设置请求头

时间:2019-05-27 19:03:18

标签: javascript angular request http-headers jwt

我有一个带有JTW的Java Spring中的Angular 7应用程序和一个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);

的结果

好像还可以,授权和令牌就在那里

enter image description here

请求

不要在此处传递令牌:c

enter image description here

错误

  

OPTIONS 401访问XMLHttpRequest   “ http://localhost:4200”处的CORS政策已阻止:对   飞行前请求未通过访问控制检查:它没有   HTTP正常状态。

我对insonmia进行了相同的请求(通过了授权和令牌),一切都很好,问题在于角度请求。

2 个答案:

答案 0 :(得分:0)

首先,如果尚未这样做,则需要在根模块中提供拦截器。将此添加到providers字段:

{ provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true }

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

还从Angular存储库中的某个问题中检出this discussion。如果您从导入HttpClientModule的第三方程序包中导入某些模块,则会发生相同的行为。

答案 1 :(得分:0)

感谢您的意见,我能够制定解决方案,我修改了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();
    }
}