首页 > 解决方案 > 未正确添加授权标头

问题描述

我正在使用 JWT,并成功制作了一个处理它们的 Express 应用程序,并使用 Postman 进行了验证。然后我去做 Angular 7 前端,我偶然发现了一个问题。我成功添加了标头,但它们似乎没有出现在实际请求中:

我记录了标题,可以看到它们已设置:

在此处输入图像描述

但是当我查看请求时,它没有出现:

在此处输入图像描述

我的代码如下所示:

@Injectable({
  providedIn: 'root'
})
export class ApiService {

  private baseUrl = environment.apiUrl;

  constructor(private http: Http,
              private auth: AuthService) { }

  get(url: string) {
    return this.request(url, RequestMethod.Get);
  }

  post(url: string, body: Object) {
    return this.request(url, RequestMethod.Post, body);
  }

  put(url: string, body: Object) {
    return this.request(url, RequestMethod.Put, body);
  }

  delete(url: string) {
    return this.request(url, RequestMethod.Delete);
  }

  request(url: string, method: RequestMethod, body?: Object) {
  let headers = new Headers()
  headers.append('Content-Type', 'application/json');
  headers.append('Authorization', `Bearer ${this.auth.getToken()}`);

  console.log(headers);

  const requestOptions = new RequestOptions({
    url: `${this.baseUrl}/${url}`,
    method: method,
    headers: headers
  });

  if (body) {
    requestOptions.body = body;
  }

  const request = new Request(requestOptions);

  return this.http.request(request)
    .pipe(map((res: Response) => res.json()))
    .pipe(catchError((res: Response) => this.onRequestError(res)));
}

onRequestError(res: Response) {
  const statusCode = res.status;
  const body = res.json();


  const error = {
    statusCode: statusCode,
    error: body.error
  };

  console.log(error);

  return observaleThrowError(error || "Server error");
}
}

登录组件:

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
  email: string;

  constructor(public api: ApiService,
    private auth: AuthService,
    private router: Router) { }

  ngOnInit() {
  }

  onSubmit(form: NgForm) {
    const values = form.value;

    const payload = {
      username: values.username,
      password: values.password
    }

    this.api.post('authenticate', payload).subscribe(data => {
      this.auth.setToken(data.token);
      this.router.navigate(['/contacts']);
    })
  }
}

再一次,它与 Postman 一起工作得很好。对出了什么问题有任何想法吗?

标签: angularheaderjwtangular7

解决方案


对于 Angular 应用程序中的 JWT 身份验证,我建议您使用拦截器。

你定义你的拦截器是这样的:

import {Injectable} from '@angular/core';
import {HttpRequest, HttpHandler, HttpEvent, HttpInterceptor} from '@angular/common/http';
import {Observable} from 'rxjs/Observable';

@Injectable()
export class JwtInterceptor implements HttpInterceptor {
     intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
     // add authorization header with jwt token if available
     const currentUser = JSON.parse(String(localStorage.getItem('currentUser')));
     if (currentUser && currentUser.Token) {
         request = request.clone({
         setHeaders: {
             Authorization: `Bearer ${currentUser.Token}`
         }
      });
      }
      return next.handle(request);
   }
}

基本上,它的作用是,它使用存储在客户端 localStorage 中的 JWT 令牌,并将其与每个 HTTP 请求一起发送到您的后端。

然后你只需要在你身上注册它app.module.ts

providers: [
  HttpClient,
  {
     provide: HTTP_INTERCEPTORS,
     useClass: JwtInterceptor,
     multi: true
  }
]

推荐阅读