使用ASP成员资格从LDAP检索用户

时间:2023-01-26 01:40:36

My company is using LDAP to authenticate its users. I have the logging in portion working but now I need a way that once logged in we can refer to the user. I have tried multiple ways and none of them are working.

我的公司正在使用LDAP对其用户进行身份验证。我有登录部分工作但现在我需要一种方式,一旦登录我们可以引用用户。我尝试了多种方式,但没有一种方法可以正常工作。

Here is the code I am using to log in:

这是我用来登录的代码:

var x = Membership.Provider;

if (Membership.ValidateUser(model.UserName, model.Password))
{
    FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);

    if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
    && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
    {
        return Redirect(returnUrl);
    }
    else
    {
        string userId = Membership.GetUser().ProviderUserKey.ToString();
        return RedirectToAction("Index", "Home");
    }
}

On this line:

在这一行:

string userId = Membership.GetUser().ProviderUserKey.ToString();

I am getting an error:

我收到一个错误:

The parameter 'username' must not be empty.

参数'username'不能为空。

I have also tried a few options from here:

我也从这里尝试了几个选项:

How can I access UserId in ASP.NET Membership without using Membership.GetUser()?

如何在不使用Membership.GetUser()的情况下访问ASP.NET成员身份中的UserId?

Like this one:

像这个:

MembershipUser CurrentUser = Membership.GetUser(User.Identity.Name);

which I get the same error

我得到了同样的错误

For anyone wondering, iamtooamazing suggested below:

对于任何想知道的人,iamtooamazing建议如下:

string userId = Membership.GetUser(model.UserName).ProviderUserKey.ToString();

That would work in this method. However, I will not be able to use that anywhere else in the solution. I need something that will work in all the controllers (and methods in them)

这将适用于这种方法。但是,我无法在解决方案的任何其他地方使用它。我需要能在所有控制器中使用的东西(以及它们中的方法)

Using this code:

使用此代码:

string user = ((CustomIdentity)User.Identity).UserId;

I am receiving this error on that line:

我在该行收到此错误:

Unable to cast object of type 'System.Security.Principal.GenericIdentity' to type 'STCAuthentication.Models.CustomIdentity'.

无法将类型为“System.Security.Principal.GenericIdentity”的对象强制转换为“STCAuthentication.Models.CustomIdentity”。

This is the current state of my code:

这是我的代码的当前状态:

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginModel model, string returnUrl)
{
    if (ModelState.IsValid)
    {

        var x = Membership.Provider;
        if (Membership.ValidateUser(model.UserName, model.Password))
        {

            if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
            {
                return Redirect(returnUrl);
            }
            else
            {
                string user = ((CustomIdentity)User.Identity).UserId;
                return RedirectToAction("Index", "Home");
            }
        }
        else
        {
            ModelState.AddModelError("", "The user name or password provided is incorrect.");
        }
    }

    // If we got this far, something failed, redisplay form
    return View(model);
}

1 个解决方案

#1


0  

That would work in this method. However, I will not be able to use that anywhere else in the solution. I need something that will work in all the controllers (and methods in them)

这将适用于这种方法。但是,我无法在解决方案的任何其他地方使用它。我需要能在所有控制器中使用的东西(以及它们中的方法)

What about if you create a custom identity that stores your userid?

如果您创建存储用户ID的自定义标识怎么样?

public class CustomIdentity : IIdentity
{
    private IIdentity Identity { get; set; }
    public string UserId { get; private set; }

    public string AuthenticationType { get { return Identity.AuthenticationType; } }
    public bool IsAuthenticated { get { return Identity.IsAuthenticated; } }
    public string Name { get { return Identity.Name; } }

    public CustomIdentity(IIdentity identity)
    {
        Identity = identity;
        UserId = Membership.GetUser(identity.Name).ProviderUserKey.ToString();
    }
}

Create a CustomPrincipal as well,

创建一个CustomPrincipal,

public class CustomPrincipal : IPrincipal
{
    private IPrincipal Principal;
    public IIdentity Identity { get; private set; }
    public bool IsInRole(string role) { return Principal.IsInRole(role); }

    public CustomPrincipal(IPrincipal principal)
    {
        Principal = principal;
        //this force the load of the userid
        Identity = new CustomIdentity(principal.Identity);
    }
}

Then in Global.asax just set

然后在Global.asax中设置

protected void Application_PreRequestHandlerExecute(object sender, EventArgs e)
{
        if (Request.IsAuthenticated)
        {
            var principal = new CustomPrincipal(HttpContext.Current.User);
            HttpContext.Current.User = principal;
        }
}

And you can access your UserId like this

您可以像这样访问您的UserId

((CustomIdentity)User.Identity).UserId //In Controllers
((CustomIdentity)HttpContext.Current.User.Identity).UserId //Inside classes

Was this what you were looking for?

这是你在寻找什么?

#1


0  

That would work in this method. However, I will not be able to use that anywhere else in the solution. I need something that will work in all the controllers (and methods in them)

这将适用于这种方法。但是,我无法在解决方案的任何其他地方使用它。我需要能在所有控制器中使用的东西(以及它们中的方法)

What about if you create a custom identity that stores your userid?

如果您创建存储用户ID的自定义标识怎么样?

public class CustomIdentity : IIdentity
{
    private IIdentity Identity { get; set; }
    public string UserId { get; private set; }

    public string AuthenticationType { get { return Identity.AuthenticationType; } }
    public bool IsAuthenticated { get { return Identity.IsAuthenticated; } }
    public string Name { get { return Identity.Name; } }

    public CustomIdentity(IIdentity identity)
    {
        Identity = identity;
        UserId = Membership.GetUser(identity.Name).ProviderUserKey.ToString();
    }
}

Create a CustomPrincipal as well,

创建一个CustomPrincipal,

public class CustomPrincipal : IPrincipal
{
    private IPrincipal Principal;
    public IIdentity Identity { get; private set; }
    public bool IsInRole(string role) { return Principal.IsInRole(role); }

    public CustomPrincipal(IPrincipal principal)
    {
        Principal = principal;
        //this force the load of the userid
        Identity = new CustomIdentity(principal.Identity);
    }
}

Then in Global.asax just set

然后在Global.asax中设置

protected void Application_PreRequestHandlerExecute(object sender, EventArgs e)
{
        if (Request.IsAuthenticated)
        {
            var principal = new CustomPrincipal(HttpContext.Current.User);
            HttpContext.Current.User = principal;
        }
}

And you can access your UserId like this

您可以像这样访问您的UserId

((CustomIdentity)User.Identity).UserId //In Controllers
((CustomIdentity)HttpContext.Current.User.Identity).UserId //Inside classes

Was this what you were looking for?

这是你在寻找什么?