Microsoft OAuth with in react hook

Author: markzzw | Date: 2023-12-07

OAuth is helpful to let developers get user information easily, here I will show you the usages with the microsoft OAuth in react hook way, let's start the travel.

Config in Azure

Register your app

Note: remenber the application ID and Directory ID we will use them in the next step

Set up your react project

Node modules

fisrt we need to install the dependencies.

Create a msconfig.js file

msconfig.js

Create a microsoft auth provider

If we want to use it in react hook way, we need to create a provider.

MsAuthProvider.jsx

Use MsAuthProvider to warp your react application

In the App.jsx, we need to do the refactor as the follow.

We can use the AuthenticatedTemplate and UnauthenticatedTemplate provided by the @azure/msal-react, it's helpful to control of the displaying component, we don't need to handle the authrized status, MsAuthProvider will handle this for the app.

Create SignIn component

SignIn component index.jsx

Get user information

profile.jsx

Here we need to get access token so we use the ["User.Read"] as the scpoes param, if you want to get id token, you should use the ['openid'] as the scpoes param.

Integration with axios

Axios has interceptors can help us to add some configuration before request, let's integrate axios for the requests.

request.js

Then we can use axios request like this.

Refactor profile.jsx

Reference

Last updated