По сути, я пытаюсь создать пользователя в своем приложении .NET с помощью C# и пространства имен System.DirectoryServices.AccountManagement.
Моя проблема в том, что я получаю аутентификацию ошибка при установке атрибута нового пользователя, которого я пытаюсь создать. И я на 1000% уверен, что это правильные учетные данные, а также правильные разрешения.
Мой файл с логикой для нового пользователя в AD:
using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;
using System;
using System.Diagnostics;
namespace guest_register.Services
{
public class ActiveDirectoryServices
{
private readonly string _domainName;
private readonly string _ldapPath;
private readonly string _adminUser;
private readonly string _adminPassword;
public ActiveDirectoryServices(string ldapPath, string domainName,string adminUser, string adminPassword)
{
_domainName = domainName;
_ldapPath = ldapPath;
_adminUser = adminUser;
_adminPassword = adminPassword;
}
public void createGuest(string userName, string password)
{
try
{
Debug.WriteLine($"Connecting to LDAP path: {_ldapPath} with user: {_adminUser}");
using (PrincipalContext context = new PrincipalContext(ContextType.Domain, _domainName, _ldapPath, _adminUser, _adminPassword))
{
Debug.WriteLine("Connected to LDAP successfully.");
using (UserPrincipal userPrin = new UserPrincipal(context))
{
Debug.WriteLine("Created a UserPrincipal");
// Set properties for the user
userPrin.SamAccountName = userName;
userPrin.SetPassword(password);
userPrin.Enabled = true;
// You can set other properties as needed
userPrin.Save();
Debug.WriteLine("Successfully created user");
}
}
}
catch (PrincipalOperationException pex)
{
Debug.WriteLine($"Message pex: {pex.Message}");
}
catch (Exception ex)
{
throw new Exception(ex.StackTrace);
}
}
}
}
Вот как я запускаю эту службу:
using guest_register.Services;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddScoped(sp => new ActiveDirectoryServices("DC=radius,DC=internal", "192.168.45.130", "demo", "test-123"));
// Add services to the container.
builder.Services.AddControllersWithViews();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
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.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
И фрагмент файла, который вызывает функции для создания пользователя:
try
{
_adService.createGuest("test-123", "test-123");
return Ok("User created successfully");
}
Кто-нибудь знает, что происходит не так?
Я пытался возиться с учетными данными, а также с разрешениями. У меня также был установлен ContextOptions в PrincipalContext, но это тоже не помогло.
Я не смог найти никаких ресурсов, поскольку это не помогло, как и большинство руководств. просто вообще не использовал учетные данные...
Изменить:
Connecting to LDAP path: DC=radius,DC=internal with user: demo
'guest-register.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\6.0.26\System.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'guest-register.exe' (CoreCLR: clrhost): Loaded 'D:\coding\guest-register\guest-register\bin\Debug\net6.0\runtimes\win\lib\net6.0\System.DirectoryServices.Protocols.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'guest-register.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\6.0.26\System.Xml.ReaderWriter.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
Connected to LDAP successfully.
'guest-register.exe' (CoreCLR: clrhost): Loaded 'D:\coding\guest-register\guest-register\bin\Debug\net6.0\runtimes\win\lib\net6.0\System.DirectoryServices.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
Exception thrown: 'System.Security.Authentication.AuthenticationException' in System.DirectoryServices.AccountManagement.dll
Debugging:
'guest-register.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\6.0.26\System.Diagnostics.StackTrace.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'guest-register.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\6.0.26\System.Reflection.Metadata.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'guest-register.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\6.0.26\System.Collections.Immutable.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
Exception thrown: 'System.Exception' in guest-register.dll
Подробнее здесь: https://stackoverflow.com/questions/785 ... ng-c-sharp
Создайте пользователя в Active Directory в ASP.NET, используя C#. ⇐ C#
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение
-
-
Как я могу найти как фамилию пользователя, так и имя в Active Directory, используя C#
Anonymous » » в форуме C# - 0 Ответы
- 8 Просмотры
-
Последнее сообщение Anonymous
-