locked
How to get the login users' GUID instead of theit Identity.Name RRS feed

  • Question

  • User-540818677 posted

    I am working on an ASP.NET MVC 5 web application, and I am using forms authentication against our LDAP server.

    Here is the login action method:-

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public ActionResult Login(LoginModel model, string returnUrl)
    {
        MembershipProvider domainProvider;
        domainProvider = Membership.Providers["ADMembershipProvider"];
        if (ModelState.IsValid)

    And the related entities inside our web.config file, which connects to the LDAP:

    <providers>
    <add name="ADMembershipProvider" type="System.Web.Security.ActiveDirectoryMembershipProvider, System.Web, Version=4.0.0.0, &#xA;   Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" connectionStringName="TestDomain1ConnectionString" connectionUsername="ad.user" connectionPassword="***" attributeMapUsername="sAMAccountName"/>
    </providers>
    
    <connectionStrings>
    <add name="TestDomain1ConnectionString" connectionString="LDAP://ad-Tgroup.intra/OU=T,DC=ad-Tgroup,DC=intra"/>
    </connectionStrings>

    Currently I am storing the domainname\username inside our log table, as follows:

    string ADusername = User.Identity.Name.ToString();
    repository.InsertOrUpdateResturant(resturant, ADusername);

    Using the User.Identity.Name might work in almost 95% of the cases because it can uniquely identify any user, but on the other hand, the username might be changed (let's say a user got married or divorced). So I am planning on replacing my User.Identity.Name and getting the user GUID instead. But I'm not sure if MVC 5 provides a way to get the login user GUID. For example, I cannot write User.Identity.GUID

    Tuesday, December 16, 2014 12:01 PM

Answers

All replies

  • User753101303 posted

    Hi,

    Don't know if you can do that with the provider but in the past I used http://msdn.microsoft.com/en-us/library/bb344891(v=vs.110).aspx to get the user and get  its http://msdn.microsoft.com/en-us/library/system.directoryservices.accountmanagement.principal.sid(v=vs.110).aspx property...

    Tuesday, December 16, 2014 12:31 PM
  • User-1301051635 posted

    Hello John,

    Depending on the ASP.NET authentication provider you can get the currently logged-on user id (guid) by using one of the code snippets below:

    -------------------------------------------------

    • ASP.NET Membership Provider
    string userId = Membership.GetUser().ProviderUserKey.ToString();

    If you need the user id in Guid type you can cast it:

    Guid guid = (Guid)Membership.GetUser().ProviderUserKey;

    MSDN Reference:

    http://msdn.microsoft.com/en-us/library/ms152019%28v=vs.110%29.aspx

    http://msdn.microsoft.com/en-us/library/system.web.security.membershipuser.provideruserkey%28v=vs.110%29.aspx

    http://msdn.microsoft.com/en-us/library/system.web.security.membershipuser%28v=vs.110%29.aspx

    -------------------------------------------------

    • ASP.NET Identity 2.0
    using Microsoft.AspNet.Identity;
    string userId = User.Identity.GetUserId();

    MSDN Reference:

    http://msdn.microsoft.com/en-us/library/microsoft.aspnet.identity.identityextensions.getuserid%28v=vs.108%29.aspx

    GitHub Source Code:

    https://github.com/aspnet/Identity/blob/dev/src/Microsoft.AspNet.Identity/ClaimsIdentityExtensions.cs

    -------------------------------------------------

    Just let me know if you have any further questions or concerns.

    Tuesday, December 16, 2014 1:30 PM
  • User-540818677 posted

    encounter


    Depending on the ASP.NET authentication provider you can get the currently logged-on user id (guid) by using one of the code snippets below

    Thanks for the reply. as i mentioned before i am using  Asp.net MemberShip Provider , which authenticate users against out Active Directory's LDAP server. in my case i provide a form where users enter their AD username & Password, then i authenticate them against the LDAP . i have already provide the related code i my original question.

    Second question

    encounter

    If you need the user id in Guid type you can cast it:

    Guid guid = (Guid)Membership.GetUser().ProviderUserKey;

    will this cause a call to the LDAP database ? or the GetUSer().ProviderUserKey will be inside the session information. for example when i get the login user name using:-

    User.Identity.Name.ToString()

    as i know that this info is already inside the session , and it will not cause an immediate call to the LDAP to get the info,, so doe this also apply when using :-

    Guid guid = (Guid)Membership.GetUser().ProviderUserKey;

    Tuesday, December 16, 2014 8:59 PM
  • User-540818677 posted

    If you need the user id in Guid type you can cast it:

    Guid guid = (Guid)Membership.GetUser().ProviderUserKey;

    when i tried this code i got the following exception:-

    Server Error in '/' Application.
    
    A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified) 
      Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 
    
     SQLExpress database file auto-creation error: 
    
    
    The connection string specifies a local Sql Server Express instance using a database location within the application's App_Data directory. The provider attempted to automatically create the application services database because the provider determined that the database does not exist. The following configuration requirements are necessary to successfully check for existence of the application services database and automatically create the application services database:
    
    1.If the application is running on either Windows 7 or Windows Server 2008R2, special configuration steps are necessary to enable automatic creation of the provider database. Additional information is available at: http://go.microsoft.com/fwlink/?LinkId=160102. If the application's App_Data directory does not already exist, the web server account must have read and write access to the application's directory. This is necessary because the web server account will automatically create the App_Data directory if it does not already exist.
    2.If the application's App_Data directory already exists, the web server account only requires read and write access to the application's App_Data directory. This is necessary because the web server account will attempt to verify that the Sql Server Express database already exists within the application's App_Data directory. Revoking read access on the App_Data directory from the web server account will prevent the provider from correctly determining if the Sql Server Express database already exists. This will cause an error when the provider attempts to create a duplicate of an already existing database. Write access is required because the web server account's credentials are used when creating the new database.
    3.Sql Server Express must be installed on the machine.
    4.The process identity for the web server account must have a local user profile. See the readme document for details on how to create a local user profile for both machine and domain accounts.
    
    
    Source Error: 
    
    
     An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.  
    
    Stack Trace: 
    
    
    
    
     
    

    Tuesday, December 16, 2014 9:32 PM
  • User-1301051635 posted

    All right, John. I think I got your point. In that case why don't you try one of the solutions provided in StackOverflow thread "Getting authenticate AD users objectGuid from asp.net":

    // using System.Security.Principal;
    IPrincipal userPrincipal = HttpContext.Current.User;
    WindowsIdentity windowsId = userPrincipal.Identity as WindowsIdentity;
    if (windowsId != null)
    {
        SecurityIdentifier sid = windowsId.User;
    
        using(DirectoryEntry userDirectoryEntry = new DirectoryEntry("LDAP://<SID=" + sid.Value + ">"))
        {
            Guid objectGuid = new Guid(userDirectoryEntry.NativeGuid);
        }
    }

    and let me know the result. Have a great day!

    MSDN Reference for NativeGuid Property:

    http://msdn.microsoft.com/en-us/library/system.directoryservices.directoryentry.nativeguid.aspx

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, December 18, 2014 7:19 AM
  • User-540818677 posted

    All right, John. I think I got your point. In that case why don't you try one of the solutions provided in StackOverflow thread "Getting authenticate AD users objectGuid from asp.net":

    // using System.Security.Principal;
    IPrincipal userPrincipal = HttpContext.Current.User;
    WindowsIdentity windowsId = userPrincipal.Identity as WindowsIdentity;
    if (windowsId != null)
    {
        SecurityIdentifier sid = windowsId.User;
    
        using(DirectoryEntry userDirectoryEntry = new DirectoryEntry("LDAP://<SID=" + sid.Value + ">"))
        {
            Guid objectGuid = new Guid(userDirectoryEntry.NativeGuid);
        }
    }

    and let me know the result. Have a great day!

    MSDN Reference for NativeGuid Property:

    http://msdn.microsoft.com/en-us/library/system.directoryservices.directoryentry.nativeguid.aspx

    ok thanks for the reply, i will try your approach. but i want to make sure that your approach will work in my situation. for example currently I am getting the

    User.Identity.Name.ToString();

    inside a custom Authorization attribute class, so i get the User.Identity.Name before calling any action method, which does not cause any performance drawbacks because retrieving the username using User.Identity.Name will not cause any call to the LDAP or database,,, but in your case seems that i need to call the LDAP before getting the GUID, which will have bad performance i think. can you adivce ? .

    Thursday, December 18, 2014 8:32 AM
  • User-1301051635 posted

    Hi, again. In the using statement there is one additional call to the LDAP compared to your approach:

    User.Identity.Name.ToString(); 

    So if the solution provided in the StackOverflow thread is working for you it is up to you to decide which option to use. This depends on the number of users utilizing the website and of course you can perform some load tests to see how the website will perform with this code. Let me know in case of any questions.

    Thursday, December 18, 2014 8:51 AM