如何在单页应用中实现授权码流?

问题描述

您好,我正在为我的客户端 SPA 应用程序和 .Net 核心后端 API 应用程序实施身份验证和授权。我在 azure 广告中为 SPA 和 API 应用程序注册了两个应用程序。我可以使用 Postman 获取令牌,如下所示。

postman to get token

我能够获取包含所需详细信息的令牌。现在我在前端反应应用程序中尝试同样的事情。我正在使用 react adal 库。

我有以下代码获取令牌

   /* istanbul ignore file */
import { adalGetToken,AuthenticationContext,UserInfo } from 'react-adal';
import { UserProfile } from '../common/models/userProfile';
class AdalContext {
    private authContext: AuthenticationContext | any;
    private appId: string = '';
    private endpoints: any;

    public initializeAdal(adalConfig: any) {
        debugger;
        this.authContext = new AuthenticationContext(adalConfig);
        this.appId = adalConfig.clientId;
        this.endpoints = adalConfig.endpoints.api;
    }
    get AuthContext() {
        return this.authContext;
    }

    public getToken(): Promise<string | void | null> {
        debugger;
        return adalGetToken(this.authContext,this.appId,this.endpoints).catch((error: any) => {
            if (error.msg === 'login_required' || error.msg === 'interaction_required') {
                this.authContext.login();
            }
        });
    }

    public acquiretoken(callback: Function) {
        let user = this.AuthContext.getCachedUser();
        if (user) {
            this.authContext.config.extraQueryParameter = 'login_hint=' + (user.profile.upn || user.userName);
        }

        adalGetToken(this.authContext,this.endpoints).then(
            (token) => {
                callback(token);
            },(error) => {
                if (error) {
                    if (error.msg === 'login_required') this.authContext.login();
                    else {
                        console.log(error);
                        alert(error);
                    }
                }
            }
        );
    }

    public getCachedToken(): string {
        return this.authContext.getCachedToken(this.authContext.config.clientId);
    }
    public getCachedUser(): UserInfo {
        return this.authContext.getCachedUser();
    }

    public getUserProfileData(): UserProfile {
        const user = this.authContext.getCachedUser();
        const userProfileData = new UserProfile();
        if (user) {
            userProfileData.name = user.profile.name;
            userProfileData.firstName = user.profile.given_name;
            userProfileData.surname = user.profile.family_name;
            userProfileData.emailAddress = user.userName;
            userProfileData.userProfileName = user.profile.name || user.userName;
        }
        return userProfileData;
    }

    public logout() {
        this.authContext.logout();
    }
}

const adalContext: AdalContext = new AdalContext();
export default adalContext;
export const getToken = () => adalContext.getToken();

我能够生成令牌,但这里的问题是在 Aud 字段中我正在获取 SPA 的客户端 ID,但我的目的是获取后端的客户端 ID,因为我正在为我的后端应用程序生成令牌。所以我正在努力在反应 adal 代码中设置范围。 在邮递员中,我正在进入范围,但在这里不确定如何通过应对。端点在这里是否意味着范围?同样在邮递员中,我正在传递 SPA 应用程序的客户端秘密,但在这里我没有看到任何传递客户端秘密的选项。有人可以帮助我在这里做错什么,或者我是否以错误的方式理解事情。任何帮助,将不胜感激。谢谢

解决方法

你有一个后端api程序,所以如果你需要为里面的api生成一个访问令牌,你需要在azure ad中expose that api然后给一个azure ad应用程序api权限(可以是那个暴露的 api),然后您就可以生成该令牌。

然后我发现了一个带有 react 的 sample of using adal。并添加了如下所示的acquireToken代码,你可以看到范围是图形,因为在这里我想调用图形api。和你的一样,如果你想生成用于调用你自己的api的token,你需要更改acquireToken的参数,并更改ajax调用中的url。

而且 micrsoft 已经升级到 recommend to use msal 来替代 adal,this sample 很有帮助。

