In this tutorial, we’ll walk through using Azure Active Directory (AD) to secure a React application with a .NET Core backend.
create-react-app
http://localhost:3000
). For redirecting logout to work without HTTPS, modify the Front-Channel Logout in the manifest.Microsoft.AspNetCore.Authentication.JwtBearer
NuGet package.In the appsettings.json
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"AzureAd": {
"Instance": "https://login.microsoftonline.com/",
"Domain": "",
"TenantId": "",
"ClientId": ""
}
}
In program config
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAd"));
react-aad-msal
npm package to handle authentication with Azure AD.react-aad-msal
provider component to use your Azure AD application’s client ID and redirect URI.react-aad-msal
provider component.AuthenticationContext
object provided by react-aad-msal
to authenticate the user and acquire and access token.Sign in
export const SignInButton = () => {
const { instance } = useMsal();
const handleLogin = () => {
instance.loginRedirect(loginRequest).catch((e) => {
console.log(e);
});
};
return (
<button
onClick={handleLogin}
className="group relative flex w-full justify-center rounded-md border border-transparent
bg-indigo-600 py-2 px-4 text-sm font-medium text-white hover:bg-indigo-700
focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2"
>
Sign in
</button>
);
};
Sign out
export const SignOutButton = () => {
const { instance } = useMsal();
const handleLogout = () => {
instance.logoutRedirect({
postLogoutRedirectUri: "http://localhost:3000",
});
};
return (
<button
onClick={handleLogout}
className="text-gray-300 hover:bg-gray-700 hover:text-white px-3 py-2 rounded-md text-sm font-medium">
Sign Out
</button>
);
};
The acquireTokenSilent will handle the token refresh
const getWeatherForecast = () => {
instance
.acquireTokenSilent({
...loginRequest,
account: accounts[0],
})
.then((response) => {
const headers = new Headers();
const bearer = `Bearer ${response.accessToken}`;
headers.append("Authorization", bearer);
const options = {
method: "GET",
headers: headers,
};
fetch(process.env.REACT_APP_API_PATH + "/WeatherForecast", options).then(
(response) => {
if (response.ok) {
response.json().then((value) => setData(value));
}
}
);
});
};
By following this tutorial, you should now have a React application secured with Azure AD authentication and a .NET Core backend that validates access tokens. With this setup, you can build secure, authenticated applications that utilize Azure AD for identity management.
Copyright (c) 2024