Steps for Azure AD Integration in ASP
Steps for Azure AD Integration in ASP
5. Select APP roles from the left section and create app role and add the entries for
each API in the menu shown below:
6. Next we need to navigate to token confifuration and add optional claim as idtyp to
determine if token is an app token or app + user token
Under token type select access and then under the claim search for idtyp as
shown below
7. Under the appsettings.json we will be adding following things as shown
below:
"AzureAd": {
"Instance": "https://login.microsoftonline.com",
"TenantId": "30bf9f37-d550-4878-9494-1041656caf27",
"ClientId": "e1262245-c87d-4f59-ade5-034e808ac807",
"Scopes": {
"Read": [ "ToDoList.Read", "ToDoList.ReadWrite" ],
"Write": [ "ToDoList.ReadWrite" ]
},
"AppPermissions": {
"Read": [ "ToDoList.Read.All", "ToDoList.ReadWrite.All" ],
"Write": [ "ToDoList.ReadWrite.All" ]
}
},
using Microsoft.Identity.Web;
using Microsoft.AspNetCore.Authentication.JwtBearer;
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationSche
me).AddMicrosoftIdentityWebApi(builder.Configuration, “AzureAd”);
We can skip the second argurment as we are using the AzureAd default.
10.After app.useHttpsRedirection() and before app.UseAuthorization() add
app.UseAuthentication();
11. At controller level we need to add [Authorize] annotations to the class
name.
[ApiController]
[Route("[controller]")]
[Authorize]
public class WeatherForecastController: ControllerBase
{
// Controller logic……}
12. We need to then define the scope to the controller function by using the
data annotation as shown below:
[RequiredScopeOrAppPermission(
RequiredScopesConfigurationKey = "AzureAD:Scopes:Read",
RequiredAppPermissionsConfigurationKey = "AzureAD:AppPermissions:Read"
)]
public IEnumerable<WeatherForecast> Get()
{
If we skip any endpoint with the above annotations then we will get forbidden error.
We can also add the above annotations at the controller level.
Steps for Azure AD Integration in React Application:
1. Create App registration and then select appropriate Supported Account Types.
2. Select Authentication option from the sidebar and appropriate redirect URIs.
3. Under the API Permissions section select the appropriate delegated
permissions by clicking on the Add a permission:
a. Select Microsoft Graph from the Microsoft APIs section.
/**
* Scopes you add here will be prompted for user consent during sign-in.
* By default, MSAL.js will add OIDC scopes (openid, profile, email) to any login
request.
* For more information about OIDC scopes, visit:
* https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-
permissions-and-consent#openid-connect-scopes
*/
export const loginRequest = {
scopes: ["openid", "profile",
"user.read", ...protectedResources.customerListAPI.scopes.read, ...protectedReso
urces.customerListAPI.scopes.write]
};
6. We need to create a custom hook to fetch the data along with getting
accesstoken as mentioned below:
import { useCallback, useState, useEffect } from "react";
import { InteractionRequiredAuthError, InteractionStatus } from "@azure/msal-
browser";
import { useMsal } from "@azure/msal-react";
const useFetchWithMsal = (msalRequest) => {
const { instance, inProgress, accounts } = useMsal();
const [accessToken, setAccessToken] = useState("");
useEffect(() => {
if (accounts.length > 0 && inProgress === InteractionStatus.None) {
getAccessToken();
}
}, [instance, msalRequest, accounts, inProgress, getAccessToken]);
const execute = useCallback(async (method, endpoint, requestData = null)
=> {
const token = accessToken || await getAccessToken();
const headers = new Headers();
headers.append("Authorization", `Bearer ${token}`);
if (requestData) headers.append('Content-Type', 'application/json');
const options = {
method: method,
headers: headers,
body: requestData ? JSON.stringify(requestData) : null,
};
return {
execute,
};
};
6. We need to use the custom hook for making the api call by including the
access token as shown below:
const {execute} = useFetchWithMsal({
scopes: protectedResources.customerListAPI.scopes.write,
});
execute("POST", protectedResources.customerListAPI.endpoint,
formData).then(data=> {
console.log(data)
}).catch(error=> {
console.error(error);
})