使用Ionic 2配置Identity Server 4

时间:2017-12-19 03:49:17

标签: javascript angular cordova typescript ionic2

我正在尝试配置Identity Server以使用Ionic 2.我对如何配置重定向网址感到有些困惑。当我在浏览器中进行测试时。

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

我已经创建了一个打字稿提供程序并将其注册到我的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在登录后为您的流程提供令牌和声明。

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不使用网址进行路由,假设我有一个处理存储身份验证令牌的组件AuthenticationPage。 如何配置重定向网址以便导​​航到身份验证页面,以便我可以在浏览器中对此进行测试?

1 个答案:

答案 0 :(得分:1)

<强> TL; DR

我必须做一些事情来使这个工作 我一开始并没有意识到,但我的Redirect 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中设置路由,我需要找到一种与Ionic通信的方法(对于浏览器测试目的,正常的通信将通过cordova完成)。

所以我指出redirct url是url ionic是托管我的应用程序而在构造函数中的app.Component.ts上我添加了代码以尝试获取我的身份验证令牌。

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客户端回调,它将从get params读取令牌

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

注意 Login组件只是一个代表登录着陆页的模式,它只使用登录按钮来初始化弹出窗口。您可以将其挂钩到任何用户驱动的事件以触发登录,但如果您想在不触发弹出窗口阻止程序的情况下支持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); });
}

我确定有更好的重定向到不同的路线,这只是一个快速而肮脏的黑客