【问题标题】:How to get current user's roles in API (Azure Function) on Azure Static Web Apps如何在 Azure 静态 Web 应用程序的 API(Azure 函数)中获取当前用户的角色
【发布时间】:2021-08-26 00:25:37
【问题描述】:

我想调用 api,并在函数中根据用户的角色决定显示/返回的信息级别。 有人可以举例说明如何在 Azure 静态 Web 应用上的 Azure Function 中获取登录用户的角色吗?

通过“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);
        }
    }
}

【问题讨论】:

    标签: azure azure-static-web-app


    【解决方案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);
            }
    

    这是一个sample

    【讨论】:

      猜你喜欢
      • 2018-02-28
      • 1970-01-01
      • 2021-08-24
      • 2022-12-08
      • 1970-01-01
      • 2016-05-22
      • 2021-04-11
      • 2016-12-03
      • 2021-04-28
      相关资源
      最近更新 更多