首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >未设置请求的头部

未设置请求的头部
EN

Stack Overflow用户
提问于 2019-05-28 03:03:18
回答 2查看 52关注 0票数 0

我有一个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(请求)的结果;

看起来没问题,授权和令牌都在那里

请求

不要在这里传递令牌:c

Erros

选项401访问位于‘http://localhost:4200’的XMLHttpRequest已被CORS策略阻止:对印前检查请求的响应未通过访问控制检查:它没有HTTP ok状态。

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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-05-28 05:55:19

谢谢你的评论,我能够制定一个解决方案,我修改了我的WebSecurityConfig.java应用程序接口文件,问题不是角度请求。感谢所有人。

@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();
    }
}
票数 0
EN

Stack Overflow用户

发布于 2019-05-28 04:33:10

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

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

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

也可以从Angular repo上的一个问题中查看this discussion。如果您从导入HttpClientModule的第三方包中导入某些模块,则可能会发生相同的行为。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56331269

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档