[英]HttpContext.Current.User.Identity.Name Alternative for Non-Windows User?
我向 Azure 部署了一個應用程序。具有 Windows 帳戶的內部用戶在導航到該應用程序時會自動登錄。 外部用戶需要輸入用戶名和密碼才能登錄應用程序。 他們的用戶名是一個 email 地址,其域名與內部用戶使用的域名不同。
我使用HttpContext.Current.User.Identity.Name
來設置CreatedBy
和ModifiedBy
值。 我還在視圖中使用@User.Identity.Name
來顯示問候語。 這兩個都不顯示具有非 Windows 帳戶的外部用戶的值。
非 Windows 帳戶獲取這些值的替代選項是什么?
啟動.Auth.cs
public partial class Startup
{
public void ConfigureAuth(IAppBuilder app)
{
var clientId = ConfigurationManager.AppSettings["ida:ClientId"];
var aADInstance = ConfigurationManager.AppSettings["ida:AADInstance"];
var tenantId = ConfigurationManager.AppSettings["ida:TenantId"];
var postLogoutRedirectUri = ConfigurationManager.AppSettings["ida:PostLogoutRedirectUri"];
var authority = string.Format(CultureInfo.InvariantCulture, aADInstance, tenantId);
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = "Cookies",
CookieManager = new SystemWebChunkingCookieManager()
});
app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions
{
ClientId = clientId,
Authority = authority,
PostLogoutRedirectUri = postLogoutRedirectUri,
TokenValidationParameters = new TokenValidationParameters
{
NameClaimType = ClaimTypes.Upn,
RoleClaimType = ClaimTypes.Role
},
Notifications = new OpenIdConnectAuthenticationNotifications
{
AuthenticationFailed = context =>
{
context.HandleResponse();
context.Response.Redirect("/");
return Task.FromResult(0);
}
}
}
);
}
}
我嘗試查看HttpContext.Current.User.Identity.Name
是否有其他選項來獲取所需的值,例如在Identity
之后和User
之后。 我還檢查了活動目錄用戶配置文件是否有任何缺失值,例如 email 地址或名稱。
在ASP.NET Core中,可以通過HttpContext class上的User屬性獲取當前用戶的身份信息。
而 HttpContext.Current 屬性在 ASP.NET Core 中不可用。 相反,您可以使用依賴項注入來獲取 IHttpContextAccessor 接口的實例,並使用它來訪問當前的 HttpContext。
public class HomeController : Controller
{
private readonly IHttpContextAccessor _contextAccessor;
public HomeController(IHttpContextAccessor contextAccessor)
{
_contextAccessor = contextAccessor;
}
public IActionResult Index()
{
var userName = _contextAccessor.HttpContext.User.Identity.Name;
if (string.IsNullOrEmpty(userName) && _contextAccessor.HttpContext.User.Identity.IsAuthenticated)
{
userName = _contextAccessor.HttpContext.User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Email)?.Value;
}
return View(userName);
}
}
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.LoginPath = new PathString("/Account/Login");
options.AccessDeniedPath = new PathString("/Account/AccessDenied");
});
}
在 startup.cs class 中,在 configure 方法中,為內部和外部用戶使用 UseWindowsAuthentication 和 UseCookieAuthentication。
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.Use(async (context, next) =>
{
if (context.User.Identity.IsAuthenticated && context.User.Identity.AuthenticationType == "NTLM")
{
var email = context.User.Identity.Name;
if (!email.EndsWith("@internal-domain.com"))
{
await context.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
context.Response.Redirect("/Account/Login");
return;
}
}
await next();
});
app.UseWindowsAuthentication();
app.UseCookieAuthentication();
}
創建處理外部用戶登錄的登錄操作方法:
[HttpPost]
public async Task<IActionResult> Login(LoginViewModel model)
{
if (ModelState.IsValid)
{
if (IsValidUser(model.Email, model.Password))
{
if (!model.Email.EndsWith("@internal-domain.com"))
{
var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
identity.AddClaim(new Claim(ClaimTypes.Name, model.Email));
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity));
return RedirectToAction("Index", "Home");
}
else
{
ModelState.AddModelError("", "Invalid UserName.");
}
}
else
{
ModelState.AddModelError("", "Invalid password.");
}
}
return View(model);
}
private bool IsValidUser(string email, string password)
{
// check with DB to compare the credentials.
return true;
}
我使用 HttpContext.Current.User.Identity.Name 來設置 CreatedBy 和 ModifiedBy 值。 我還在視圖中使用@User.Identity.Name 來顯示問候語。 這兩個都不顯示具有非 Windows 帳戶的外部用戶的值。
在視圖中,您可以使用以下代碼來檢查用戶是否已通過身份驗證。
@if (User.Identity.IsAuthenticated)
{
<text>Welcome, @User.Identity.Name</text>
}
else
{
<text>Welcome, User</text>
}
Windows 登錄:
參考: Forms 和 Windows 身份驗證感謝@mvolo 的博客。
對於這個問題,我將NameClaimType = ClaimTypes.Upn
更新為NameClaimType = ClaimTypes.Name
。
我首先選擇了Upn
而不是Name
,因為根據他們的描述, Upn
似乎更“獨特”。
我與外部用戶確認現在顯示了用戶名。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.