如何在 Azure 静态 Web 应用程序的 API(Azure 函数)中获取当前用户的角色

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

我想调用 api 并在函数中根据用户的角色决定 show/return 的信息级别。 有人可以提供有关如何在 Azure 静态 Web 应用程序上的 Azure 函数中获取已登录用户角色的示例吗?

通过“Function App”部署Azure Function时,我可以获得角色和当前用户名,但是通过“Static Web App”我还没有搞清楚。

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);
        }
    }
}

您可以这样访问,

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);
        }

这是一个sample