在ASP .net CORE mvc中构建内联网,我需要获取当前用户的Windows用户名进行登录,我不需要使用Windows身份验证自动登录用户,我已经有一个自定义登录控制器来做到这一点,我只需要他的用户名。
它在本地工作正常,但在 IIS 服务器上无法获取用户名:
Local :
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
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)