A wrapper around Microsofts MSAL library for react. This package can be used with Azure AD OR Azure B2C, simply change config object to refelct right endpoints. Here is a minimal repo showinf step by step how to get started using Feliz minimal template. It does assume you register you application in AD or B2C in advance.
-
Install npm dependencies
npm:
dotnet add package Feliz.React.Msal npm install @azure/msal-react
femto:
femto install Feliz.React.Msal
-
Initialize msal config (this is an example using B2C with sign in flow)
open Feliz.React.Msal let msalConfig ={ auth={ clientId="" authority="https://<domain>.b2clogin.com/<domain>.onmicrosoft.com/<Sign in flow>" knownAuthorities=[|"https://<domain>.b2clogin.com"|] redirectUri= "https://localhost:8080/" postLogoutRedirectUri = "https://localhost:8080/"}; cache={cacheLocation="sessionStorage"; storeAuthStateInCookie=false} } let client:IPublicClientApplication = createClient msalConfig
-
Pass client into msal component
[<ReactComponent>] let App() = MsalProvider.create[ MsalProvider.instance client MsalProvider.children[ ] ]
Use Authenticated/Unauthenticated
template to show or hide sections of UI. Alternatively use useIsAuthenticated()
hook if use if XXX then xxx else
block to show or hide UI.
AuthenticatedTemplate.create [
AuthenticatedTemplate.children [
]
]
UnauthenticatedTemplate.create [
UnauthenticatedTemplate.children [
]
]
If you are using Elmish you will need to use the useEffect()
react hook in conjuction with useIsAuthenticated()
or useMsal()
hooks to verify user is logged in and dispatch an event.
[<ReactComponent>]
let Component () =
let client = useMsal()
let isAuthenticated = useIsAuthenticated(None)
//Dispatch you event here
let someEffect() = async {
if isAuthenticated then
let account = client.accounts[0]
setUser Some account |> dispatch
else
setUser None |> dispatch
}
//Re runs effect isAuthenticated changes
React.useEffect(someEffect >> Async.StartImmediate, [| box isAuthenticated |])
Support for the following custon msal hooks are supported under the 'Hooks' module;
- useAccount
- useIsAuthenticated
- useMsal
- useMsalAuthentication