Angular 6 - 为什么生产版本中缺少 Bearer Token? (在开发构建中工作正常)

Angular 6 - Why is Bearer Token missing in production build? (works fine in dev build)

我正在使用 Angular 6 和一个 HTTP 拦截器,配置为将持有者令牌应用于传出请求。

在产品构建中,我通过在应用后将 header 转储到控制台来验证正在应用 header。

我不知道为什么他们被排除在 http 请求之外。

我的 environment 文件没有差异。

我还应该看什么?

我该怎么做才能解决这个问题?

起初我以为这是我的本地环境和暂存环境之间的问题,但后来我在本地尝试 运行 ng serve --prod 并看到相同的结果。

综上所述,除了一个是生产版本而一个是开发版本之外,其他一切都是相同的。

jwt-interceptor:

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

@Injectable()
export class JwtInterceptor implements HttpInterceptor {
    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

        // add authorization header with jwt token if available
        let currentUser = JSON.parse(localStorage.getItem('currentUser'));

        if (currentUser && currentUser.token) {
            request = request.clone({
                setHeaders: {
                    Authorization: `Bearer ${currentUser.token}`
                }
            });
            console.log('headers:', request.headers); // <---- I can see headers in console output
        }

        return next.handle(request);
    }
}

这是我在控制台中看到的内容:

app.module.ts

import { HttpClientModule, HttpClient, HttpInterceptor } from '@angular/common/http';
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { PortalModule } from '@angular/cdk/portal';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';

import { JwtInterceptor } from './jwt-interceptor';
import { ENV } from '../environments/environment';
import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';
... 
import { myApiService } from './services/my-api.service';
import { myModalComponent } from './_components/my-modal/my-modal.component';
import { myModalService } from './services/my-modal.service';

import { AngularLaravelEchoModule, PusherEchoConfig, EchoInterceptor } from 'angular-laravel-echo/angular-laravel-echo';

export const echoConfig: PusherEchoConfig = {
    userModel: 'App.User',
    notificationNamespace: 'App\Notifications',
    options: {
        broadcaster: 'pusher',
        key: ENV.pusherConfig.key,
        cluster: ENV.pusherConfig.cluster,
        host: ENV.apiRoot,
        authEndpoint: ENV.apiRoot + '/broadcasting/auth',
    }
};

@NgModule({
    declarations: [
        AppComponent,
        ...
    ],
    imports: [
        BrowserModule,
        HttpClientModule,
        BrowserModule,
        AppRoutingModule,
        FormsModule,
        ReactiveFormsModule,
        PortalModule,
        AngularLaravelEchoModule.forRoot(echoConfig)
    ],
    providers: [
        myApiService,
        myModalService,
        {
            provide: HTTP_INTERCEPTORS,
            useClass: JwtInterceptor,
            multi: true,
        },
        {
            provide: HTTP_INTERCEPTORS,
            useClass: EchoInterceptor,
            multi: true
        }
    ],
    bootstrap: [AppComponent],
    entryComponents: [ 
        myModalComponent
    ]
})

export class AppModule {
}

我在服务器完全忽略 Authorization header 的生产环境中遇到了几乎类似的问题。 Angular 6 正确发送 Authorization header 但服务器完全剥离(由于大多数生产服务器、共享主机安全设置)。我知道这可能不是您要找的答案。但是,我只是想给你一个线索。

所以,最后为了让这个工作正常,我不得不使用不同的 header 参数,例如 Php-Auth-Digest,就像这样。

request = request.clone({
    setHeaders: {
      "Php-Auth-Digest": `Bearer ${currentUser.token}`,
    }
  });

解决方法是尝试更改 header 参数名称。

干杯!

您可以尝试在实际的 api 调用中设置 header 吗?例如:

put(path: string, body: Object = {}): Observable<any> {
return this.http.put(`${environment.api_url}${path}`, body, { headers: 
     this.setHeaders() })
     .map((res: Response) => {
        return res;
     });
}

private setHeaders(): HttpHeaders {
    const headersConfig = {
      'Content-Type': 'application/json',
      'Accept': 'application/json',
      'Authorization': 'Bearer ' + this.oauthService.getAccessToken()
    };
    return new HttpHeaders(headersConfig);
}

拦截器将只有

request.clone() 

您可以尝试在 request.clone() 方法中手动克隆 headers。这对我有用:

export class HttpHeaderInterceptor implements HttpInterceptor {
  // ...
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    // ...
    const clonedRequest = req.clone({ 
      headers: req.headers.set('Authorization', 'Bearer ' + currentUser.token) 
    });
    return next.handle(clonedRequest).pipe(
      catchError(err => { /* Error handling here */ })
    );
  }
}

希望对您有所帮助:-)

试试这个

if (currentUser && currentUser.token) {
        request = request.clone({
            setHeaders: {
                Authorization: `Bearer ${currentUser.token}`
            }
        });
        console.log('headers:', request.headers); // <---- I can see headers in console output
    }
if (typeof $ != 'undefined') {
    $.ajaxSetup({
      beforeSend: function (xhr: any) {
        xhr.setRequestHeader('Authorization', 'Bearer ' + currentUser.token);
      }
    });
  }
    return next.handle(request);

我在 StackBlitz 中编写了这个应用程序,当我使用 ng serve --prod 在本地 运行 它工作正常。

https://stackblitz.com/edit/angular-yzckos

下载并 运行 查看您的网络选项卡中是否仍然显示 undefined。如果您能看到 header 被正确发送,那么您的代码中肯定有一些有趣的东西。

试试下面的方法:

1- 尝试 运行ning `ng serve --port=aDifferentPort // 比如 2098

也许那个端口上有东西 运行ning 并发送 auth header

2- 尝试使用 AOT false,想不出为什么会导致任何问题

3- 确保您的浏览器没有任何覆盖 Auth 的扩展程序 header 或尝试其他浏览器

4- 关闭你的其他 HTTP 拦截器,也许其中一个做了一些意想不到的事情

5- 把header名字从Authorizaion改成MyAuthorization,看看是不是还是undefined,如果不是,那就是被某个东西覆盖,检查你的 package.json 并确保你没有 运行 在生产服务器上安装任何其他东西。

6- 完全关闭 JwtInterceptor 并尝试将授权 header 附加到您的 HTTP 请求,看看您是否仍然获得 undefined.

7- 如果 none 有帮助,您确实需要向我们发送更多代码:)

我对此有一个想法 - 但我不确定它是否可行,请检查

HttpHeaders 是可变的,如果你添加任何 header 它会更新现有的并附加值 - 所以这导致我在附加 header 时遇到问题所以遵循下面的方法:

private getHeaders(): HttpHeaders {
    let headers = new HttpHeaders();
    headers = headers.append("Content-Type", "application/json");
    return headers;
  }

从那以后,我附加了新的 headers 并将 object 分配给原始 object 并返回了 object - 这对我来说在两个产品中都很好和开发构建

但在您的情况下,您可以在 HttpInterceptor 中使用上述相同的方法,或者尝试将 setheaders 更改为 headers,如下面的示例

if (currentUser && currentUser.token) {
            request = request.clone({
                headers: new HttpHeaders({
                    Authorization: `Bearer ${currentUser.token}`
                })
            });
            console.log('headers:', request.headers); 
        }

我相信这会解决您在两个版本中的问题 - 如果它不起作用请尝试告诉我 - 希望它能起作用谢谢 - 编码愉快!!