我想编写一些ASP .NET Core中间件来将Azure Apps EasyAuth HTTP标头转换为声明.我找到了两种方法:
>解析EasyAuth在HTTP标头中提供的令牌.这似乎不是一个通用的解决方案,因为我必须编写代码来解析每个身份提供者的令牌.
>向/.auth/me提出服务器端请求.这会返回一些我想要转换为声明的JSON,但我不确定是否必须手动执行此操作或者是否有框架支持.
解决方法
根据你的描述,我发现了类似的
issue.据我所知,目前没有任何框架可供你实现.根据我的理解,如果您希望在使用Azure App Service EasyAuth时检索所有声明,我假设您最好向内置端点/.auth/me发出服务器端请求以检索声明,如下所示:
Startup.cs>配置
app.Use(async (context,next) => { // Create a user on current thread from provided header if (context.Request.Headers.ContainsKey("X-MS-CLIENT-PRINCIPAL-ID")) { // Read headers from Azure var azureAppServicePrincipalIdHeader = context.Request.Headers["X-MS-CLIENT-PRINCIPAL-ID"][0]; var azureAppServicePrincipalNameHeader = context.Request.Headers["X-MS-CLIENT-PRINCIPAL-NAME"][0]; #region extract claims via call /.auth/me //invoke /.auth/me var cookieContainer = new CookieContainer(); HttpClientHandler handler = new HttpClientHandler() { CookieContainer = cookieContainer }; string uriString = $"{context.Request.Scheme}://{context.Request.Host}"; foreach (var c in context.Request.Cookies) { cookieContainer.Add(new Uri(uriString),new Cookie(c.Key,c.Value)); } string jsonResult = string.Empty; using (HttpClient client = new HttpClient(handler)) { var res = await client.GetAsync($"{uriString}/.auth/me"); jsonResult = await res.Content.ReadAsStringAsync(); } //parse json var obj = JArray.Parse(jsonResult); string user_id = obj[0]["user_id"].Value<string>(); //user_id // Create claims id List<Claim> claims = new List<Claim>(); foreach (var claim in obj[0]["user_claims"]) { claims.Add(new Claim(claim["typ"].ToString(),claim["val"].ToString())); } // Set user in current context as claims principal var identity = new GenericIdentity(azureAppServicePrincipalIdHeader); identity.AddClaims(claims); #endregion // Set current thread user to identity context.User = new GenericPrincipal(identity,null); }; await next.Invoke(); });