授权标记在Angular的响应中作为空发送 [英] Authorization Token getting sent as null in the Response in Angular
问题描述
我正在尝试使用我的企业应用程序和Angular中提供的REST API.我想要实现的是从企业应用程序中获取一些数据.为此,我必须做两件事:
I am trying to work with REST API's provided within my Enterprise Application and Angular. What I am trying to achieve is to fetch some data from my Enterprise Application. For this I have to do two things:
1-通过Angular登录到我的企业应用程序.为此,企业应用程序已经提供了自定义身份验证REST API.我正在消费相同.生成一个身份验证令牌,我将其保存在localStorage中.
1- Login to my Enterprise Application via Angular. For doing so, there's already a custom authentication REST API provided by the Enterprise Application. I am consuming the same. An authentication token is generated which I am saving within localStorage.
2-发生身份验证后,向企业应用程序发送GET请求以获取数据.这是我面临的问题.我无法在GET请求中传递身份验证令牌.在"Chrome开发者工具"的应用程序"选项卡下进行检查时,我可以在请求标头"部分下看到授权值为空.下面是相同的屏幕截图:
2- Send a GET request to the Enterprise Application to fetch data after Authentication happened. This is where I am facing issues. I am unable to pass the authentication token within the GET Request. On Checking the same under "Application" Tab of Chrome Dev Tools, I Could see under "Request Headers" Section that Authorization value is null. Below is the screenshot of the same:
下面是我开发的代码:
1-身份验证服务(auth.service.ts)
1 - Authentication Service (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)
2 - Token Interceptor (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)
3 - App Component (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.ts)
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 { }
在运行上述项目时,以下是控制台中显示的输出:
On running the above project, below is the output displayed in Console:
我无法理解为什么我的令牌没有随GET请求一起传递.
I am unable to understand as to why is my token not getting passed with the GET Request.
推荐答案
您正在使用此行保存令牌
You are saving the token using this line
localStorage.setItem('currentUser', JSON.stringify({ ticket: data }));
但是,您的函数 getToken()
从 localStorage
弄错了.我认为您的函数应如下所示:
But, your function getToken()
is getting it wrong from localStorage
. I think your function should look like:
public getToken() {
const currentUser = JSON.parse(localStorage.getItem('currentUser') || '{}');
console.log("GET TOKEN VALUE ", currentUser.ticket))//done for debugging
return currentUser.ticket;
}
希望有帮助
这篇关于授权标记在Angular的响应中作为空发送的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!