【问题标题】:How to implement authorization code flow in single page application?如何在单页应用中实现授权码流?
【发布时间】:2021-03-22 13:43:25
【问题描述】:

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

我可以获得带有所需详细信息的令牌。现在我在前端反应应用程序中尝试同样的事情。我正在使用 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.appId, 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 是由您自己维护的,即使您提供带有 SPA 客户端 ID 的 Aud 的访问令牌,您也可以将其视为正确的验证码中的Aud。也就是说,如何检查token是否有效,就看你自己了。
  • 实际上,我期望 aud 值作为后端客户端 ID,因为稍后在令牌的帮助下,我想代表我的第三个应用程序流实现。代表我的后端应用程序的令牌和客户端 ID 中的流 Aud 值应该相同
  • 先生有进展吗?很高兴收到您的回复。

标签: reactjs asp.net-core azure-active-directory adal


【解决方案1】:

您有一个后端 api 程序,因此如果您需要为其中的 api 生成访问令牌,您需要在 azure ad 中 expose that api 然后将 api 权限授予 azure ad 应用程序(可以是暴露的 api ),然后您可以生成该令牌。

我发现一个 sample of using adal 有反应。并添加了如下的acquireToken代码,你可以看到范围是graph,因为这里我想调用graph api。和你的一样,如果你想生成用来调用自己api的token,你需要改变acquireToken的参数,改变ajax调用中的url。

微软已经升级到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”。例如,您注册了一个 azure 广告应用调用“backendAPP”,您可以按照上面的教程转到该应用并公开一个 api,接下来,还有这个应用,转到 api 权限面板并单击添加权限->选择我的api->选择'backendAPP'->获取权限,然后点击底部的添加权限。现在您已经完成了配置。

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

==============================更新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, url, 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/', function (error, 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;

【讨论】:

  • 嗨蒂娜瓦谢谢你的回答。我尝试了上面提供的示例,我能够生成令牌和网页,我能够看到我的电子邮件 ID。但是当我看到 JWT 令牌 Aud 具有 SPA 客户端 ID 的值时。但我期待后端 api 正确的 Aud 值客户端 ID
  • 嗨蒂娜瓦,非常感谢您的解释。我在 azure 门户中配置了上述步骤,并尝试使用 postman 如下授权类型:隐式回调 URL:getpostman.com/oauth2/callback Auth URL:login.microsoftonline.com/tenantid/oauth2/v2.0/authorize 客户端 ID:SPA 应用范围的客户端 ID; api://clientidof backend/Access_as_user 这会给我带有 aud 值的令牌作为后端 api 的 clientid。但在反应代码 Aud 中作为 SPA 应用程序的客户端 ID
  • @MrPerfect 正如您所说,您可以使用邮递员生成正确的令牌,但是在您的代码中它不起作用,恐怕您需要在代码中的某个位置更改 id生成令牌,我会尝试你的生成访问令牌的功能。你也可以试试我的功能。
  • 您是否在配置文件中将端点更改为 api://clientidof backend/Access_as_user
  • 是的,我放了,我将更新我上面的代码和 index.tsx 我有下面的代码 export const 配置:AdalConfig = { cacheLocation: 'sessionStorage', redirectUri: getReplyUrl(), clientId: '123' , 租户: '123', 端点: { api: 'api://123/Access_as_user' }, loadFrameTimeout: 10000 };
猜你喜欢
  • 1970-01-01
  • 2018-11-04
  • 2021-08-13
  • 1970-01-01
  • 2020-03-12
  • 1970-01-01
  • 1970-01-01
  • 2020-04-04
  • 2016-11-12
相关资源
最近更新 更多