eduardogoncalves
eduardogoncalves

Reputation: 173

How to get current user's roles in API (Azure Function) on Azure Static Web Apps

I want to call the api and at the function decides what level of info to show/return based on user's roles. Can someone give a sample on how to get logged user's roles in Azure Function on Azure Static Web App?

When deploying Azure Function via "Function App", I can get the roles and current username, but with "Static Web App" I haven't figured it out yet.

namespace Function1
{
    public class Function1
    {
        [FunctionName("Function1")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
            ClaimsPrincipal principal)
        {

            IEnumerable<string> roles = principal.Claims.Where(e => e.Type.Equals("roles")).Select(e => e.Value);

            string name = principal.Identity.Name;

            string responseMessage = $"Hello, {name}. This HTTP triggered function executed successfully. {string.Join(',', roles)}";

            return new OkObjectResult(responseMessage);
        }
    }
}

Upvotes: 0

Views: 954

Answers (1)

Sajeetharan
Sajeetharan

Reputation: 222722

You can access like this,

public static ClaimsPrincipal Parse(HttpRequest req)
        {
            var header = req.Headers["x-ms-client-principal"];
            var data = header.FirstOrDefault();
            if(data == null) {
                return null;
            }
            
            var decoded = System.Convert.FromBase64String(data);
            var json = System.Text.ASCIIEncoding.ASCII.GetString(decoded);
            var principal = JsonSerializer.Deserialize<ClientPrincipal>(json, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });

            principal.UserRoles = principal.UserRoles.Except(new string[] { "anonymous" }, StringComparer.CurrentCultureIgnoreCase);

            if (!principal.UserRoles.Any())
            {
                return new ClaimsPrincipal();
            }

            var identity = new ClaimsIdentity(principal.IdentityProvider);
            identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, principal.UserId));
            identity.AddClaim(new Claim(ClaimTypes.Name, principal.UserDetails));
            identity.AddClaims(principal.UserRoles.Select(r => new Claim(ClaimTypes.Role, r)));
            return new ClaimsPrincipal(identity);
        }

Here is a sample

Upvotes: 2

Related Questions