serge
serge

Reputation: 15239

Get Azure Roles in the Web App

I created a WebApp in Azure. I have the authentication based on the AzureAD...

Actually all users have the same rights... I need to have a group of Administrators and the rest of the world.

I see that in the Azure Portal for my web app there is a Acces control (IAM) where some roles are listed... enter image description here Can I use these roles in my Application?

What actually I do in my View is:

var isAdmin = User.HasClaim("IsAdmin", true.ToString());

If I understand correctly that is named "Claims Based" authentication, but I would like to try to use the Role Based Authentication...

I tried also to do

var userIdentity = (System.Security.Claims.ClaimsIdentity)User.Identity;
var claims = userIdentity.Claims;
var roleClaimType = userIdentity.RoleClaimType;
var roles = claims.Where(c => c.Type == System.Security.Claims.ClaimTypes.Role).ToList();

but that roles list is empty...

Here is the my Startup.cs Autentication code in the public void Configure(IApplicationBuilder app,...

app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions
{
    ClientId = Configuration["Authentication:AzureAd:ClientId"],
    Authority = Configuration["Authentication:AzureAd:AADInstance"] + Configuration["Authentication:AzureAd:TenantId"],
    CallbackPath = Configuration["Authentication:AzureAd:CallbackPath"],
    Events = new OpenIdConnectEvents
    {
        OnTicketReceived = async context =>
        {
            var user = (ClaimsIdentity)context.Ticket.Principal.Identity;
            if (user.IsAuthenticated)
            {
                var firstName = user.FindFirst(ClaimTypes.GivenName).Value;
                var lastName = user.FindFirst(ClaimTypes.Surname).Value;
                var email = user.HasClaim(cl => cl.Type == ClaimTypes.Email) ? user.FindFirst(ClaimTypes.Email).Value : user.Name;
                var connectedOn = DateTime.UtcNow;
                var userId = user.Name;
                var myUser = await repository.GetAsync<Connection>(userId);
                if (myUser == null)
                {
                    myUser = new Connection(userId)
                    {
                        FirstName = firstName,
                        LastName = lastName,
                        Email = email
                    };
                }
                myUser.LastConnectedOn = connectedOn;
                List<Connection> myList = new List<Connection>() { myUser };
                var results = await repository.InsertOrMergeAsync(myList);   
                Claim clm = new Claim("IsAdmin", myUser.IsAdmin.ToString(), ClaimValueTypes.Boolean);
                user.AddClaim(clm);
            }
            return;
        }
      },
    }
});

And also my appsettings.json

"Authentication": {
  "AzureAd": {
    "AADInstance": "https://login.microsoftonline.com/",
    "CallbackPath": "/signin-oidc",
    "ClientId": "xxxxxxxx-xxxx-xxxx-xxxxx-xxxxxxxxxxxx",
    "Domain": "mysite.azurewebsites.net",
    "TenantId": "xxxxxxxx-xxxx-xxxx-xxxxx-xxxxxxxxxxxx"
  }
}

Upvotes: 1

Views: 839

Answers (1)

Jean-Marc Prieur
Jean-Marc Prieur

Reputation: 1649

I believe that the roles that you observed in the portal are related to the administration of the Web Apps, not the authorization to features it exposes. To use roles programmatically, I suggest that you look at the following sample which explains how to setup the roles in the Azure AD application corresponding to the project that you deployed as a Web App. https://github.com/Azure-Samples/active-directory-dotnet-webapp-roleclaims

This way you'll be able to protect pages (from the code in the controller) using attributes: ``

    [Authorize(Roles = "Admin, Observer, Writer, Approver")]

See https://github.com/Azure-Samples/active-directory-dotnet-webapp-roleclaims/blob/master/WebApp-RoleClaims-DotNet/Controllers/TasksController.cs#L17

You can also test for users having given roles: if (User.IsInRole("Admin") || User.IsInRole("Writer")) { ... }

Upvotes: 1

Related Questions