我正在將 .NET 4.8 應用程式遷移到 .NET Core。當前應用運行在 Azure 上,使用微軟作為身份提供者進行身份驗證(在 azure 應用的身份驗證頁面上設定,代碼中沒有任何內容,見下圖),以便 Azure AD 中的任何用戶都可以訪問它。身份驗證作業正常,當您尚未使用 Azure AD 帳戶登錄時,您將重定向到 login.microsoftonline.com 頁面。

該應用程式包含一段在 .NET 4.8 中始終有效的簡單代碼
@if (Request.IsAuthenticated)
{
<strong>@User.Identity.Name</strong>
}
else
{
<div><i>Not logged in</i></div>
}
(開發者也可以在本地使用這個應用,這樣就不需要認證了)
我現在準備在 Azure 上測驗新應用程式,但我看到 User.Identity 沒有填充,我附加了一個遠程除錯器并看到所有屬性都是空的(沒有宣告,一個具有默認值的標識)。我發現許多主題也報告了這個問題,但其中大多數已經使用了一些代碼。我想我可能遺漏了一些啟動代碼,但我無法弄清楚它是什么。目前我有
// ConfigureServices
services.AddAuthentication();
services.Configure<IdentityOptions>(options =>
options.ClaimsIdentity.UserIdClaimType = ClaimTypes.NameIdentifier); // found this somewhere as solution, but didn't work so it's probably not required
// Configure
app.UseAuthentication();
app.UseAuthorization();
所以總結一下:
- 在 Azure 門戶中設定了 Microsoft 身份提供程式 (Azure AD) 的 Azure Web 應用在 .NET 4.8 (MVC5) 中運行良好
- 相同的應用程式,相同的設定,但遷移到 .NET Core 不再設定 User.Identity 屬性
uj5u.com熱心網友回復:
經過更多的挖掘,我發現這篇文章有同樣的問題。所以事實證明它是由以不同方式作業的 ASP.NET Core 引起的。其中一個答案包含一段解決問題的代碼,我用它來創建一個新的簡單中間件:
public static class AzureAuthExtensions
{
/// <summary>
/// Enables support for Azure EasyAuth, so that User.Identity.Name is populated correctly.
/// </summary>
public static IApplicationBuilder UseAzureEasyAuth(this IApplicationBuilder app)
{
if (app == null)
{
throw new ArgumentNullException(nameof(app));
}
return app.UseMiddleware<AzureEasyAuthMiddleware>();
}
}
public class AzureEasyAuthMiddleware
{
private readonly RequestDelegate _next;
public AzureEasyAuthMiddleware(RequestDelegate next)
{
_next = next ?? throw new ArgumentNullException(nameof(next));
}
/// <summary>
/// Invoke the middleware.
/// </summary>
/// <param name="context">The <see cref="HttpContext"/>.</param>
public Task Invoke(HttpContext context)
{
// 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];
// Create claims id
var claims = new Claim[] {
new System.Security.Claims.Claim("http://schemas.microsoft.com/identity/claims/objectidentifier", azureAppServicePrincipalIdHeader),
new System.Security.Claims.Claim("name", azureAppServicePrincipalNameHeader)
};
// Set user in current context as claims principal
var identity = new GenericIdentity(azureAppServicePrincipalNameHeader);
identity.AddClaims(claims);
// Set current thread user to identity
context.User = new GenericPrincipal(identity, null);
};
return _next(context);
}
}
這就像一個魅力!
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/409266.html
標籤:
上一篇:托管BlazorWebassembly和非托管BlazorWebassembly之間的請求標頭“Referer”不同
下一篇:.NETCore6中的連接字串
