在ASP .net CORE mvc中构建内联网,我需要获取当前用户的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 属性。匿名网站访问仍然是可能的。
launchSettings.json
"iisSettings": {
"windowsAuthentication": true,
"anonymousAuthentication": false,
"iisExpress": {
"applicationUrl": "http://localhost:53321",
"sslPort": 44320
}
}
然后,您可以使用以下代码从控制器获取用户的 Windows 用户名。
HomeController.cs
public IActionResult Index()
{
string userName = HttpContext.User.Identity.Name;
return View(userName);
}
依赖注入
如果您想在启动脚本或存储库中访问 Windows 用户名,那么您可以依赖注入 HttpContextAccessor,这将允许访问 User 对象。更多详细信息可以在这里找到。
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/
程序.cs
builder.Services.AddAuthentication(NegotiateDefaults.AuthenticationScheme)
.AddNegotiate();
builder.Services.AddAuthorization(options =>
{
// By default, all incoming requests will be authorized according to the default policy.
options.FallbackPolicy = options.DefaultPolicy;
});
app.UseAuthentication();
app.UseAuthorization();
家庭控制器
string userName = HttpContext.User.Identity.Name;