C# ASP.NET Core 3.0中UPN的Active Directory身份验证
我正在尝试在ASP.NET Core 3.0 Web应用程序中设置身份验证和授权。用户必须能够使用其用户主体名称和密码进行身份验证。然后,我需要检索他们的组成员身份,以确定他们的角色 我在各种来源中找到了一些文章,建议使用Microsoft.Windows.Compatibility NuGet包。然而,我不知道如何“粘合”所有这些 我的主要参考点是这个问题: 我的三个主要问题是:C# ASP.NET Core 3.0中UPN的Active Directory身份验证,c#,asp.net-core,active-directory,C#,Asp.net Core,Active Directory,我正在尝试在ASP.NET Core 3.0 Web应用程序中设置身份验证和授权。用户必须能够使用其用户主体名称和密码进行身份验证。然后,我需要检索他们的组成员身份,以确定他们的角色 我在各种来源中找到了一些文章,建议使用Microsoft.Windows.Compatibility NuGet包。然而,我不知道如何“粘合”所有这些 我的主要参考点是这个问题: 我的三个主要问题是: 身份验证代码在代码结构中位于何处?单独的名称空间、类等 如何在ConfigureServices方法中配置此项
- 身份验证代码在代码结构中位于何处?单独的名称空间、类等
- 如何在ConfigureServices方法中配置此项
- 这一切如何融入ASP身份验证/授权结构
谢谢你的广告认证,你可以试试 要将AD身份验证与Asp.Net Core结合使用,可以将
CookieAuthentication
和Novell.Directory.Ldap.NETStandard
结合使用
您可以按照以下步骤操作:
Version=“3.0.0-beta5”
iaauthenticationservice
和ldapaauthenticationservice
public class LdapAuthenticationService : IAuthenticationService
{
public bool ValidateUser(string domainName, string username, string password)
{
string userDn = $"{username}@{domainName}";
try
{
using (var connection = new LdapConnection { SecureSocketLayer = false })
{
connection.Connect(domainName, LdapConnection.DefaultPort);
connection.Bind(userDn, password);
if (connection.Bound)
return true;
}
}
catch (LdapException ex)
{
// Log exception
}
return false;
}
}
public interface IAuthenticationService
{
bool ValidateUser(string domainName, string username, string password);
}
Startup.cs中配置
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddScoped<IAuthenticationService, LdapAuthenticationService>();
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
}
这一选择正在发挥作用。我还找到了另一个选项,这里有代码。然而,这是针对Asp.NETCore2.0的 我已将其更新为在Asp.NETCore3.0上运行,并在GitHub上发布了我的代码。它目前还使用Novell库。我不保证它是完美的,但希望它也能帮助其他人
代码示例显示了正常运行的LDAP身份验证,然后提取已验证用户的组成员身份,以构造一组可用于身份验证的角色和声明。您不使用的任何原因(这将为intranet用户自动登录-无需键入凭据)是,不能保证客户端使用的是Windows,而且需要不依赖弹出窗口,而是基于表单的身份验证。这很公平。不幸的是,我帮不了多少忙,因为我还没有在ASP.NET内核中完成这项工作。(我在旧式的ASP.NET中做过)我对.NET相当陌生。因此,虽然我可以按照您的示例进行操作,但我不太确定步骤2中的代码放在哪里。启动时,它似乎不属于控制器的一部分。感谢您的帮助和指导。
public class AccountController : Controller
{
private readonly IAuthenticationService _authenticationService;
public AccountController(IAuthenticationService authenticationService)
{
_authenticationService = authenticationService;
}
public IActionResult Login()
{
return View();
}
[HttpPost]
public async Task<IActionResult> Login(LoginModel model)
{
var result = _authenticationService.ValidateUser("xx.com",model.UserName, model.Password);
if (result)
{
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, model.UserName),
new Claim(ClaimTypes.Role, "Administrator"),
};
var claimsIdentity = new ClaimsIdentity(
claims, CookieAuthenticationDefaults.AuthenticationScheme);
var authProperties = new AuthenticationProperties
{
//AllowRefresh = <bool>,
// Refreshing the authentication session should be allowed.
//ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(10),
// The time at which the authentication ticket expires. A
// value set here overrides the ExpireTimeSpan option of
// CookieAuthenticationOptions set with AddCookie.
//IsPersistent = true,
// Whether the authentication session is persisted across
// multiple requests. When used with cookies, controls
// whether the cookie's lifetime is absolute (matching the
// lifetime of the authentication ticket) or session-based.
//IssuedUtc = <DateTimeOffset>,
// The time at which the authentication ticket was issued.
//RedirectUri = <string>
// The full path or absolute URI to be used as an http
// redirect response value.
};
await HttpContext.SignInAsync(
CookieAuthenticationDefaults.AuthenticationScheme,
new ClaimsPrincipal(claimsIdentity),
authProperties);
}
return Ok();
}
public IActionResult Index()
{
var user = HttpContext.User.Identity.Name;
return View();
}
}
public class LoginModel
{
public string UserName { get; set; }
public string Password { get; set; }
}