Coder Social home page Coder Social logo

microsoftgraph / msgraph-sample-reactspa Goto Github PK

View Code? Open in Web Editor NEW
123.0 12.0 104.0 20.78 MB

This sample demonstrates how to use the Microsoft Graph JavaScript SDK to access data in Office 365 from React browser apps.

License: MIT License

HTML 5.92% CSS 3.53% TypeScript 90.48% JavaScript 0.07%
microsoft-graph react devxsample

msgraph-sample-reactspa's Introduction

page_type description products languages
sample
This sample demonstrates how to use the Microsoft Graph JavaScript SDK to access data in Office 365 from React browser apps.
ms-graph
office-exchange-online
typescript
nodejs

Microsoft Graph sample React single-page app

This sample demonstrates how to use the Microsoft Graph JavaScript SDK to access data in Office 365 from React browser apps.

Prerequisites

Before you start this tutorial, you should have Node.js and Yarn installed on your development machine. If you do not have Node.js or Yarn, visit the previous links for download options.

You should also have either a personal Microsoft account with a mailbox on Outlook.com, or a Microsoft work or school account. If you don't have a Microsoft account, there are a couple of options to get a free account:

Register a web application with the Azure Active Directory admin center

  1. Open a browser and navigate to the Azure Active Directory admin center. Login using a personal account (aka: Microsoft Account) or Work or School Account.

  2. Select Azure Active Directory in the left-hand navigation, then select App registrations under Manage.

    Note: Azure AD B2C users may only see App registrations (legacy). In this case, please go directly to https://aka.ms/appregistrations.

  3. Select New registration. On the Register an application page, set the values as follows.

    • Set Name to React Graph Tutorial.
    • Set Supported account types to Accounts in any organizational directory and personal Microsoft accounts.
    • Under Redirect URI, set the first drop-down to Single-page application (SPA) and set the value to http://localhost:3000.
  4. Choose Register. On the React Graph Tutorial page, copy the value of the Application (client) ID and save it, you will need it in the next step.

Configure the sample

  1. Rename the ./graph-tutorial/src/Config.example.ts file to ./graph-tutorial/src/Config.ts.

  2. Edit the ./graph-tutorial/src/Config.ts file and make the following changes.

    1. Replace YOUR_APP_ID_HERE with the Application Id you got from the App Registration Portal.
  3. In your command-line interface (CLI), navigate to the graph-tutorial directory and run the following command to install requirements.

    yarn install

Run the sample

  1. Run the following command in your CLI to start the application.

    yarn start
  2. Open a browser and browse to http://localhost:3000.

Code of conduct

This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact [email protected] with any additional questions or comments.

Disclaimer

THIS CODE IS PROVIDED AS IS WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.

msgraph-sample-reactspa's People

Contributors

andrewconnell avatar baywet avatar dependabot[bot] avatar dodaromike avatar github-actions[bot] avatar jackson-woods avatar jasonjoh avatar jthake avatar juliemturner avatar microsoft-github-policy-service[bot] avatar moich avatar morz avatar slowik84 avatar therealpecus avatar vgrem avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

msgraph-sample-reactspa's Issues

Users with no time zone in mailbox settings causes app to fail

Where did you get the code?

Describe the bug

Not all Microsoft accounts are supported by this demo, because not all user objects retrieved from GraphService's getUserDetails method have the mailboxSettings.timeZone property. Accounts that do not have this property will hang whenever the user goes to the "Calendar" tab.

In my particular case, I was able to find a timeZone property that worked in:
mailboxSettings.workingHours.timeZone.name
in the JSON retrieved from getUserDetails() on the AuthProvider HOC.

To Reproduce

  1. Log in with an account which does not have the user.mailboxSettings.timeZone property
  2. Click "Calendar"
  3. The page will hang.

Expected behavior

The demo should be able to retrieve timezone data for any kind of Microsoft account.
The demo should not hang for any valid Microsoft account.

Desktop

  • OS: Windows 10
  • Browser: Chrome, Edge, Firefox
  • Version: Latest

https://docs.microsoft.com/en-us/graph/tutorials/react?tutorial-step=3 is not building

Where did you get the code?

Describe the bug

There is a mistake in the tutorial page for the AuthProvider.tsx render function.

