![](/img/trans.png)
[英]Asp.Net core Web Application with IdentityServer4 and Identity both
[英]How to get the CurrentPrincipal Identity on ASP.Net Core 2 Web Application?
我創建了一個Azure AD B2C租戶以與Azure Function一起使用。 我用這個,它正在工作:
Thread.CurrentPrincipal.Identity.IsAuthenticated
現在,我嘗試使用戶登錄,並在ASP Net Core 2網站Razor頁面Index.cshtml.cs中以同樣的方式調用該用戶。
public void OnGet()
{
var isAuth = Thread.CurrentPrincipal.Identity.IsAuthenticated;
ClaimsPrincipal cp = (ClaimsPrincipal)Thread.CurrentPrincipal;
}
但是Thread.CurrentPrincipal在ASP Net Core 2上返回null
在Startup.cs上的ConfigureServices方法中,我添加了
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
//services.AddAuthentication();
services.AddAuthentication(options =>
{
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.RequireHttpsMetadata = false;
options.Audience = Configuration["Authentication:AzureAd:ClientId"];
//options.Events = new JwtBearerEvents
//{
// OnAuthenticationFailed = AuthenticationFailed
//};
var authorityBase = string.Format("https://login.microsoftonline.com/tfp/{0}/", "empresateste123.onmicrosoft.com"/*Configuration["Authentication:AzureAd:Tenant"]*/);
options.Authority = string.Format("{0}{1}/v2.0/", authorityBase, "B2C_1_policysignin " /*Configuration["Authentication:AzureAd:Policy"]*/);
});
}
在Startup.cs的 Configure方法中,我添加了
app.UseAuthentication();
當我發布並轉到URL時,此行發生此異常:
An unhandled exception occurred while processing the request.
NullReferenceException: Object reference not set to an instance of an object.
如果我用
public void OnGet()
{
//var isAuth = Thread.CurrentPrincipal.Identity.IsAuthenticated;
//ClaimsPrincipal cp = (ClaimsPrincipal)Thread.CurrentPrincipal;
var u = this.User;
var uc = u.Claims.ToList();
}
現在來了,但是Claims.Count = 0,沒有用戶信息
我還需要添加什么才能使其正常工作?
使用PageModel.User
返回代表當前Web應用程序用戶的ClaimsPrincipal
對象。 不應使用Thread.CurrentPrincipal
來獲取當前的Web應用程序用戶,因為Thread.CurrentPrincipal
涉及由.NET(可能還有操作系統)管理的線程安全性。
ASP.NET早在2001年成立之初(ab)便通過使用當前的ASP.NET“用戶”覆蓋Thread.CurrentPrincipal
使用.NET的此功能-在Identity上下文中使用它時具有實際好處具有Windows身份驗證的模擬功能,允許Web應用程序訪問安全受限的文件,網絡資源和操作系統功能,否則將無法訪問。
2004年以來的這篇文章給出了很好的解釋(忽略對現已過時的FormsAuthentication
模塊的引用): https : Thread.CurrentPrincipal
本文還解釋了為什么Thread.CurrentPrincipal
可能為null
原因在調用HttpApplication.OnThreadEnter()
(設置CurrentPrincipal
屬性)之前調用應用程序代碼時。
我不太熟悉Razor-Pages的生命周期(自2017年末以來ASP.NET Core中的一項新功能),或者該安全系統如何在Azure Functions和Azure AppService(fka Azure網站)上下文中發生變化。
無論如何,解決方法是始終使用ASP.NET中的User
屬性而不是Thread.CurrentPrincipal
。
System.Web.HttpContext::User
(或System.Web.UI.Page::User
) System.Web.Mvc.Controller::User
.aspx
視圖時)可以使用System.Web.Mvc.ViewPage::User
System.Web.WebPages.WebPageRenderingBase::User
繼承)訪問@this.User
(或僅@User
)。 Microsoft.AspNetCore.Mvc.ControllerBase::User
。 Microsoft.AspNetCore.Mvc.RazorPages.PageModel::User
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.