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

标签 azure azure-static-web-app

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

最佳答案

您可以这样访问,

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

关于azure - 如何在 Azure 静态 Web 应用上的 API(Azure 函数)中获取当前用户的角色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67896692/

相关文章:

azure - SvelteKit 应用程序未在 Azure Web Static App 中上传

Azure SWA : redirect to modified version of requested route?

linux - 如何访问Azure中Linux服务器上的网站?

azure - 使用 Azure CLI 从资源组中仅获取可用资源列表

sql-server - Azure SQL 报告的本地化

azure - Azure 静态 Web 应用中预览环境的自定义域?

azure - 如何在azure静态Web应用程序中配置角色管理

azure - 通过 Bicep 为 StaticWebApp 创建 AppInsights 实例

c# - Microsoft azure 中的角色未记录到 WADLogsTable

c# - Azure 移动服务 - Facebook 注销