How to use RenewToken method of MSADAL in Angular 6+?

后端 未结 2 571
暗喜
暗喜 2021-01-07 07:42

I am using MS Adal NPM package (https://www.npmjs.com/package/microsoft-adal-angular6) for Angular 6 to get the user Authenticated with Azure AD. I am using Implicit Flow t

2条回答
  •  一整个雨季
    2021-01-07 07:52

    Use an http wrapper service/interceptor to intercept all http requests and set the token subscribed by the this._adalService.acquireToken method and set in the Authorization header of each http request as follows,

          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 {
    
        return this._adalService
            .acquireToken(this._appDataService.adalConfig.clientId)
            .flatMap((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);
                }
            });
          }
       }
    

    The token returned by the this._adalService.acquireToken method will be always the current active token. Also set the below configurations for 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
          };
       }
     }
    

    Hope this helps...

提交回复
热议问题