15

目前我在组件 .ts 文件中使用了这个静态代码,但这一个不起作用。它返回未经授权的(401)。但是当我将令牌作为查询字符串传递时,它工作正常。请为组件 .ts 文件提供一个工作示例。

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


    var t=`eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC9sb2NhbGhvc3Q6ODAwMFwvYXBpXC9sb2dpbiIsImlhdCI6MTUzNzcxNTMyNSwiZXhwIjoxNTM3NzE4OTI1LCJuYmYiOjE1Mzc3MTUzMjUsImp0aSI6IlBKWVhnSkVyblQ0WjdLTDAiLCJzdWIiOjYsInBydiI6Ijg3ZTBhZjFlZjlmZDE1ODEyZmRlYzk3MTUzYTE0ZTBiMDQ3NTQ2YWEifQ.1vz5lwPlg6orzkBJijsbBNZrnFnUedsGJUs7BUs0tmM`;

    var headers_object = new HttpHeaders();
        headers_object.append('Content-Type', 'application/json');
        headers_object.append("Authorization", "Bearer " + t);

        const httpOptions = {
          headers: headers_object
        };


   this.http.post(
                  'http://localhost:8000/api/role/Post', {limit:10}, httpOptions
                 ).subscribe(resp => {
                  this.roles = console.log(resp)
                  }
                );
4

5 回答 5

28

添加AuthInterceptor它将拦截您的所有 http 请求并将令牌添加到其标头中:

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

@Injectable()
export class AuthInterceptor implements HttpInterceptor {

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const token = localStorage.token; // you probably want to store it in localStorage or something

    if (!token) {
      return next.handle(req);
    }

    const req1 = req.clone({
      headers: req.headers.set('Authorization', `Bearer ${token}`),
    });

    return next.handle(req1);
  }

}

然后将其注册到您的AppModule

@NgModule({
  declarations: [...],
  imports: [...],
  providers: [
    { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true },
  ],
  bootstrap: [ AppComponent ],
})
export class AppModule { }

更多关于拦截器:

https://angular.io/guide/http#intercepting-requests-and-responses

于 2018-09-23T16:47:06.787 回答
20

您的代码的问题是HttpHeaders该类是不可变的,因此当您调用append它时,它实际上会返回一个具有指定值的新实例,但不会修改原始对象。

试试这个

var headers_object = new HttpHeaders().set("Authorization", "Bearer " + t);

Content-Type 默认设置为 jsonHttpClient

如果您需要在所有 API 调用中发送授权令牌,那么最好使用 Martin 建议的拦截器

于 2018-09-23T17:05:14.140 回答
3

另一种解决方案是使用 angular-jwt:https ://github.com/auth0/angular2-jwt

无需创建拦截器,只需更新您的 AppModule:

import { JwtModule } from "@auth0/angular-jwt";
import { HttpClientModule } from "@angular/common/http";

export function tokenGetter() {
    return localStorage.getItem('access_token');
}

@NgModule({
    declarations: [
        AppComponent
    ],
    imports: [
        HttpClientModule,
        JwtModule.forRoot({
            config: {
                tokenGetter: tokenGetter,
                allowedDomains: ['localhost:3000', 'example.com'],
                disallowedRoutes: ["http://example.com/examplebadroute/"],
                authScheme: "Bearer " // Default value
            }
        })
    ],
    bootstrap: [AppComponent]
})
export class AppModule { }

使用 Angular 的 HttpClient 发送的任何请求都会自动附加一个令牌作为 Authorization 标头。

于 2020-10-24T09:14:21.457 回答
2

请像这样创建 HttpHeaders 对象(而不是附加),

var t="eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC9sb2NhbGhvc3Q6ODAwMFwvYXBpXC9sb2dpbiIsImlhdCI6MTUzNzcxNTMyNSwiZXhwIjoxNTM3NzE4OTI1LCJuYmYiOjE1Mzc3MTUzMjUsImp0aSI6IlBKWVhnSkVyblQ0WjdLTDAiLCJzdWIiOjYsInBydiI6Ijg3ZTBhZjFlZjlmZDE1ODEyZmRlYzk3MTUzYTE0ZTBiMDQ3NTQ2YWEifQ.1vz5lwPlg6orzkBJijsbBNZrnFnUedsGJUs7BUs0tmM";

    var headers_object = new HttpHeaders({
      'Content-Type': 'application/json',
       'Authorization': "Bearer "+t)
    });

        const httpOptions = {
          headers: headers_object
        };


   this.http.post(
                  'http://localhost:8000/api/role/Post', {limit:10}, httpOptions
                 ).subscribe(resp => {
                  this.roles = console.log(resp)
                  }
                );
于 2018-12-04T13:01:39.000 回答
0
import { Injectable } from '@angular/core';
import {
  HttpEvent, HttpInterceptor, HttpHandler, HttpRequest
} from '@angular/common/http';

import { Observable } from 'rxjs';

/** Pass untouched request through to the next request handler. */
@Injectable()
export class NoopInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler):
    Observable<HttpEvent<any>> {
      return next.handle(req);
    }
}

拦截器能够在您的 Header 中添加令牌

通过下面的 URL https://angular.io/guide/http#intercepting-requests-and-responses

于 2020-04-15T15:36:24.327 回答