如何获取经过身份验证的用户信息 dotnet core web api?

问题描述 投票:0回答:1

我正在创建一个 dotnet core Web 应用程序。我想获取没有登录的用户,但是获取Ldap用户信息。他们通过 Active Directory 用户信息登录 Windows 或 Mac 计算机。那么我可以在我的 dotnet core 应用程序中获取操作系统用户信息作为身份吗? dotnet 核心应用程序托管在 docker 容器中。

c# .net asp.net-core ldap
1个回答
0
投票

在 Docker 容器中托管的 .NET Core Web 应用程序中,您无法直接访问访问应用程序的客户端计算机的操作系统用户信息。但是,您可以在应用程序中实施 LDAP 身份验证,以根据 Active Directory 对用户进行身份验证。

以下是如何实现这一目标的总体概述:

LDAP 身份验证:在 .NET Core 应用程序中实现 LDAP 身份验证,以根据 Active Directory 对用户进行身份验证。您可以使用 Novell.Directory.Ldap.NETStandard 或 System.DirectoryServices.Protocols 等库进行 LDAP 身份验证。

检索 LDAP 用户信息:用户通过 LDAP 进行身份验证后,您可以检索其 LDAP 用户信息,例如用户名、电子邮件、组等。此信息可用于创建用户会话、填充用户配置文件或授予对某些特定用户的访问权限。您的应用程序中的资源。

Docker 配置:确保您的 Docker 容器可以通过网络访问您的 Active Directory 服务器。您可能需要在 Docker 环境中配置网络以允许与 LDAP 服务器通信。

处理授权:对用户进行身份验证后,您可以在应用程序中实现授权逻辑,以确定允许经过身份验证的用户访问哪些资源或操作。

以下是如何在 .NET Core 应用程序中实现 LDAP 身份验证的简化示例:

// Install Novell.Directory.Ldap.NETStandard package via NuGet

using Novell.Directory.Ldap;

public class LdapAuthenticationService
{
    private readonly LdapConnection _ldapConnection;

    public LdapAuthenticationService()
    {
        _ldapConnection = new LdapConnection();
        _ldapConnection.Connect("your_ldap_server", 389);
        _ldapConnection.Bind("username", "password");
    }

    public bool AuthenticateUser(string username, string password)
    {
        try
        {
            _ldapConnection.Bind($"CN={username},OU=Users,DC=your_domain,DC=com", password);
            return true;
        }
        catch (LdapException)
        {
            return false;
        }
    }
}

// In your controller or service
public class AuthController : Controller
{
    private readonly LdapAuthenticationService _ldapAuthService;

    public AuthController(LdapAuthenticationService ldapAuthService)
    {
        _ldapAuthService = ldapAuthService;
    }

    [HttpPost]
    public IActionResult Login(string username, string password)
    {
        if (_ldapAuthService.AuthenticateUser(username, password))
        {
            // Authentication successful
            // Generate JWT token or create user session
            return Ok("Authentication successful");
        }
        else
        {
            // Authentication failed
            return Unauthorized("Invalid credentials");
        }
    }
}

这是一个帮助您入门的基本示例。根据您的具体要求和 LDAP 服务器配置,您可能需要相应地调整代码。此外,请确保您安全地处理用户密码并遵循身份验证和授权的最佳实践。

© www.soinside.com 2019 - 2024. All rights reserved.