gpt4 book ai didi

与哈希位置策略一起使用时,使用 ng2-adal 库的 Angular4 azure Active Directory 身份验证失败

转载 作者:行者123 更新时间:2023-12-02 03:38:34 25 4
gpt4 key购买 nike

使用 ng2-adal 库的 Angular4 azure Active Directory 身份验证会从 URL 中删除 id_token。

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

  1. 已安装 ng4-adal

  2. 为 ng4-adal 创建了一个 typescript 配置文件来设置 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 防护,在导航之前验证 Angular 路线,如下所示,

             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. 为了防止用户每次都必须重新登录,身份验证 token 将存储在浏览器缓存中。这使我们能够尝试检索此 token 并继续使用应用程序,而无需再次重定向到 Azure 登录页面。

在app.component.ts的ngOninit中添加以下代码来解决上述问题,如下所示,

              ngOnInit() {
this._adalService.handleWindowCallback();
this._adalService.getUser();
}
  • 在 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 }
    ];
  • 在app.module中注册服务。

  • 我在控制台中遇到的错误如下,错误错误:未捕获( promise ):错误:无法匹配任何路由。 URL 段:'id_token'

    研究发现的问题:在 Angular 2 中使用哈希值时存在重定向问题。问题在于,当身份验证后 authResult 返回到重定向时,Angular 认为这是一个名为 access_token 的路由。

    有什么解决办法吗?

    最佳答案

    我找到了解决方案。

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

    a.创建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']);
    }
    }
    }

    b.为“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;
    }
    }

    c.在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/

    关于与哈希位置策略一起使用时,使用 ng2-adal 库的 Angular4 azure Active Directory 身份验证失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49367651/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com