首页 > 解决方案 > Azure oAuth 从 Angular 获取请求中获取 HTML 正文而不是代码

问题描述

我只是像下面那样对授权端点进行简单的获取请求,但在正文中获得了 HTML 响应,但我希望重定向 URI 中的代码,以便我可以使用此代码来获取令牌。我在 Angular 应用程序中提出这个获取请求

getAuth() {
return this.http.get('https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/authorize?response_type=code&client_id=0b59aafg-786c-425a-b2b4-l3f1e9e0d09g
&scope=openid+profile+email
&response_mode=query
&redirect_uri=https://qwe1124/logentry/log-entry/#/', { responseType: 'text', observe: 'response' });
  }

以下是响应示例正文:“ ↵ ↵<!-- 版权所有 (C) Microsoft Corporation。所有“标头:HttpHeaders {normalizedNames: Map(0),lazyUpdate: null,lazyInit: ƒ} ok: true status: 200 statusText :“确定”类型:4

请帮我解决这个问题..

标签: angularazureoauthazure-active-directory

解决方案


首先要说,auth code grant flow 是一种交互式身份验证,它需要交互式登录(由用户)。因此,如果您对 url 使用 get 请求https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/authorize,它将响应登录页面的 html。

要实现验证码授权流程,您需要使用弹出窗口进行验证。我找到下面提供的代码示例供您参考:

this.authWindow = new BrowserWindow(
    {
        alwaysOnTop : true, // keeps this window on top of others
        webPreferences : {
            nodeIntegration  : false, // again, don't need to specify these if Electron v4+ but showing for demo
            contextIsolation : true // we can isolate this window
        }
    }
);

this.authWindow.on('closed', () => {
    this.authWindow = null;
});

authWindow.loadURL(`
    https://login.microsoftonline.com/${config.auth.tenantId}/oauth2/v2.0/authorize?
        client_id=xxxxxxx
        &response_type=code
        &redirect_uri=xxxxxxx
        &response_mode=query
        &scope=xxxxxxx
`);

在新的浏览器窗口中,您需要登录以进行身份​​验证。

然后我们需要监听它何时返回 URL 中的查询参数,其中包含?code=并将具有用于获取访问令牌的授权代码。您可以参考下面的代码示例:

authWindow.webContents.on('did-finish-load', () => {
    session.defaultSession.webRequest.onCompleted({ urls: [`{redirect_uri}/?code=` + '*'] }, details => {
        const _url        = details.url.split('?')[1]; // get the equivalent of window.location.search for the URLSearchParams to work properly
        const _params     = new URLSearchParams(_url);
        const _accessCode = _params.get('code');

        if (_accessCode) {
            const tokenRequestUrl = `https://login.microsoftonline.com/${config.auth.tenantId}/oauth2/v2.0/token`;

            const tokenRequestBody = {
                grant_type    : 'authorization_code',
                client_id     : xxxxxxx,
                code          : _accessCode,
                redirect_uri  : xxxxxxx,
                scope         : xxxxxxx,
                client_secret : xxxxxxx     //Only required for web apps
            };

            request.post(
                { url: tokenRequestUrl, form: tokenRequestBody },
                (err, httpResponse, body) => {
                    if (!err) {
                        console.log('Token Received!\n', body);
                    } else {
                        // Probably throw an error? 
                    }
                }
            );
        } else {
          // Probably throw an error?   
        }
    });
});

之后,您可以在body上面的代码中获取访问令牌(在console.log('Token Received!\n', body);上面)


推荐阅读