How to inject aditional claims after Azure AD Login in Blazor Server

Mohammad Nasir Uddin 41 Reputation points
2022-10-03T12:29:52.813+00:00

I have Blazor Server apps. I have a SSO (Azure Active Directory) login feature. After login with SSO I get some claims from Azure Active Directory (AD). But after login I would like to set some aditiional claims. So I have these below code in the MainLayout.razor.cs file.

[Inject] UserManager<AppUser> UserManager { get; set; }  
  
 protected override async Task OnInitializedAsync()  
 {  
    string username = "testuser@email.com";  
    var createdUser = await UserManager.FindByNameAsync(username);                              
    await UserManager.AddClaimAsync(createdUser, new Claim(ClaimTypes.Role, "Adminstrator"));  
 }  

And in every razor page, I have the below authorize attribute to secure the page to view.

@attribute [Authorize(Roles = "Adminstrator")]  

But even after injecting the role I can not access the page. I checked and found that the claim with role is not injected.

Can anyone tell me how to selve this problem?

Microsoft Entra ID
Microsoft Entra ID
A Microsoft Entra identity service that provides identity management and access control capabilities. Replaces Azure Active Directory.
19,466 questions
0 comments No comments
{count} votes

Accepted answer
  1. Sandeep G-MSFT 14,406 Reputation points Microsoft Employee
    2022-10-04T06:33:52.117+00:00

    @Mohammad Nasir Uddin

    Thank you for posting your question in Microsoft Q&A.

    By looking at the issue it seems that Azure AD is not sending the user role as claim in the token sent to your application.

    Not sure what is the protocol you have used to configure Blazor application.

    Thinking that you have used SAML protocol, you can use below steps to pass user role as a claim to application.

    I have tested this in my lab and it working as expected. To pass the user role as claim you don't have to specifically create additional claim. Roles that will be passed in SAML tokens are defined in application. Azure AD roles cannot be passed in SAML token. Only roles that are defined in application and the roles which are assigned to users when you assign users to application can be sent as a claim in SAML token.

    247295-image.png

    If you do not have any application roles defined, then you can refer below article to create roles using graph explorer,
    https://learn.microsoft.com/en-us/azure/active-directory/develop/active-directory-enterprise-app-role-management

    Do let us know if you have any further questions on this.

    Please "Accept the answer" if the information helped you. This will help us and others in the community as well.

    0 comments No comments

0 additional answers

Sort by: Most helpful