authContext.acquireToken('https://graph.microsoft.com',function (error,token) {
        console.log("the token is:" + token);
        $.ajax({
          url: 'https://graph.microsoft.com/v1.0/me',headers:{'authorization':'Bearer '+ token},type:'GET',dataType:'json'
        }).done(function(res) {
          console.log(res);
        });
      })

==================================更新============ ================

是的,我会提供更多细节,如果我误解了,请原谅。

我之前提到过“公开 api”。例如,您已经注册了一个名为“backendAPP”的 azure 广告应用程序,您可以按照上面的教程转到该应用程序并公开一个 api,接下来,也是这个应用程序,转到 api 权限面板并单击添加权限->选择我的apis->选择'backendAPP'->选择权限并点击底部的添加权限。现在你已经完成了配置。

enter image description here enter image description here enter image description here

如果你是第一次暴露一个api,你可能会看到这个,api就是你需要在代码中使用的。

enter image description here

================================ 更新 2============== ========================

我发现 react-adal.js 中的 adalgetToken 如下所示,我的意思是只有 2 个参数,但在您的代码中似乎有 3 个参数。

/**
 * Return user token
 * @param authContext Authentication context
 * @param resource Resource GUID ot URI identifying the target resource.
 */
export function adalGetToken(authContext: AuthenticationContext,resourceUrl: string): Promise<string | null>;

您已经定义了“this.authContext”,我认为您可以直接在代码中使用 this.authContext.acquireToken('resource',callback)

我的adalConfig.js,这里我使用spa appid作为'clientId',当然我已经添加了'api://xx/accses_user'的api权限。我做这个设置只是为了与客户端应用程序和服务器应用程序不同。

import { AuthenticationContext,adalFetch,withAdalLogin,adalGetToken } from 'react-adal';

export const adalConfig = {
tenant: 'e4c-----57fb',clientId: '2c0e---f157',endpoints: {
    api: 'api://33a01---aebfe202/user_access' // <-- The Azure AD-protected API
},cacheLocation: 'localStorage',};

export const authContext = new AuthenticationContext(adalConfig);

export const adalApiFetch = (fetch,url,options) =>
    adalFetch(authContext,adalConfig.endpoints.api,fetch,options);

export const withAdalLoginApi = withAdalLogin(authContext,adalConfig.endpoints.api);

export const adalGetToken2 = () =>
    adalGetToken(authContext,adalConfig.endpoints.api);

我的 app.js

import React,{ Component } from 'react';
import { authContext,adalConfig,adalGetToken2} from './adalConfig';
import { runWithAdal } from 'react-adal';

const DO_NOT_LOGIN = false;

class App extends Component {

  state = {
    username: ''
  };

  componentDidMount() {

    runWithAdal(authContext,() => {
      // TODO : continue your process
      var user = authContext.getCachedUser();
      if (user) {        
        console.log(user);
        console.log(user.userName);
        this.setState({ username: user.userName });        
      }
      else {
          // Initiate login
          // authContext.login();        
        console.log('getCachedUser() error');
      }
  
      var token = authContext.getCachedToken(adalConfig.clientId)
      if (token) {        
        console.log(token);
      }
      else {        
        console.log('getCachedToken() error');       
      }

      authContext.acquireToken('api://33a01fed-253f-43e5-a0bb-0fffaebfe202/',token) {
        console.log("the token is:" + token);
      })

      // adalGetToken2().then(
      //   (token) => {
      //     console.log("the token2 is : "+token);
      //   },//   (error) => {
      //       if (error) {
      //           if (error.msg === 'login_required') this.authContext.login();
      //           else {
      //               console.log("the error is : "+error);
      //           }
      //       }
      //   }
      // );
     },DO_NOT_LOGIN);
  }

  render() {
    return (
      <div>
        <p>username:</p>
        <pre>{ this.state.username }</pre>
      </div>
    );
  }
}

export default App;