[英]Asp net Core Get user Windows username
在 ASP .net CORE mvc 中構建 Intranet,我需要獲取當前用戶的 Windows 用戶名進行登錄,我不需要使用 Windows 身份驗證自動登錄用戶,我已經有一個自定義登錄控制器來做到這一點,我只需要他的用戶名。
它在本地運行良好,但在 IIS 服務器上無法獲取用戶名:
當地的 :
Environment.UserName => VeronY
System.Security.Principal.WindowsIdentity.GetCurrent().Name => Domain\VeronY
IIS服務器:
Environment.UserName => Intranet
System.Security.Principal.WindowsIdentity.GetCurrent().Name => APPPOOL\Intranet
使用 Windows 身份驗證它會自動登錄我,這不是我需要的。 必須有 2 種類型的身份驗證:自動使用 AD 和手動使用身份框架管理表單。
ASP .net 似乎沒有授權 2 種不同類型的連接,所以我讓主站點使用表單身份驗證,並創建了一個小 API:
[Authorize]
[Route("api/[controller]")]
public class ValuesController : Controller
{
[HttpGet]
public ActionResult Get()
{
return Json(User.Identity.Name);
}
}
使用 Windows 身份驗證進行配置。
這是主網站中的 LoginController :
String responseString = "";
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://myapiURL");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = client.GetAsync("api/values").Result;
if (response.IsSuccessStatusCode)
{
responseString = response.Content.ReadAsStringAsync().Result;
responseString = Regex.Unescape(responseString).Replace("\"","");//Because the response is something like \\"Domaine\\\\Username\"\
}
else
{
return View();//server cannot be found or Windows authentication fail => form Login
}
}
String username = "";
String domain = "";
if (responseString != "" && responseString.Contains("\\"))
{
domain = responseString.Split('\\')[0];
username = responseString.Split("\\")[1];
if(domain !="MYDOMAIN")
{
return View();//Not in the correct domain => form Login
}
}
else
{
return View();//Not the correct response => form Login
}
UserPrincipal user = UserPrincipal.FindByIdentity(new PrincipalContext(ContextType.Domain), username);
if (null != user)
{
CustomAutomaticLogin(user)//All seems ok, try to log the user with custom login with AD informations
}
else
{
return View()//Not in AD => form login
}
}
在 ASP .NET Core 中獲取 Windows 用戶名
首先更新launchSettings.json 文件中的windowsAuthentication 和anonymousAuthentication 屬性。 匿名站點訪問仍然是可能的。
啟動設置.json
"iisSettings": {
"windowsAuthentication": true,
"anonymousAuthentication": false,
"iisExpress": {
"applicationUrl": "http://localhost:53321",
"sslPort": 44320
}
}
然后,您可以使用以下代碼從控制器獲取用戶 Windows 用戶名。
家庭控制器.cs
public IActionResult Index()
{
string userName = HttpContext.User.Identity.Name;
return View(userName);
}
依賴注入
如果您想在啟動腳本或存儲庫中訪問 Windows 用戶名,那么您可以依賴注入 HttpContextAccessor,這將允許訪問用戶對象。 可以在此處找到更多詳細信息。
public virtual void ConfigureServices(IServiceCollection services)
{
services.AddHttpContextAccessor();
services.AddControllers();
}
https://blog.bitscry.com/2020/05/05/getting-the-windows-user-name-in-asp-net-core/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.