如何在 Angular 6+ 中使用 MSADAL 的 RenewToken 方法?
How to use RenewToken method of MSADAL in Angular 6+?
我正在使用 Angular 6 的 MS Adal NPM 包 (https://www.npmjs.com/package/microsoft-adal-angular6) 来让用户通过 Azure AD 进行身份验证。我正在使用隐式流来获取访问令牌。我已经能够成功获取访问令牌,在构造函数中使用以下代码。
if (!this.adalSvc.userInfo) {
this.adalSvc.login();
} else {
const token = this.adalSvc.acquireToken('https://graph.microsoft.com').subscribe((token: string) => {
localStorage.setItem('authtoken', token);
});
}
在隐式流程中,仅返回访问令牌,并且此访问令牌的有效期为一小时。我需要刷新这个令牌。 microsoft-adal-angular6 包的文档页面提到了方法 RenewToken。但是,我看不到此方法的任何详细信息,也无法获得任何可以向我展示如何使用此方法的示例代码。谁能帮我解决这个问题?
我在网站 https://docs.microsoft.com/en-us/microsoftteams/platform/concepts/authentication/auth-silent-aad 上找到了关于 ADAL 如何创建隐藏的 IFrame 的很好的解释。
The ADAL.js library creates a hidden iframe for OAuth 2.0 implicit
grant flow, but it specifies prompt=none so that Azure AD never shows
the login page. If user interaction is required because the user needs
to log in or grant access to the application, Azure AD will
immediately return an error that ADAL.js then reports to your app. At
this point your app can show a login button if needed.
解决方案非常简单。我只需要写一行代码
this.adalsvc.RenewToken('https://graph.microsoft.com');
这里唯一需要注意的是,由于"adalsvc"变量是在构造函数中通过注入创建的,因此需要创建一个adalsvc的副本,并将其存储为MsAdalAngular6Service类型的全局变量,然后在此对象上执行 RenewToken 方法。这是我编写的示例代码。我在单击按钮时执行 RenewToken,但在实际场景中,它可以以 non-interactical 方式执行。
import { Component } from '@angular/core';
import { MsAdalAngular6Service } from 'microsoft-adal-angular6';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app';
newadalsvc: MsAdalAngular6Service;
onClickMe() {
this.getNewToken();
}
constructor(private adalSvc: MsAdalAngular6Service) {
if (!this.adalSvc.userInfo) {
this.adalSvc.login();
} else {
const token = this.adalSvc.acquireToken('https://graph.microsoft.com').subscribe((token: string) => {
this.newadalsvc = adalSvc;
alert(token);
console.log(token);
localStorage.setItem('authtoken', token);
});
}
}
getNewToken()
{
this.newadalsvc.RenewToken('https://graph.microsoft.com');
//Without calling acquireToken the new token will not be set in the "Local Storage"
this.newadalsvc.acquireToken('https://graph.microsoft.com').subscribe((token) => {
console.log('Token >>>>>>>>>>>>>>', token);
});
}
}
使用http wrapper service/interceptor拦截所有http请求并设置this._adalService.acquireToken方法订阅的token并在每个请求的Authorization header中设置http请求如下,
import {Component, Injectable } from '@angular/core';
import { Headers, Http, Response, RequestOptions, XHRBackend, Request,
RequestOptionsArgs } from '@angular/http';
import { Router, ActivatedRoute } from '@angular/router';
import { Observable } from 'rxjs/Rx';
import { AdalService } from 'ng4-adal/core';
export class HttpService extends Http {
constructor(backend: XHRBackend, options: RequestOptions,private
_adalService:AdalService) {
super(backend, options);
}
request(url: string | Request, options: RequestOptionsArgs): Observable<Response> {
return this._adalService
.acquireToken(this._appDataService.adalConfig.clientId)
.flatMap<string, Response>((token) => {
var access_token = token ||
this._adalService.getCachedToken(this._appDataService.adalConfig.clientId);
if (typeof (url) == "string") {
if (!options) {
options = {};
options.headers = new Headers();
}
options.headers.append('Authorization', 'Bearer ' + access_token);
return super.request(url, options);
}
else {
url.headers.append('Authorization', 'Bearer ' + access_token);
return super.request(url, options);
}
});
}
}
this._adalService.acquireToken 方法返回的令牌将始终是当前活动令牌。还要为 ADAL 设置以下配置,
import {Injectable} from '@angular/core';
@Injectable()
export class AdalConfig {
constructor() {
}
public get getAdalConfig(): any {
return {
tenant: "tenantName",
clientId: "clientId",
redirectUri: window.location.origin + '/',
postLogoutRedirectUri: window.location.origin + '/' + "#/logout",
extraQueryParameter: "domain_hint=someDomain.com",
cacheLocation: "localStorage",
expireOffsetSeconds: "1200" //Worked for me to avoid token returned as null
};
}
}
希望这对您有所帮助...
我正在使用 Angular 6 的 MS Adal NPM 包 (https://www.npmjs.com/package/microsoft-adal-angular6) 来让用户通过 Azure AD 进行身份验证。我正在使用隐式流来获取访问令牌。我已经能够成功获取访问令牌,在构造函数中使用以下代码。
if (!this.adalSvc.userInfo) {
this.adalSvc.login();
} else {
const token = this.adalSvc.acquireToken('https://graph.microsoft.com').subscribe((token: string) => {
localStorage.setItem('authtoken', token);
});
}
在隐式流程中,仅返回访问令牌,并且此访问令牌的有效期为一小时。我需要刷新这个令牌。 microsoft-adal-angular6 包的文档页面提到了方法 RenewToken。但是,我看不到此方法的任何详细信息,也无法获得任何可以向我展示如何使用此方法的示例代码。谁能帮我解决这个问题?
我在网站 https://docs.microsoft.com/en-us/microsoftteams/platform/concepts/authentication/auth-silent-aad 上找到了关于 ADAL 如何创建隐藏的 IFrame 的很好的解释。
The ADAL.js library creates a hidden iframe for OAuth 2.0 implicit grant flow, but it specifies prompt=none so that Azure AD never shows the login page. If user interaction is required because the user needs to log in or grant access to the application, Azure AD will immediately return an error that ADAL.js then reports to your app. At this point your app can show a login button if needed.
解决方案非常简单。我只需要写一行代码
this.adalsvc.RenewToken('https://graph.microsoft.com');
这里唯一需要注意的是,由于"adalsvc"变量是在构造函数中通过注入创建的,因此需要创建一个adalsvc的副本,并将其存储为MsAdalAngular6Service类型的全局变量,然后在此对象上执行 RenewToken 方法。这是我编写的示例代码。我在单击按钮时执行 RenewToken,但在实际场景中,它可以以 non-interactical 方式执行。
import { Component } from '@angular/core';
import { MsAdalAngular6Service } from 'microsoft-adal-angular6';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app';
newadalsvc: MsAdalAngular6Service;
onClickMe() {
this.getNewToken();
}
constructor(private adalSvc: MsAdalAngular6Service) {
if (!this.adalSvc.userInfo) {
this.adalSvc.login();
} else {
const token = this.adalSvc.acquireToken('https://graph.microsoft.com').subscribe((token: string) => {
this.newadalsvc = adalSvc;
alert(token);
console.log(token);
localStorage.setItem('authtoken', token);
});
}
}
getNewToken()
{
this.newadalsvc.RenewToken('https://graph.microsoft.com');
//Without calling acquireToken the new token will not be set in the "Local Storage"
this.newadalsvc.acquireToken('https://graph.microsoft.com').subscribe((token) => {
console.log('Token >>>>>>>>>>>>>>', token);
});
}
}
使用http wrapper service/interceptor拦截所有http请求并设置this._adalService.acquireToken方法订阅的token并在每个请求的Authorization header中设置http请求如下,
import {Component, Injectable } from '@angular/core';
import { Headers, Http, Response, RequestOptions, XHRBackend, Request,
RequestOptionsArgs } from '@angular/http';
import { Router, ActivatedRoute } from '@angular/router';
import { Observable } from 'rxjs/Rx';
import { AdalService } from 'ng4-adal/core';
export class HttpService extends Http {
constructor(backend: XHRBackend, options: RequestOptions,private
_adalService:AdalService) {
super(backend, options);
}
request(url: string | Request, options: RequestOptionsArgs): Observable<Response> {
return this._adalService
.acquireToken(this._appDataService.adalConfig.clientId)
.flatMap<string, Response>((token) => {
var access_token = token ||
this._adalService.getCachedToken(this._appDataService.adalConfig.clientId);
if (typeof (url) == "string") {
if (!options) {
options = {};
options.headers = new Headers();
}
options.headers.append('Authorization', 'Bearer ' + access_token);
return super.request(url, options);
}
else {
url.headers.append('Authorization', 'Bearer ' + access_token);
return super.request(url, options);
}
});
}
}
this._adalService.acquireToken 方法返回的令牌将始终是当前活动令牌。还要为 ADAL 设置以下配置,
import {Injectable} from '@angular/core';
@Injectable()
export class AdalConfig {
constructor() {
}
public get getAdalConfig(): any {
return {
tenant: "tenantName",
clientId: "clientId",
redirectUri: window.location.origin + '/',
postLogoutRedirectUri: window.location.origin + '/' + "#/logout",
extraQueryParameter: "domain_hint=someDomain.com",
cacheLocation: "localStorage",
expireOffsetSeconds: "1200" //Worked for me to avoid token returned as null
};
}
}
希望这对您有所帮助...