render() {
  return <WrappedComponent
    error = { this.state.error }
    isAuthenticated = { this.state.isAuthenticated }
    user = { this.state.user }
    login = { () => this.login() }
    logout = { () => this.logout() }
    getAccessToken = { (scopes: string[]) => this.getAccessToken(scopes)}
    setError = { (message: string, debug: string) => this.setErrorMessage(message, debug)}
    {...this.props} {...this.state} />;

-> {...this.state} is causing build error, this code is already fixed in the github, but should be updated in the tutorial

To Reproduce

Steps to reproduce the behavior:

Copy the code from the tutorial until step 3 and try to run it. You'll get error message
F:/code/webDev/ReactMsGraph/LearningMsGraph/graph-tutorial/src/AuthProvider.tsx
TypeScript error in F:/code/webDev/ReactMsGraph/LearningMsGraph/graph-tutorial/src/AuthProvider.tsx(58,21):
'error' is specified more than once, so this usage will be overwritten. TS2783

56 |             render() {
57 |                 return <WrappedComponent

58 | error = { this.state.error }
| ^
59 | isAuthenticated = { this.state.isAuthenticated }
60 | user = { this.state.user }
61 | login = { () => this.login() }

  1. Go to '...'
  2. Click on '....'
  3. Scroll down to '....'
  4. See error

Expected behavior

I expected that the tutorial code would build without errors.

Screenshots

If applicable, add screenshots to help explain your problem.

Desktop

  • OS: Windows 10
  • Browser Chrome
  • Version 86.0.4240.111

Dependency versions

  • Authentication library (MSAL, etc.) version:
  • Graph library (Graph SDK, REST library, etc.) version:

Additional context

Add any other context about the problem here.

ServerError: AADB2C90205: This application does not have sufficient permissions against this web resource to perform the operation.

Hi All,

I get this error when trying to access Microsoft Graph API via B2C authority.

ServerError: AADB2C90205: This application does not have sufficient permissions against this web resource to perform the operation.
Correlation ID: e894fe39-b9bf-4441-b3c4-5740ff72fd5e
Timestamp: 2020-04-14 15:39:16Z

This it my config for MSAL library. i am using the version 1.2.2 of MSAL. Appears to throw the above error when attempting "acquireTokenSilent" for an access token.

export const config = {
appId: "appID",
redirectUri: "http://localhost:3000",
authority:
"https://tenantName.b2clogin.com/tenantName.onmicrosoft.com/B2C_1_SUSI",
scopes: ["https://graph.microsoft.com/User.Read"]
};

I did notice that the builtin b2c-extensions-app that is created when setting up the B2C uses the old Azure Active Directory Graph in it's API permissions. Not sure if this is related.

Regards,

Ben

Incorrect null method in NavBar and Welcome authButtonMethod's components.

In the https://docs.microsoft.com/en-us/graph/tutorials/react?tutorial-step=1 tutorial's step the authButtonMethod method is missing in the App.js file. Here is null and it doesn't work.
According the github code it should be authButtonMethod={this.state.isAuthenticated ? this.logout.bind(this) : this.login.bind(this)} in NavBar component, and authButtonMethod={this.login.bind(this)} in the Welcome (both in render method).

Can you please update the tutorial to correct code, otherwise it takes longer than copy paste and run solution!

403 Error - Access token is empty

I am just trying to run the code with no changes from tutorial but keep getting this error when user authenticates:

{
  "error": {
    "code": "InvalidAuthenticationToken",
    "message": "Access token is empty.",
    "innerError": {
      "date": "2020-09-11T11:21:34",
      "request-id": "4f00c76f-d4dc-465e-889a-d81dfa04969f",
      "client-request-id": "4f00c76f-d4dc-465e-889a-d81dfa04969f"
    }
  }
}

When I log the code output I can see there is in fact an access token which is passed into getAuthenticatedClientas expected. Any idea what's going on?

Thanks

slide 01 typo

slide 01 "page" 12 has a typo, "User create-react-app graph-tutorial" should be "Use create-react-app graph-tutorial"

Getting error "signature invalid" when trying to call my .net core api from this sample

Anyone know why I get the error "signature invalid" when trying to call my .net core api from this sample? I'm passing the access token in the header of the fetch() like other documents have suggested. I created a Azure app registration for my API and exposed the api etc. However, something is wrong with token or how I'm trying to validate it on my .net core api. The api works fine if I disable the [authorize] attribute on my class. Any suggestions would be greatly appreciated as I am suck.

.net core api startup.cs snippet:

services.AddAuthentication(AzureADDefaults.BearerAuthenticationScheme)
.AddAzureADBearer(options => Configuration.Bind("AzureAd", options));

react spa snippet:
// Get the user's access token
var accessToken = await this.props.getAccessToken(config.scopes);

    const startDateEncoded = encodeURIComponent('2018-02-01');
    const endDateEncoded = encodeURIComponent('2018-02-07');
      debugger;
    const response = await fetch(`https://localhost:44307/api/Amounts?StartDate=${startDateEncoded}&endDate=${endDateEncoded}`,{
        headers: !accessToken ? {} : { 'Authorization': `Bearer ${accessToken}`}
    }
    );

ClientAuthError - User Cancelled when running the app in Edge, works fine in Chrome

Hi,

When running the application in Edge I receive the following error:

image

This happens when clicking 'Click here to sign in' as soon as the popup opens to, the error appears.

If I attempt to continue signing in, after entering my password I get redirected to the home page within the popped up window:

image

When running in chrome, the app works perfectly.

Thanks!

Error: Usage of the /common endpoint is not supported for such applications created after '10/15/2018'. Use a tenant-specific endpoint or configure the application to be multi-tenant.

Current Config:

  1. Supported account types: Who can use this application or access this API?
  • Selection: Accounts in this organizational directory only (Single tenant)
  1. Changed app ID, set redirect URL to localhost:3000

Error: Usage of the /common endpoint is not supported for such applications created after '10/15/2018'. Use a tenant-specific endpoint or configure the application to be multi-tenant.

Is it possible to use single tenant and resolve this error? Thanks!

Typescript 3.9 Error

C:/Users/..../Documents/nodejs/react/graphtuto/src/AuthProvider.tsx
TypeScript error in C:/Users/.../Documents/nodejs/react/graphtuto/src/AuthProvider.tsx(74,11):
'error' is specified more than once, so this usage will be overwritten. TS2783

    72 |       return (
    73 |         <WrappedComponent
  > 74 |           error={this.state.error}
       |           ^
    75 |           isAuthenticated={this.state.isAuthenticated}
    76 |           user={this.state.user}
    77 |           login={() => this.login()}

BrowserAuthError, when I click the sign in button in the sample.

Describe the bug
BrowserAuthError: interaction_in_progress: Interaction is currently in progress. Please ensure that this interaction has been completed before calling an interactive API.

To Reproduce
Steps to reproduce the behavior:

  1. Install dependencies and start the app.
  2. Click on 'Click here to sign in' button.
  3. See error on console and screen:

Expected behavior
Redirect to Microsoft sign in page.

Screenshots
image

Desktop (please complete the following information):

  • OS: Windows 11
  • Browser: Edge
  • Version: 119

Dependency versions

  • Authentication library (MSAL, etc.) version: "@azure/msal-browser": "^2.38.3", "@azure/msal-react": "^1.5.12",
  • Graph library (Graph SDK, REST library, etc.) version: "@microsoft/microsoft-graph-client": "^3.0.7",

First step fails

Where did you get the code?

https://docs.microsoft.com/en-us/graph/tutorials/react

Describe the bug

Can't successfully launch generated app.

Works without typescript flag

To Reproduce

Steps to reproduce the behavior:

  1. I run npx [email protected] graph-tutorial --template typescript
  2. Run npm start
  3. Get error

Expected behavior

Browser opens

Desktop

MacOS
bash
Edge Browser

Additional context

I made sure to use the 12.16.1 version of Node

This is the resulting error message.

10:31 $ npm start

> [email protected] start /Users/davidstarr/projects/rjsgraphapi/graph-tutorial
> react-scripts start

/Users/davidstarr/projects/rjsgraphapi/graph-tutorial/node_modules/react-scripts/scripts/utils/verifyTypeScriptSetup.js:239
      appTsConfig.compilerOptions[option] = value;
                                          ^

TypeError: Cannot assign to read only property 'jsx' of object '#<Object>'
    at verifyTypeScriptSetup (/Users/davidstarr/projects/rjsgraphapi/graph-tutorial/node_modules/react-scripts/scripts/utils/verifyTypeScriptSetup.js:239:43)
    at Object.<anonymous> (/Users/davidstarr/projects/rjsgraphapi/graph-tutorial/node_modules/react-scripts/scripts/start.js:31:1)
    at Module._compile (internal/modules/cjs/loader.js:1158:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1178:10)
    at Module.load (internal/modules/cjs/loader.js:1002:32)
    at Function.Module._load (internal/modules/cjs/loader.js:901:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12)
    at internal/main/run_main_module.js:18:47
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] start: `react-scripts start`
npm ERR! Exit status 1

Single Tenant, Organization only

Hello, how would I go about configuring this for single-tenant purposes?

Currently, this training is for multi-tenant use, all users allowed. I wish to restrict my app to only my organization. Is there a different node package that needs to be used instead of msal?

Best regards.
Ingimar

AADB2C90205: This application does not have sufficient permissions against this web resource to perform the operation

You will receive a insufficient permissions error when you execute this sample using the scopes in the Config.js file. You need to provide the scopes correctly for a v2 App.

Config.js

scopes: [
'user.read',
'calendars.read'
]

Should read:

scopes: [
'https://graph.microsoft.com/user.read',
'https://graph.microsoft.com/calendars.read'
]

After making this modification, the React App successfully retrieved the user's profile for my B2C Tenant.

No App registrations option in Azure AD

I could not complete the tutorial following the indications, but there is a workaround. An update might be needed for the tutorial. When signing-in to https://aad.portal.azure.com/ there is only one option for App registrations. The option is called App registrations (Legacy). That option doesn't have a feature for adding Access tokens and ID tokens. Proceeding without those settings will cause an error that says: response_type 'id_token' is not enabled for the application. Below is an image of the only option for adding apps in Azure AD.

App_Registration_Legacy

The only way I could find that would allow me to complete the tutorial by using the above menu was by editing the application manifest and setting the oauth2AllowImplicitFlow value to true.

The problem with that is that the App registrations (Legacy) will be deprecated eventually: https://developer.microsoft.com/en-us/identity/blogs/deprecation-of-app-registrations-legacy-experience-and-the-application-registration-portal-apps-dev-microsoft-com/

According to this article in the Azure AD B2C menu, there is now an option called App registrations (Preview) that also works for authenticating users from Azure AD in Web Apps. This option has the ability to set Access tokens and ID tokens. From the article, in the future, there will be a unified place to register Azure AD and Azure AD B2C apps regardless of which of those two services will the app target.

AADB2C

If one follows this link from the above article: https://aka.ms/appregistrations it takes one to the unified place for app registration. Since it is still not complete, a yellow triangle with an exclamation mark on it appears informing the experience is still not supported on Azure AD B2C directories. Regardless of the message, registering an app there or on the menu App registrations (Preview) works for Azure AD authentication on a React SPA.

New_Registration

Multiple Authorities Error

Hi

As I tried sin-in according to tutorial, I saw the error "Multiple Authorities" as below screen and couldn't log in successfully.

キャプチャ

I tested several times with MS accounts (private and company) on browsers (chrome, edge), sometimes I could login without error. But after sign-out and sing-in again, the error message comes again.
How should I do for solve this issue?

notes.read.all demands for admin approval

Hi,

Using "React Graph Tutorial", scope "notes.read.all" is asking for admin approval

Need admin approval
React Graph Tutorial

React Graph Tutorial needs permission to access resources in your organization that only an admin can grant. Please ask an admin to grant permission to this app before you can use it.
<<<<<

Where as a the following call for "notes.read.all" works without any admin approval issue

"https://login.microsoftonline.com/organizations/oauth2/v2.0/authorize?client_id=1f4ddefc-d849-4f30-a410-73297ed98422&response_type=code&redirect_uri=http%3A%2F%2Flocalhost%3A8000%2Fcgi-bin%2Fcode.py&response_mode=query&scope=Notes.Read.All&state=202005051404";
<<<<<

Where is the issue?

Thanks.

Doesn't work with React 18

Get the versions of the dependencies from the repo instead of using the ones installed with CRA. If you don't, you'll likely run in to issues.

Calling err.split('|') in login()'s catch body throws an exception

I'm experiencing errors during login and it looks like err is not a string.
Changing the line to err.toString().split('|') worked.

Unhandled Rejection (TypeError): err.split is not a function
App.login
E:/hack/msgraph/src/App.js:83
80 | await this.getUserProfile();
81 | }
82 | catch(err) {
83 | var errParts = err.split('|'); <------ ERROR
84 | this.setState({
85 | isAuthenticated: false,
86 | user: {},
View compiled

Typescript support for Create React App Samples

Hi, This project really helped to start with a react app for the graph MSAL library, however working through it found that it is missing typescript which is my preference. Hence, updated my copy to Typescript and is working now. I am interested to make a contribution to this project with the typescript version of the code. I already have the code updated into my git fork, if Ok, will submit a PR. Please let me know

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.