使用ng2-adal库的Angular4 azure活动目录身份验证在与哈希位置策略

时间:2018-03-19 16:17:17

标签: angular azure-active-directory

使用ng2-adal库的Angular4 azure活动目录身份验证会从网址中删除id_token。

我引用了以下博客来实现。 https://dotronald.be/add-azure-active-directory-to-an-existing-angular-2-single-page-application/

  1. 已安装ng4-adal

  2. 为ng4-adal创建了一个打字稿配置文件,以设置azure连接详细信息,如下所示,             从' @ angular / core';

    导入{Injectable}
            @Injectable()
           export class AdalConfig {
                  public get getAdalConfig(): any {
                  return {
                      tenant: 'YOUR TENANT NAME',
                      clientId: 'YOUR CLIENT ID',           
                      redirectUri: window.location.origin + '/',
                       postLogoutRedirectUri: window.location.origin + 
                      '/logout'
                };
                }
             }
    
  3. 创建了一个canActivate防护装置,用于在导航前验证角度路线,如下所示,

             import { Injectable } from '@angular/core';
             import { Router, CanActivate,   
             ActivatedRouteSnapshot,RouterStateSnapshot, NavigationExtras } 
             from '@angular/router';
             import {AdalService} from "ng4-adal/core";
    
             @Injectable()
             export class AuthenticationGuard implements CanActivate {
    
             constructor(private _adalService: AdalService, private router: 
             Router) { }
    
             canActivate(route: ActivatedRouteSnapshot, state: 
             RouterStateSnapshot): boolean{
    
                if (this._adalService.userInfo.isAuthenticated) {
                    return true;
                }
                else {
                        this._adalService.login();
                        return false;
                }   }  }
    
  4. 在app.component.ts的构造函数中添加以下代码,以启动ng4-adal服务,如下所示,

                constructor(
                     private _adalService: AdalService,
                     private _adalConfigService: AdalConfig
               )                 
         {this._adalService.init(this._adalConfigService.getAdalConfig);}
    
  5. 为了防止用户每次都必须登录,身份验证令牌存储在浏览器缓存中。这允许我们尝试检索此令牌并继续使用该应用程序,而无需再次重定向到Azure登录页面。

  6. 在app.component.ts的ngOninit中添加以下代码以克服上述问题,如下所示,

                  ngOnInit() {
                     this._adalService.handleWindowCallback();
                     this._adalService.getUser();
                  }
    
    1. 在app-routing.ts文件中设置步骤3中为所需路由创建的防护,如下所示,

              const routes: Routes = [
              { path: '', redirectTo: '/home', pathMatch: 'full', canActivate: 
               [AuthenticationGuard]},
               { path: 'admin-measure', redirectTo: '/#admin-measure'},
               { path: 'home', component: HomeComponent, canActivate: 
                 [AuthenticationGuard] },                 
               { path: 'logout', component: LogoutComponent },
               { path: 'unauthorized', component: UnauthorizedComponent }
             ];
      
    2. 在app.module中注册了服务。

    3. 我进入控制台的错误如下: 错误错误:未捕获(在承诺中):错误:无法匹配任何路由。网址细分:' id_token'

      研究发现的问题:在Angular 2中使用哈希时,重定向存在问题。问题是当身份验证后authResult重新定向时,Angular认为&# 39;一个名为access_token的路由。

      对此有何解决方案?

1 个答案:

答案 0 :(得分:2)

我找到了解决方案。

来自服务提供商的回调是使用#/ id_token,Angular2路由器无法理解。将在控制台中出现错误 - “错误:无法匹配任何路由。网址细分:'id_token'“。为了解决这个问题,我们将添加一个回调路由来消化JWT令牌,然后重定向到我们的目标页面。

一个。按如下所示创建oauth-callback.component,

        import { Component, OnInit } from '@angular/core';
        import { Router } from '@angular/router';
        import {AdalService} from "ng4-adal/core";

        @Component({
                template: '<div>Please wait...</div>'
        })

        export class OAuthCallbackComponent implements OnInit {

        constructor(private router: Router, private _adalService: 
        AdalService) {}

        ngOnInit() {
                if (!this._adalService.userInfo) {
                    this._adalService.login();
                } else {
                    this.router.navigate(['home']);
               }
              }
        }

湾为“id_token”路由创建一个oauth-callback-handler.guard,如下所示,

        import { Injectable } from '@angular/core';
        import { Router, CanActivate, ActivatedRouteSnapshot, 
        RouterStateSnapshot } from '@angular/router';
        import { AdalService } from 'ng4-adal/core';

        @Injectable()
        export class OAuthCallbackHandlerGuard implements CanActivate {

        constructor(private router: Router, private _adalService: 
        AdalService) { }

        canActivate(route: ActivatedRouteSnapshot, state: 
        RouterStateSnapshot): boolean {

            this._adalService.handleWindowCallback();

            if (this._adalService.userInfo.isAuthenticated) {

                var returnUrl = route.queryParams['returnUrl'];
                if (!returnUrl) {
                    this.router.navigate(['home']);
                } else {
                    this.router.navigate([returnUrl], { queryParams: 
                    route.queryParams });
                }
            }
            else {
                    this._adalService.login();
            }

            return false;
            }
         }

℃。在app.module中注册oauth-callback.component和oauth-callback-handler.guard。

d。注册“id_token”的路由由oauth-callback.component和oauth-callback-handler.guard处理,如下所示,

          const routes: Routes = [
         { path: 'id_token', component: OAuthCallbackComponent, canActivate: 
           [OAuthCallbackHandlerGuard] }[AuthenticationGuard]},              
         { path: 'logout', component: LogoutComponent }];       

如需进一步参考,请参阅以下链接

https://blogs.msdn.microsoft.com/premier_developer/2017/04/26/using-adal-with-angular2/