授权令牌在Angular中的响应中被发送为null

时间:2018-06-12 16:28:51

标签: javascript angular angular4-httpclient

我正在尝试使用我的企业应用程序和Angular中提供的REST API。我想要实现的是从我的企业应用程序中获取一些数据。为此,我必须做两件事:

1-通过Angular登录我的企业应用程序。为此,企业应用程序已经提供了自定义身份验证REST API。我也在消费。生成一个身份验证令牌,我将其保存在localStorage中。

2-发送身份验证后,向企业应用程序发送GET请求以获取数据。这是我面临问题的地方。我无法在GET请求中传递身份验证令牌。在Chrome开发工具的“应用程序”选项卡下检查相同内容时,我可以在“请求标题”部分看到授权值为空。以下是相同的屏幕截图:

enter image description here

以下是我开发的代码:

1 - 身份验证服务(auth.service.ts)

     import { Injectable } from '@angular/core';
     import { HttpClient, HttpHeaders } from '@angular/common/http';
     import{Http} from '@angular/http'
     import { Observable } from 'rxjs';
     import { map } from 'rxjs/operators';
     import { URLSearchParams,Response } from '@angular/http'

     @Injectable()
     export class AuthenticationService {
     constructor(private http: Http) { }
     username:string = 'Admin';
     password:string='livelink';  
     token:any; 
     login() 
     {

    let urlSearchParams = new URLSearchParams();
    urlSearchParams.append('Username', this.username);
    urlSearchParams.append('Password', this.password);
     this.http.post('http://localhost/otcs/cs.exe/api/v1/auth',urlSearchParams)
        .subscribe((res:Response) => 
        {
            // login successful if there's a jwt token in the response
            if (res) {
                const data = res.json();
                ;
                this.token = data;
                console.log(data);
                // store username and jwt token in local storage to keep user logged in between page refreshes
                localStorage.setItem('currentUser', JSON.stringify({  ticket: data }));

            }
        });

        console.log("INSIDE LOGIN this.token  = "+this.token)//done for debugging, returning undefined
}

public getToken()
 {

    console.log("GET TOKEN VALUE "+ localStorage.getItem('ticket'))//done for debugging, returning undefined
    return localStorage.getItem('ticket');
     }

  }

2 - 令牌拦截器(token.interceptor.ts)

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

     @Injectable()
     export class TokenInterceptor implements HttpInterceptor {
     constructor(public auth: AuthenticationService) {}
     intercept(request: HttpRequest<any>, next: HttpHandler): 
     Observable<HttpEvent<any>> {

     request = request.clone({
     setHeaders: {
     Authorization: `Bearer ${this.auth.getToken()}`
     }
   });

        return next.handle(request);
     }
   }

3 - 应用程序组件(app.component.ts)

 import { Component } from '@angular/core';
 import { AuthenticationService } from './auth.service';
 import{Http} from '@angular/http'
 import { HttpClient } from '@angular/common/http'
 @Component({
 selector: 'app-root',
 templateUrl: './app.component.html',
 styleUrls: ['./app.component.css']
 })
  export class AppComponent 
  {

 constructor(private authenticationService: AuthenticationService, private 
 http:HttpClient)
   {
      this.authenticationService.login();
      this.ping() ;

    }

     public ping() {
    this.http.get('http://localhost/otcs/cs.exe/api/v1/nodes/16236/output')
     .subscribe(
  data => console.log(data),
  err => console.log(err)
        );
      }
    }

4- App Module(app.module.ts)

     import { BrowserModule } from '@angular/platform-browser';
     import { NgModule } from '@angular/core';
     import { HttpClientModule, HTTP_INTERCEPTORS } from 
     '@angular/common/http';
     import { AppComponent } from './app.component';
     import { AuthenticationService } from './auth.service';
     import { HttpModule } from '@angular/http';
     import { TokenInterceptor } from './token.interceptor';

     @NgModule({
     declarations:[AppComponent],
     imports: [
            BrowserModule,
            HttpClientModule,
            HttpModule
           ],

    providers: [AuthenticationService,
   {
      provide: HTTP_INTERCEPTORS,
      useClass: TokenInterceptor,
       multi: true
}],
        bootstrap: [AppComponent]
     })
        export class AppModule { }

在运行上述项目时,下面是Console中显示的输出:

enter image description here

我无法理解为什么我的令牌没有通过GET请求传递。

2 个答案:

答案 0 :(得分:1)

您正在使用此行保存令牌

var date = "2018-06-11T14:12:43";
var LastModifiedDate = {
        date: date,
        tzId: "America/Mexico_City",
        tzCode: "PDT" 
}
       console.log("Mexico_City-> normal ->" + utils.formatDate(utils.convertPlatformDateToMillis(LastModifiedDate)));

        LastModifiedDate = {
             date: date,
             tzId: "America/New_York",
             tzCode: "PDT"
         }
        console.log("New_York-> 1 hr ->" + utils.formatDate(utils.convertPlatformDateToMillis(LastModifiedDate)));
        LastModifiedDate = {
            date: date,
            tzId: "America/Los_Angeles",
            tzCode: "PDT"
        }
        console.log("Los_Angeles-> 2hr ->" + utils.formatDate(utils.convertPlatformDateToMillis(LastModifiedDate)));


class Utils {

        convertPlatformDateToMillis(pltDateObject) {
           return momentTimeZone.tz(pltDateObject.date, pltDateObject.tzId);
        }

        formatDate(dateInMillis) {
           return moment(new Date(dateInMillis)).format('MMM DD, YYYY HH:mm A');
        }
}

但是,您的功能localStorage.setItem('currentUser', JSON.stringify({ ticket: data })); getToken()出错了。我认为你的功能应该如下:

localStorage

希望有所帮助

答案 1 :(得分:0)

在getToken中检索令牌时,请使用密钥“currrentUser”而不是“ticket”

public getToken() {
    const currentUser = JSON.parse(localStorage.getItem('currentUser'));
    if (currentUser) {
    return currentUser.ticket;
    } else return null;
}

最好将密钥存储在某个配置中,以便可以随处访问,因此当前密钥不会丢失。