MSAL/Azure React authentication hook
npm install @vtfk/react-msal 
MSAL (Azure auth) React hook
``bash`
npm install --save @vtfk/react-msal
config.js
`javascript
export const config = {
auth: {
clientId: '
authority: 'https://login.microsoftonline.com/
redirectUri: '
postLogoutRedirectUri: '
cache: {
cacheLocation: 'sessionStorage',
storeAuthStateInCookie: false
}
}
// See valid values here: https://azuread.github.io/microsoft-authentication-library-for-js/ref/msal-browser/modules/_src_request_redirectrequest_.html
export const loginRequest = {
scopes: ['openid', 'profile', 'User.Read']
}
`
index.js
`jsx
import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'
import { MsalProvider } from '@vtfk/react-msal'
import { config, loginRequest } from './config'
ReactDOM.render(
document.getElementById('root')
)
`
App.js
`jsx
const App = () => {
const { isAuthenticated, login, authStatus } = useSession()
if (['pending'].includes(authStatus)) {
return
if (!isAuthenticated) {
console.log('app-!isAuth')
login(loginRequest)
return <>>
}
if (isAuthenticated && authStatus === 'finished') {
return
$3
The useSession() hook has these methods and objects available:
-
isAuthenticated (bool)
- authStatus (string) - values are: pending, finished, rejected, unknown
- user (object) - user object from MS Graph - example
- token (string) - access_token from MS Graph
- idToken (string) - id_token from MS Graph
- popupOpen (bool) - true if login popup is open
- loginError (object) - login error object
- login (function) - trigger login
- logout (function) - trigger logout (clears session storage and redirects to azure)
- getToken (function) - gathers and returns the users access token
- apiGet (function) - gets data from provided URL using the users id_token
Parameters
- url (string) (required)
- returnFullResponse (bool) (optional) default = false
- apiPost (function) - posts the provided data to the URL using the users id_token
Parameters
- url (string) (required)
- data (required)
- returnFullResponse (bool) (optional) default = false
- apiPut (function) - updates/put the provided data to the URL using the users id_token
Parameters
- url (string) (required)
- data (required)
- returnFullResponse (bool) (optional) default = false
- apiDelete (function) - deletes data from provided URL using the users id_token
Parameters
- url (string) (required)
- returnFullResponse (bool) (optional) default = false
#### User object
`javascript
{
displayName: 'Trine Testesen',
givenName: 'Trine',
name: 'Trine Testesen',
onPremisesSamAccountName: 'tri0308',
surname: 'Testesen',
tenantId: '08f3813c-9f29-482f-9aec-16ef7cbf477a',
userPrincipalName: 'trine.testesen@vtfk.no',
username: 'trine.testesen@vtfk.no'
}
``