如何将azure广告整合到也使用azure的REST API的React Web应用程序中 [英] How to integrate azure ad into a react web app that consumes a REST API in azure too

查看:52
本文介绍了如何将azure广告整合到也使用azure的REST API的React Web应用程序中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Web应用程序,这是React,并且我已经为该Web应用程序本身配置了Azure AD身份验证。它的100%Client网站应用程序,没有服务器端组件。

I have one web app which is React, and I already configured Azure AD Authentication for the web app itself. Its 100% Client site app, no server side components.

我使用了以下组件:
https://github.com/salvoravida/react-adal

我的代码如下:
adalconfig.js

My code is as follows: adalconfig.js

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

export const adalConfig = {
  tenant: 'mytenantguid',
  clientId: 'myappguid',
  endpoints: {
    api: '14d71d65-f596-4eae-be30-27f079bf8d4b',
  },
  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);

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import DashApp from './dashApp';
import registerServiceWorker from './registerServiceWorker';
import 'antd/dist/antd.css';

import { runWithAdal } from 'react-adal';
import { authContext } from './adalConfig';

const DO_NOT_LOGIN = false;

runWithAdal(authContext, () => {

  ReactDOM.render(<DashApp />, document.getElementById('root'));

  // Hot Module Replacement API
  if (module.hot) {
    module.hot.accept('./dashApp.js', () => {
      const NextApp = require('./dashApp').default;
      ReactDOM.render(<NextApp />, document.getElementById('root'));
    });
  }

},DO_NOT_LOGIN);


registerServiceWorker();

dashapp.js

dashapp.js

import React from "react";
import { Provider } from "react-redux";
import { store, history } from "./redux/store";
import PublicRoutes from "./router";
import { ThemeProvider } from "styled-components";
import { LocaleProvider } from "antd";
import { IntlProvider } from "react-intl";
import themes from "./settings/themes";
import AppLocale from "./languageProvider";
import config, {
  getCurrentLanguage
} from "./containers/LanguageSwitcher/config";
import { themeConfig } from "./settings";
import DashAppHolder from "./dashAppStyle";
import Boot from "./redux/boot";

const currentAppLocale =
  AppLocale[getCurrentLanguage(config.defaultLanguage || "english").locale];


const DashApp = () => (
  <LocaleProvider locale={currentAppLocale.antd}>
    <IntlProvider
      locale={currentAppLocale.locale}
      messages={currentAppLocale.messages}
    >
      <ThemeProvider theme={themes[themeConfig.theme]}>
        <DashAppHolder>
          <Provider store={store}>
            <PublicRoutes history={history} />
          </Provider>
        </DashAppHolder>
      </ThemeProvider>
    </IntlProvider>
  </LocaleProvider>
);
Boot()
  .then(() => DashApp())
  .catch(error => console.error(error));

export default DashApp;
export { AppLocale };

直到该点,一切正常,当用户未通过身份验证时,将其重定向到login.live.com用于身份验证,然后将其重定向回去。

Until that point everything works fine, when the user is not authenticated its redirected to login.live.com for authentication and then its redirected back.

但是我还创建了另一个Azure Web应用程序来托管REST API,该REST API已在Azure AD中进行配置,以便用户

However I also created another azure webapp for hosting a REST API, that REST API is already configured in Azure AD, so that users that try to use the rest will need to be authenticated.

现在的问题是:如何设置客户端APP来使用受Azure AD保护的REST API。 ?

Now the question is: How do I setup my client side APP to consume REST API which is protected by Azure AD.?

我找到了这个,并找到了我想要的东西,但是我不确定如何将其集成到上面的现有代码中

I found this and looks what I am looking for, but I am not sure how to integrate this into my existing code above

https://github.com/AzureAD / azure-activedirectory-library-for-js / issues / 481

更新:
面向潜在读者

Update: For potential readers

此答案以及此url上的说明以配置应用程序注册ns帮助我解决了这个问题: https://blog.ithinksharepoint.com/2016/05/16/dev-diary-s01e06-azure-mvc-web-api-angular-and-adal-js-和-401s /

This answer plus the instructions on this url to configure App registrations helped me to solve the problem: https://blog.ithinksharepoint.com/2016/05/16/dev-diary-s01e06-azure-mvc-web-api-angular-and-adal-js-and-401s/

推荐答案

此处的密钥是 adalApiFetch ,在 adalConfig.js 中定义。如您所见,它是 adalFetch 的简单包装。此方法(定义在 react- adal )接收一个ADAL实例( authContext ),一个资源标识符( resourceGuiId ),方法(获取),URL( url )和对象(选项)。该方法执行以下操作:

