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
exportconstmsalConfig= { auth: { clientId:"Enter_the_Application_Id_Here",// application id authority:"https://login.microsoftonline.com/Enter_the_Tenant_Info_Here",// directory id redirectUri:"http://localhost:3000",// after auth success, will redirect in this uri }, cache: { cacheLocation:"sessionStorage",// This configures where your cache will be stored },}
Create a microsoft auth provider
If we want to use it in react hook way, we need to create a provider.
MsAuthProvider.jsx
import*from"react";import { MsalProvider } from'@azure/msal-react';import { PublicClientApplication } from'@azure/msal-browser';import { msalConfig } from'./msconfig.js';// create msal instance and export it for using.exportconstmsalInstance=newPublicClientApplication(msalConfig);exportdefaultfunctionMsAuthProvider({ children }) {return <MsalProviderinstance={msalInstance}> {children} </MsalProvider>}
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
import*from'react';import { Card, Typography, CardBody, CardFooter, Button } from"@material-tailwind/react";import { useSelector } from"react-redux";import { useMsal } from"@azure/msal-react";exportdefaultfunctionSignIn() {consthandleLogin= () => {// this will open a popup for signin, after singin popup will be close, then// app will redirect to the redirectUri as the config in msalConfiginstance.loginPopup({ scopes: ["User.Read"] }).catch((e) =>console.log(e)); };return ( <divclassName="flex justify-center mt-32"> <CardclassName="w-96"> <CardBodyclassName="flex flex-col gap-4 place-items-center"> <Typographyvariant="h3"> Sign In </Typography> </CardBody> <CardFooterclassName="pt-0"> <ButtonclassName="bg-blue-900"fullWidthonClick={handleLogin} > Sign In With MicroSoft </Button> </CardFooter> </Card> </div> )}
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
import axios from'axios'import { msalInstance } from'./msAuthProvider/index.jsx';constrequest=axios.create({ baseURL:'/'})// add request.interceptors.request.use(async config => {// msalInstance is exported by msAuthProvider file, because we can not use the hook hereconstaccounts=msalInstance.getAllAccounts();if (accounts.length>0) {constaccessToken=awaitinstance.acquireTokenSilent({ scopes: ["User.Read"] account: accounts[0], }).then((response) =>response.accessToken);if (accessToken) {config.headers.Authorization =`Bearer ${accessToken}` } }return config;},function (error) {returnPromise.reject(error);});exportdefault request;