0

I want to set identity for a non web request. Currently I am using FormsAuthentication and I am getting user identity via this User.Identity.Name . Now I have to make the user login via API. I have the username/password for the user, how can I set the identity for this.

Rocky Singh
  • 15,128
  • 29
  • 99
  • 146

2 Answers2

1

In a non-web environment, the identity is set on the thread and can be accessed by:

Thread.CurrentPrincipal.Identity

You can use this to manipulate the identity or as Vadim suggested, completely overwrite with your own custom principal.

This code snippet is taken from the System.Web.Security.Membership class that works with principals in web and non-web environments and deomstrates how the two can be used together.

public static string GetCurrentUserName()
{
    if (HostingEnvironment.IsHosted)
    {
        HttpContext current = HttpContext.Current;
        if (current != null)
        {
            return current.User.Identity.Name;
        }
    }
    IPrincipal currentPrincipal = Thread.CurrentPrincipal;
    if ((currentPrincipal != null) && (currentPrincipal.Identity != null))
    {
        return currentPrincipal.Identity.Name;
    }
    return string.Empty;
}
Jeff
  • 13,943
  • 11
  • 55
  • 103
0

You'll need to create your own IPrincipal and IIdentity implementations that you then will assign to HttpContext.User after they have been authenticated.

Vadim
  • 17,897
  • 4
  • 38
  • 62