首页 > 解决方案 > 使用 Angular 和 spring boot 设置请求标头

问题描述

我遇到了一个非常奇怪的问题,我想在我的请求中向服务 spring boot 发送一个额外的参数 Authorization ,就像这样

Request headers
Authorization: bearer t-3e57cc74-3e7a-4fc7-9bbb-f6c83252db01
User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.97 Safari/537.11
Accept: */*
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
Cookie: JSESSIONID=908D73C50F09E75C9A0D674C4CB33D2F; ROUTEID=.1; __unam=3c3246b-13bc693352d-aa1535c-1

但是在 AppComponent 中使用这段代码

import { Component } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: [ './app.component.css' ]
})
export class AppComponent {
    constructor(private http: HttpClient) {}

    checkfingeradmin() {


        const headers = new HttpHeaders({
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': ' http://localhost:4200',
            'Access-Control-Allow-Credentials': 'true',
            'Access-Control-Allow-Methods': ' POST, GET, OPTIONS, DELETE',
            'Access-Control-Max-Age': ' 3600',
            'Access-Control-Allow-Headers': 'Content-Type, Accept, X-Requested-With, remember-me',
  'Authorization':
           'Bearer eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJoYXRlbTEyMyIsImF1dGgiOlt7ImF1dGhvcml0eSI6IlJPTEVfRU1Q'
        });
        this.http
            .get<any>(

                'http://localhost:8080/api/v1/pointage/ExitAdmin',
                { headers: headers }

            }
            )
            .subscribe((data) => {
                console.log(data);
            });
    }
}

在控制器 Spring 启动

@RestController
@CrossOrigin(origins = "*",maxAge = 3600)
@RequestMapping(value="/api/v1/pointage")
public class PointageController {  @GetMapping ("/EnterAdmin")
     public  ResponseEntity EnterAdmin(){
            return ResponseEntity.ok("for testing");}}

我使用此类jwtTokenFilter只是为了在控制台中获取消息以检查我的服务器 Spring 启动中的结果

public class JwtTokenFilter extends OncePerRequestFilter  {
 @Override
  protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
  HttpServletRequest request = (HttpServletRequest) httpServletRequest;
    HttpServletResponse response = (HttpServletResponse) httpServletResponse;

 String bearerToken = req.getHeader("Authorization");
      Enumeration<String> e = req.getHeaderNames();
      while(e.hasMoreElements()){
          String param = (String) e.nextElement();
          System.out.print(param + " : " + req.getHeader(param));
          System.out.print("\n");
if(req.getHeader(param).equals("access-control-request-headers")  ){
    System.out.print("\n========================= \n");
    System.out.print(req.getHeader(param));
    System.out.print("\n========================= \n");
}}}

它像这样发送没有传递值,它的请求类型也变成了 OPTION 而不是 GET,这里是控制台

host : localhost:8080
connection : keep-alive
accept : */*
access-control-request-method : GET
access-control-request-headers : authorization
origin : null
sec-fetch-mode : cors
sec-fetch-site : cross-site
user-agent : Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36
accept-encoding : gzip, deflate, br
accept-language : fr-FR,fr;q=0.9,en-US;q=0.8,en;q=0.7,und;q=0.6

========================= 
bearerToken : null
 msgaccess-control-allow-credentialsmsg : nullnull

谁能告诉我我怎样才能像这样通过授权:承载 eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJoYXRlbTEyMyIsImF1dGgiOlt7ImF1dGhvcml0eSI6IlJPTEVfRU1Q'

标签: angularspringspring-bootjwtauthorization

解决方案


您的 Angular 代码似乎是正确的。

您应该检查您的 Spring Security 配置。除了@CrossOrigin注释之外,还应通过以下方式启用 CORS WebSecurityConfigurerAdapter

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and()...
    }
}

Spring官方文档中的更多细节


推荐阅读