How to set up role based authentication in a Blazor Server app in Microsoft Entra ID

71185955 40 Reputation points
2024-04-29T07:39:18.5833333+00:00

Hi,

I have a Blazor Server app and I want to use role based authorization in Microsoft Entra ID. I created role for it and I added permission to it:

User's image User's image

Program.cs

builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)

.AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd"))

.EnableTokenAcquisitionToCallDownstreamApi(initialScopes)

.AddMicrosoftGraph(builder.Configuration.GetSection("MicrosoftGraph"))

.AddInMemoryTokenCaches();

builder.Services.AddControllersWithViews().AddMicrosoftIdentityUI();

builder.Services.AddAuthorization(options =>

{

options.AddPolicy("Officer", policy => policy.RequireRole("Officer"));

});

MainLayout.razor

`<AuthorizeView Policy="Officer">`

<Authorized>

<MudMainContent Style="background-color:--mud-palette-background-grey;">

@Body

</MudMainContent>

</Authorized>

<NotAuthorized>

<MudMainContent Style="background-color:--mud-palette-background-grey;">

<p>Access denied.</p>

</MudMainContent>

</NotAuthorized>

</AuthorizeView>

appsettings.json

"MicrosoftGraph": {

"BaseUrl": "https://graph.microsoft.com/v1.0",

"Scopes": [ "user.read.all", "directory.read.all", "GroupMember.Read.All", "Group.Read.All" ]

},

Unfortunately, I haven't been able to figure out the cause of the problem so far.

Blazor
Blazor
A free and open-source web framework that enables developers to create web apps using C# and HTML being developed by Microsoft.
1,414 questions
Microsoft Entra ID
Microsoft Entra ID
A Microsoft Entra identity service that provides identity management and access control capabilities. Replaces Azure Active Directory.
19,806 questions
0 comments No comments
{count} votes

Accepted answer
  1. JasonPan - MSFT 4,386 Reputation points Microsoft Vendor
    2024-04-29T08:28:32.6633333+00:00

    Hi @71185955,

    Have you assigning roles to users ? And could you kindly check this official document Add app roles to your application and receive them in the token.

    Best Regards

    Jason

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful