javascript - 使用 Ionic 2 配置 Identity Server 4

标签 javascript angular cordova typescript ionic2

我正在尝试将 Identity Server 配置为与 Ionic 2 一起使用。我对如何配置重定向 URL 感到有点困惑。当我在浏览器中进行测试时。

我正在更新和集成 OIDC Cordova 组件。 旧组件 git hub 在这里: https://github.com/markphillips100/oidc-cordova-demo

我创建了一个 typescript provider 并在我的 app.module.ts 中注册了它

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Rx';
import 'rxjs/add/operator/map';
import { Component } from '@angular/core';
import * as Oidc from "oidc-client";
import { Events } from 'ionic-angular';
import { environment } from "../rules/environments/environment";

export class UserInfo {
    user: Oidc.User = null;
    isAuthenticated: boolean = false;
}

@Injectable()
export class OidcClientProvider   {

    USERINFO_CHANGED_EVENT_NAME: string = ""
    userManager: Oidc.UserManager;
    settings: Oidc.UserManagerSettings;
    userInfo: UserInfo = new UserInfo();
    constructor(public events:Events) {

        this.settings = {
            //authority: "https://localhost:6666",
            authority: environment.identityServerUrl,
            client_id: environment.clientAuthorityId,
            //This doesn't work
            post_logout_redirect_uri: "http://localhost/oidc",
            redirect_uri: "http://localhost/oidc",
            response_type: "id_token token",
            scope: "openid profile",

            automaticSilentRenew: true,
            filterProtocolClaims: true,
            loadUserInfo: true,
            //popupNavigator: new Oidc.CordovaPopupNavigator(),
            //iframeNavigator: new Oidc.CordovaIFrameNavigator(),
        }

        this.initialize();
    }

    userInfoChanged(callback: Function) {
        this.events.subscribe(this.USERINFO_CHANGED_EVENT_NAME, callback);
    }

    signinPopup(args?): Promise<Oidc.User> {
        return this.userManager.signinPopup(args);
    }

    signoutPopup(args?) {
        return this.userManager.signoutPopup(args);
    }

    protected initialize() {

        if (this.settings == null) {
            throw Error('OidcClientProvider required UserMangerSettings for initialization')
        }

        this.userManager = new Oidc.UserManager(this.settings);
        this.registerEvents();
    }

    protected notifyUserInfoChangedEvent() {
        this.events.publish(this.USERINFO_CHANGED_EVENT_NAME);
    }

    protected clearUser() {
        this.userInfo.user = null;
        this.userInfo.isAuthenticated = false;
        this.notifyUserInfoChangedEvent();
    }

    protected addUser(user: Oidc.User) {
        this.userInfo.user = user;
        this.userInfo.isAuthenticated = true;
        this.notifyUserInfoChangedEvent();
    }

    protected registerEvents() {
        this.userManager.events.addUserLoaded(u => {
            this.addUser(u);
        });

        this.userManager.events.addUserUnloaded(() => {
            this.clearUser();
        });

        this.userManager.events.addAccessTokenExpired(() => {
            this.clearUser();
        });

        this.userManager.events.addSilentRenewError(() => {
            this.clearUser();
        });
    }
}

我正在尝试了解如何配置重定向 URL,以便我可以在浏览器中正常进行身份验证。通常你会配置一个重定向 登录后获取 token 和声明的 url。

this.settings = {
        authority: environment.identityServerUrl,
        client_id: environment.clientAuthorityId,
        post_logout_redirect_uri: "http://localhost:8100/oidc",
        redirect_uri: "http://localhost:8100/oidc",
        response_type: "id_token token",
        scope: "openid profile AstootApi",

        automaticSilentRenew: true,
        filterProtocolClaims: true,
        loadUserInfo: true,
        //popupNavigator: new Oidc.CordovaPopupNavigator(),
        //iframeNavigator: new Oidc.CordovaIFrameNavigator(),
    }

Ionic 2 不使用 url 进行路由,假设我有一个组件 AuthenticationPage 来处理存储身份验证 token 。 我如何配置重定向 URL 以便它导航到身份验证页面,以便我可以在浏览器中对此进行测试?

最佳答案

长话短说

我必须做一些事情才能让它正常工作。
起初我没有意识到,但我的重定向 Urls 必须与我的客户端存储在身份服务器中的内容相匹配。

new Client
{
    ClientId = "myApp",
    ClientName = "app client",
    AccessTokenType = AccessTokenType.Jwt,
    RedirectUris = { "http://localhost:8166/" },
    PostLogoutRedirectUris = { "http://localhost:8166/" },
    AllowedCorsOrigins = { "http://localhost:8166" },
    //...
}

因此 Typescript 中的 OIDC 客户端也需要更新。

this.settings = {
    authority: environment.identityServerUrl,
    client_id: environment.clientAuthorityId,
    post_logout_redirect_uri: "http://localhost:8166/",
    redirect_uri: "http://localhost:8166/",
    response_type: "id_token token",
}

另外,因为我不想在 Ionic 中设置路由,所以我需要找出一种 url 与 Ionic 通信的方法(出于浏览器测试目的,正常通信将通过 cordova 完成)。

所以我将重定向 url 指向 ionic 托管我的应用程序的 url,并在构造函数中的 app.Component.ts 上添加了代码以尝试获取我的身份验证 token 。

constructor(
  public platform: Platform,
  public menu: MenuController,
  public oidcClient: OidcClientProvider
)
{
  //Hack: since Ionic only has 1 default address, attempt to verify if this is a call back before calling 
   this.authManager.verifyLoginCallback().then((isSuccessful) => {
     if (!isSuccessful) {
        this.authManager.IsLoggedIn().then((isLoggedIn) => {
          if (isLoggedIn) {
              return;
          }

          this.nav.setRoot(LoginComponent)
        });
     }
  });
}

编辑 验证登录回调应该只是 oidc 客户端回调,它将从获取参数中读取 token

verifyLoginCallback(): Promise<boolean> {
    return this.oidcClient.userManager.signinPopupCallback()
        .then(user => {
            return this.loginSuccess(user).
                then(() => true,
                    () => false);
    }, err => { console.log(err); return false; });
} 

注意 登录组件只是一个代表登录登陆页面的模式,它只使用一个登录按钮来初始化弹出窗口。您可以将其挂接到任何用户驱动的事件中以触发登录,但是如果您希望在不触发弹出窗口阻止程序的情况下支持 Web,则必须使用用户驱动的事件

<ion-footer no-shadow>
  <ion-toolbar no-shadow position="bottom">
    <button ion-button block (click)="login()">Login</button>
  </ion-toolbar>
</ion-footer>

login(): Promise<any> {
    return this.oidcClient.signinPopup().then((user) => {
        this.events.publish(environment.events.loginSuccess);
    }).catch((e) => { console.log(e); });
}

我确信重定向到不同的路由会更好,这只是一个快速而肮脏的 hack

关于javascript - 使用 Ionic 2 配置 Identity Server 4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47879777/

相关文章:

javascript - 跟踪新插入的文档并执行特定事件

angularjs - Angular2 TemplateRef 选择器

JQuery Mobile 百分比高度问题

javascript - 由于重定向 URI 无效,Keycloak token 请求被拒绝

javascript - 列出来自 HTML XPath 的项目

html - 正在准备产品列表但 UI 不正确

javascript - 有条件地合并映射

javascript - 在 javascript 中使用 API 而不使用 Node.js

google-chrome - Cordova 3 + 波纹

javascript - 过滤对象数组