0

我想调用 api 并在函数处根据用户的角色决定显示/返回的信息级别。有人可以提供有关如何在 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);
        }
    }
}
4

1 回答 1

1

你可以这样访问,

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

这是一个示例

于 2021-06-09T04:18:49.553 回答