ASP. NET Базовая аутентификация LDAP Active Directory - PullRequest
0 голосов
/ 06 мая 2020

Как я могу реализовать аутентификацию LDAP в ASP. NET Core?

Я хочу создать аутентификацию ldap, но не уверен насчет своего кода - любая помощь, пожалуйста.

Я создал приложение ASP. NET Core 2.0, и когда я пытаюсь получить ответ, возникает ошибка, и я не знаю, как решить эту проблему.

Мой код:

public interface IAuthenticationService
{
    bool ValidateUser(string username, string password);
}

public class LdapAuthenticationService : IAuthenticationService
{
    public static bool ValidateUser(string username, string password)
    {
        Dictionary<string, object> properties;
        string _path = string.Format("LDAP://{0}", "ADSLOCAL");
        string _filterAttribute;

        DirectoryEntry entry = new DirectoryEntry(_path, username, password);
        properties = new Dictionary<string, object>();

        try
        {
            //Bind to the native AdsObject to force authentication.
            object obj = entry.NativeObject;

            if (obj != null)
            {
                DirectorySearcher search = new DirectorySearcher(entry);
                search.Filter = "(SAMAccountName=" + username + ")";
                search.PropertiesToLoad.Add("cn");
                search.PropertiesToLoad.Add("givenName");
                search.PropertiesToLoad.Add("sn");

                SearchResult result = search.FindOne();

                if (result == null)
                {
                    return false;
                }
                else
                {
                    if (result.Properties["sn"].Count != 0) 
                        properties.Add("FirstName", result.Properties["sn"][0]);
                    if (result.Properties["givenName"].Count != 0) 
                        properties.Add("LastName", result.Properties["givenName"][0]);
                }

                // Update the new path to the user in the directory.
                _path = result.Path;
                _filterAttribute = (string)result.Properties["cn"][0];
            }
            else
            {
                return false;
            }
        }
        catch (Exception ex)
        {
            throw new Exception("err:" + ex.Message);
        }

        return true;
    }
}

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.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.Configure<ApplicationSettings>(Configuration.GetSection("ApplicationSettings"));
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            services.AddScoped<IAuthenticationService,LdapAuthenticationService>();
            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
                    .AddCookie();
            services.AddCors();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
           app.Use(async (ctx,next)=>
           {
               await next();
               if (ctx.Response.StatusCode == 204)
               {
                   ctx.Response.ContentLength = 0;
               }
           });
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseCors(builder =>
            builder.WithOrigins(Configuration["ApplicationSettings:Client_URL"].ToString())
            .AllowAnyHeader()
            .AllowAnyMethod()
            );
            app.UseAuthentication();
            app.UseMvc();
        }
    }
}

[HttpPost]
[Route("Login")]
public async Task<IActionResult> Login(LoginModel model)
{
    bool result = LdapAuthenticationService.ValidateUser(model.UserName, model.Password);

    if (result)
    {
        var claims = new List<Claim>
            {
                new Claim(ClaimTypes.Name, model.UserName),
            };

        var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
        var authProperties = new AuthenticationProperties {};

        await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,
                        new ClaimsPrincipal(claimsIdentity), authProperties);
    }

    return Ok();
}
...