The key here is adalApiFetch, defined in adalConfig.js. As you can see, it's a simple wrapper around adalFetch. This method (defined in react-adal) receives an ADAL instance (authContext), a resource identifier (resourceGuiId), a method (fetch), a URL (url) and an object (options). The method does the following:


  1. 使用ADAL实例( authContext )获得由 resourceGuiId 标识的资源的访问令牌。

  2. 将此访问令牌添加到标头选项对象的c $ c>字段(如果未提供,则创建一个)。

  3. 调用给定的获取方法传入 url options 对象作为参数。

  1. Use the ADAL instance (authContext) to obtain an access token for the resource identified by resourceGuiId.
  2. Add this access token to the headers field of the options object (or create one if it wasn't provided).
  3. Call the given "fetch" method passing in url and the options object as parameters.

adalApiFetch 方法(已在 adalConfig.js 中定义)只需使用 adalConfig.endpoints.api 中标识的资源调用 adalFetch

The adalApiFetch method (which you have defined in adalConfig.js) simply calls adalFetch with the resource identified in adalConfig.endpoints.api.

好,那么如何使用所有这些来发出REST请求,并在React应用程序中使用响应?让我们举个例子。在以下示例中,我们将使用Microsoft Graph API作为受Azure AD保护的REST API。我们将通过友好的标识符URI( https://graph.microsoft.com )对其进行识别,但是只需记住,那也可以是Guid应用程序ID。

Ok, so how do you use all of this to make a REST request, and consume the response in your React app? Let's use an example. In the following example, we will be using the Microsoft Graph API as the Azure AD-protected REST API. We will be identifying it by it's friendly identifier URI ("https://graph.microsoft.com"), but just keep in mind that that could just as well be the Guid app ID.

adalConfig.js 定义ADAL配置,并导出几个辅助方法:

adalConfig.js defines the ADAL configuration, and exports a couple helper methods:

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

export const adalConfig = {
tenant: '{tenant-id-or-domain-name}',
clientId: '{app-id-of-native-client-app}',
endpoints: {
    api: 'https://graph.microsoft.com' // <-- 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);

index.js 包装 indexApp.js 使用 react-adal 中的 runWithAdal 方法,可确保用户使用Azure AD签名在加载 indexApp.js 之前:

index.js wraps indexApp.js with the runWithAdal method from react-adal, which ensures the user is signed with Azure AD before loading indexApp.js:

import { runWithAdal } from 'react-adal';
import { authContext } from './adalConfig';

const DO_NOT_LOGIN = false;

runWithAdal(authContext, () => {

// eslint-disable-next-line
require('./indexApp.js');

},DO_NOT_LOGIN);

indexApp.js 只是加载并呈现<$ c $的实例c> App ,这里没什么好看的:

indexApp.js simply loads and renders an instance of App, nothing fancy here:

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';

ReactDOM.render(<App />, document.getElementById('root'));
registerServiceWorker();

App.js 是发生魔术的简单组件:

App.js is a simple component where the magic happens:


  • 我们定义一个 state 值。在这种情况下,它称为 apiResponse ,因为我们只是显示原始API响应,但是您当然可以根据需要命名该状态(或具有多个状态值)。

  • componentDidMount (在DOM中的元素可用之后运行)期间,我们调用 adalApiFetch 。我们传入 fetch (从获取API 作为 fetch 参数,以及我们要发出的REST请求的端点( / me 端点):

  • render 方法中,我们只显示此状态值在< pre> 元素中。

  • We define a state value. In this case, it's called apiResponse since we're just displaying the raw API response, but of course you could name this state whatever you wanted (or have multiple state values).
  • During componentDidMount (which is run after the element is available in the DOM), we make a call to the adalApiFetch. We pass in fetch (from the Fetch API as the fetch parameter, and the endpoint for the REST request we want to make (the /me endpoint in Microsoft Graph, in this case):
  • In the render method, we simply display this state value in a <pre> element.
import React, { Component } from 'react';
import { adalApiFetch } from './adalConfig';

class App extends Component {

  state = {
    apiResponse: ''
  };

  componentDidMount() {

    // We're using Fetch as the method to be called, and the /me endpoint 
    // from Microsoft Graph as the REST API request to make.
    adalApiFetch(fetch, 'https://graph.microsoft.com/v1.0/me', {})
      .then((response) => {

        // This is where you deal with your API response. In this case, we            
        // interpret the response as JSON, and then call `setState` with the
        // pretty-printed JSON-stringified object.
        response.json()
          .then((responseJson) => {
            this.setState({ apiResponse: JSON.stringify(responseJson, null, 2) })
          });
      })
      .catch((error) => {

        // Don't forget to handle errors!
        console.error(error);
      })
  }

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

export default App;

这篇关于如何将azure广告整合到也使用azure的REST API的React Web应用程序中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