0

我正在尝试使用身份服务器 4 为我的反应应用程序进行身份验证。我遵循了这个文档。我正在使用身份服务器的隐式流程,因此 onload 应用程序将转到身份服务器的登录页面。提供正确的用户名和密码后,它将验证并提供令牌。一切都按预期工作,但我无法将我的反应应用程序重定向到仪表板页面。我很新反应请帮助我。

  // Copyright (c) Microsoft. All rights reserved.

import Config from 'app.config';
import AuthenticationContext from 'adal-angular/dist/adal.min.js'
import { Observable } from 'rxjs';
import { HttpClient } from 'utilities/httpClient';
import { toUserModel, authDisabledUser } from './models';
import Oidc, { User } from 'oidc-client';

const ENDPOINT = Config.serviceUrls.auth;

export class AuthService {

  //static authContext; // Created on AuthService.initialize()
  //static authEnabled = true;
  //static aadInstance = '';
  //static appId = '00000000-0000-0000-0000-000000000000';
  //static tenantId = '00000000-0000-0000-0000-000000000000';
  //static clientId = '00000000-0000-0000-0000-000000000000';

  static initialize() {
    if (typeof global.DeploymentConfig === 'undefined') {
      alert('The dashboard configuration is missing.\n\nVerify the content of webui-config.js.');
      throw new Error('The global configuration is missing. Verify the content of webui-config.js.');
    }

    if (typeof global.DeploymentConfig.authEnabled !== 'undefined') {
      AuthService.authEnabled = global.DeploymentConfig.authEnabled;
      if (!AuthService.authEnabled) {
        console.warn('Auth is disabled! (see webui-config.js)');
      }
    }

    //AuthService.tenantId = global.DeploymentConfig.aad.tenant;
    //AuthService.clientId = global.DeploymentConfig.aad.appId;
    //AuthService.appId = global.DeploymentConfig.aad.appId;
    //AuthService.aadInstance = global.DeploymentConfig.aad.instance;

    if (AuthService.aadInstance && AuthService.aadInstance.endsWith('{0}')) {
      AuthService.aadInstance = AuthService.aadInstance.substr(0, AuthService.aadInstance.length - 3);
    }

    // TODO: support multiple types/providers
    if (AuthService.isEnabled() && global.DeploymentConfig.authType !== 'aad') {
      throw new Error(`Unknown auth type: ${global.DeploymentConfig.authType}`);
    }

    //AuthService.authContext = new AuthenticationContext({
     // instance: AuthService.aadInstance,
      //tenant: AuthService.tenantId,
      //clientId: AuthService.clientId,
      //redirectUri: "http://localhost:3000/dashboard",
      //expireOffsetSeconds: 300, // default is 120
      //postLogoutRedirectUri: window.location.protocol
    //});
  }

  static isDisabled() {
    return AuthService.authEnabled === false;
  }

  static isEnabled() {
    return !AuthService.isDisabled();
  }

  static onLoad(successCallback) {
    debugger;
    AuthService.initialize();
    if (AuthService.isDisabled()) {
      console.debug('Skipping Auth onLoad because Auth is disabled');
      if (successCallback) successCallback();
      return;
    };
    var config = {
      authority: "http://localhost:5000",
      client_id: "mvc",
      redirect_uri: "http://localhost:3000/dashboard",
      response_type: "id_token token",

      post_logout_redirect_uri : "http://localhost:5003/index.html",
  };
  var mgr = new Oidc.UserManager(config);
  mgr.signinRedirect();


  mgr.getUser().then(function(user){
    if(user){
      console.log("User logged in", user.profile);
    }
    else {
      console.log("User not logged in");
  }
  }); 
  mgr.events.addUserLoaded(function(userLoaded){
    mgr.User=userLoaded;
  })
  mgr.events.addSilentRenewError(function (error){
    console.log('the user has signrd out');
    mgr._user=null;
  })


  //mgr.login();

  //mgr.renewToken();


    // Note: "window.location.hash" is the anchor part attached by
    //       the Identity Provider when redirecting the user after
    //       a successful authentication.
    // if (AuthService.authContext.isCallback(window.location.hash)) {
    //   console.debug('Handling Auth Window callback');
    //   // Handle redirect after authentication
    //   AuthService.authContext.handleWindowCallback();
    //   const error = AuthService.authContext.getLoginError();
    //   if (error) {
    //     throw new Error(`Authentication Error: ${error}`);
    //   }
    // } else {
    //   AuthService.getUserName(user => {
    //     if (user) {
    //       console.log(`Signed in as ${user.Name} with ${user.Email}`);
    //       if (successCallback) successCallback();
    //     } else {
    //       console.log('The user is not signed in');
    //       AuthService.authContext.login();
    //     }
    //   });
    // }
  }

  static getUserName(callback) {
    if (AuthService.isDisabled()) return;

    if (AuthService.authContext.getCachedUser()) {
      Observable.of({ Name:AuthService.authContext._user.userName, Email: AuthService.authContext._user.userName })
        .map(data => data ? { Name: data.Name, Email: data.Email } : null)
        .subscribe(callback);
    } else {
      console.log('The user is not signed in');
      AuthService.authContext.login();
    }
  }

  /** Returns a the current user */
  static getCurrentUser() {
    if (AuthService.isDisabled()) {
      return Observable.of(authDisabledUser);
    }
    return HttpClient.get(`${ENDPOINT}users/current`)
      .map(toUserModel);
  }

  static logout() {
    if (AuthService.isDisabled()) return;

    AuthService.authContext.logOut();
    AuthService.authContext.clearCache();
  }

  /**
   * Acquires token from the cache if it is not expired.
   * Otherwise sends request to AAD to obtain a new token.
   */
  static getAccessToken() {
    debugger;
    if (AuthService.isDisabled()) {
      return Observable.of('client-auth-disabled');
    }

    return Observable.create(observer => {
      return AuthService.authContext.acquireToken(
        AuthService.appId,
        (error, accessToken) => {
          if (error) {
            console.log(`Authentication Error: ${error}`);
            observer.error(error);
          }
          else observer.next(accessToken);
          observer.complete();
        }
      );
    });
  }
}

我面临的问题是在身份验证后我的应用程序正在进行某种循环意味着应用程序的 url 正在更改为身份服务器和本地应用程序 url。您可以看到我的应用程序之前使用的是 adal 的 AuthenticationContext。我想更改为 oidc身份服务器 4.

4

1 回答 1

0

我看到您提到重定向 uri 作为仪表板?'redirect_uri: " http://localhost:3000/dashboard '。所以从身份服务器,用户将被重定向到这里对吗?你能告诉我们你在仪表板页面上做什么吗?

通常,在身份服务器实现中,重定向 Uri 需要是一个简单的页面,其职责只需从 URL 访问令牌并重定向到所需的页面(比如从这里重定向到仪表板)

我知道我给您的更多是理论上的答案,但是看到您对重定向 URL 的实现可以帮助您获得更好的答案。

于 2019-06-14T13:46:18.560 回答