ASP.Net Core可以与集成的Windows身份验证进行集成,使用Windows身份验证可以使用Windows操作系统的凭据来认证用户。下面是一个使用ASP.Net Core和集成的Windows身份验证的代码示例:
Startup.cs
文件中的ConfigureServices
方法中进行配置:public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(IISDefaults.AuthenticationScheme);
services.AddAuthorization();
// 添加其他的服务配置
}
[Authorize]
特性,以确保用户必须经过验证才能访问:[Authorize]
public IActionResult Index()
{
// 执行需要验证的操作
return View();
}
HttpContext
对象,并使用User.Identity.Name
属性来获取用户的Windows用户名:public class HomeController : Controller
{
private readonly IHttpContextAccessor _httpContextAccessor;
public HomeController(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
public IActionResult Index()
{
string windowsUserName = _httpContextAccessor.HttpContext.User.Identity.Name;
// 使用用户的Windows用户名进行操作
return View();
}
}
这样,当用户访问带有[Authorize]
特性的方法时,ASP.Net Core会自动进行Windows身份验证,并提供用户的身份信息。