Microsoft React App的Azure认证

时间:2019-03-15 14:43:48

标签: reactjs azure authentication msal

我想在outlook api contact的React上使用authentification Azure AD.

以下代码可在新的create-react-app上使用,但他不在我的其他应用上使用。

“ msal”:“ 0.2.3”
“ @ microsoft / microsoft-graph-client”:“ 1.3.0”

当我使用身份验证按钮时,我的应用程序在Microsoft登录网站上重定向,她返回我的当前页面,但我没有获得令牌。 “ isAuthenticated” state not change.但是我想将isAuthenticated状态更改为true,并用身份验证响应填充用户状态。

鉴于此代码,您能帮我吗?

app.js

import config from './Config';
import { UserAgentApplication } from 'msal';
import { getUserDetails } from './GraphService';
import Calendar from './Calendar';

import './referral.scss';

class DashboardReferral extends LoadingComponent {

  constructor(props) {

    super(props);

    this.userAgentApplication = new UserAgentApplication(config.appId, null, null);

    var user = this.userAgentApplication.getUser();

    this.state = {
      isAuthenticated: (user !== null),
      user: {},
      error: null
    };

    if (user) {
      // Enhance user object with data from Graph
      this.getUserProfile();

    }
    console.log("erreur de la récup de user")
  }

  async login() {
    try {
      console.log("début fonction login")

      await this.userAgentApplication.loginRedirect(config.scopes);
      await this.getUserProfile();
      console.log("ok login")
    }
    catch (err) {
      var errParts = err.split('|');
      this.setState({
        isAuthenticated: false,
        user: {},
        error: { message: errParts[1], debug: errParts[0] }
      });
      console.log("erreur fonction login")
    }
  }

  logout() {
    this.userAgentApplication.logout();
  }

  async getUserProfile() {
    try {
      // Get the access token silently
      // If the cache contains a non-expired token, this function
      // will just return the cached token. Otherwise, it will
      // make a request to the Azure OAuth endpoint to get a token
      var accessToken = await this.userAgentApplication.acquireTokenSilent(config.scopes);
      console.log('get user profile', this.userAgentApplication)
      console.log(accessToken)
      if (accessToken) {
        
        // Get the user's profile from Graph
        var user = await getUserDetails(accessToken);
        
        this.setState({
          isAuthenticated: true,
          user: {
            displayName: user.displayName,
            email: user.mail || user.userPrincipalName
          },
          error: null
        });
      }
    }
    catch (err) {
      var error = {};
      console.log(err)
      if (typeof (err) === 'string') {
        var errParts = err.split('|');
        error = errParts.length > 1 ?
          { message: errParts[1], debug: errParts[0] } :
          { message: err };
      } else {
        error = {
          message: err.message,
          debug: JSON.stringify(err)
        };
      }

      this.setState({
        isAuthenticated: false,
        user: {},
        error: error
      });
    }
  }

config.js

module.exports = {
  appId: '*******************',
  scopes: [
    "user.read",
    "calendars.read",
    "contacts.read",
  ]
};

graphservice.js

var graph = require('@microsoft/microsoft-graph-client');

function getAuthenticatedClient(accessToken) {
  // Initialize Graph client
  const client = graph.Client.init({
    // Use the provided access token to authenticate
    // requests
    authProvider: (done) => {
      done(null, accessToken);
    }
  });

  return client;
}

export async function getUserDetails(accessToken) {
  const client = getAuthenticatedClient(accessToken);

  const user = await client.api('/me').get();
  return user;
}

export async function getEvents(accessToken) {
  const client = getAuthenticatedClient(accessToken);

  const events = await client
    .api('/me/events')
    .select('subject,organizer,start,end')
    .orderby('createdDateTime DESC')
    .get();

  return events;
}

export async function getPeople(accessToken) {
  const client = getAuthenticatedClient(accessToken);

  const people = await client
    .api('/me/contacts?$top=2000')
    .get();

  return people;
}

0 个答案:

没有答案