Asp-net Core获取用户Windows用户名



在ASP.net CORE mvc中构建intranet,我需要获得当前用户的Windows用户名进行登录,我不需要使用Windows身份验证自动登录用户,我已经有了一个自定义的登录控制器,我只需要他的用户名
它在本地运行良好,但在IIS服务器上无法获取用户名:
本地:

Environment.UserName => VeronY 
System.Security.Principal.WindowsIdentity.GetCurrent().Name => DomainVeronY

IIS服务器:

Environment.UserName => Intranet
System.Security.Principal.WindowsIdentity.GetCurrent().Name => APPPOOLIntranet 

使用Windows身份验证,它会自动登录我,这不是我需要的。必须有两种类型的身份验证:AD自动身份验证和Identity Framework表单管理手动身份验证。

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/

相关内容

  • 没有找到相关文章