ActiveDirectory Current Username in ASP.NET

后端 未结 5 1630
[愿得一人]
[愿得一人] 2020-12-31 19:20

I\'m trying to get both ActiveDirectory and standard forms login working but one thing is stopping me. I can\'t get the name of the current windows user. The closest I\'ve g

相关标签:
5条回答
  • 2020-12-31 19:56

    This is a segment of code I used in my ASP.NET MVC App not too long ago, it helped for me, Don't know if it will help you though, you are free to check though

        private static void CheckIfUserExists(string p)
        {
            try
            {
                    var user = (from x in Data.EntityDB.UserInfoes where x.SAMAccountName == p select x).FirstOrDefault();
                    DirectoryEntry entry = new DirectoryEntry(Properties.Settings.Default.LDAPPath); //this is the connection to your active directory
                    DirectorySearcher search = new DirectorySearcher(entry);
                    search.PropertiesToLoad.Add("*");
                    search.Filter = "(&(sAMAccountName=" + p + ")(objectCategory=person))";
                    SearchResult searchResult = search.FindOne();
                //If the user under the alias is not found, Add a new user. Else, update his current data
                if (user == null)
                {
                    XXXXXXX.Models.UserInfo newUserEntry = new Models.UserInfo
                    {
                        SAMAccountName = p,
                        First_Name = searchResult.Properties.Contains("givenName") ? searchResult.Properties["givenName"][0].ToString() : string.Empty,
                        Last_Name = searchResult.Properties.Contains("sn") ? searchResult.Properties["sn"][0].ToString() : string.Empty,
                        Title = searchResult.Properties.Contains("title") ? searchResult.Properties["title"][0].ToString() : string.Empty,
                        Office = searchResult.Properties.Contains("l") ? searchResult.Properties["l"][0].ToString() : string.Empty,
                        Country = searchResult.Properties.Contains("c") ? searchResult.Properties["c"][0].ToString() : string.Empty,
                        Telephone = searchResult.Properties.Contains("telephoneNumber") ? searchResult.Properties["telephoneNumber"][0].ToString() : string.Empty,
                        Mobile_Phone = searchResult.Properties.Contains("mobile") ? searchResult.Properties["mobile"][0].ToString() : string.Empty,
                        Email_Address = searchResult.Properties.Contains("mail") ? searchResult.Properties["mail"][0].ToString() : string.Empty,
                        Image_Path = string.Format(Properties.Settings.Default.UserPicturePath, p),
                        LastUpdate = DateTime.Now,
                    };
    

    update

    Take notice that I also queried a different database in this extract, ignore all the Linq statements. The DirectoryEntry, DirectorySearcher and SearchResult Classes should help you with what you need.

    update 2 the variable p can be replaced by the HttpContext.Current.User.Identity Property

    update 3 Here is a current list of LDAP names (where you see searchResult.Properties.Contains("") Over here which points to different user attributes in the active directory

    0 讨论(0)
  • I'd give a try with:

    var i = Environment.CurrentUser;

    and you can use also my class: http://pastebin.com/xnYfVsLX

    0 讨论(0)
  • 2020-12-31 20:06

    If you turn on ASP.Net Impersonation in IIS, you can get the username like you wanted to. This will only work if that data is in the forms membership provider / AD, and they are not Anonymous.

    Also, mixing Forms based and Windows/AD based auth is doable but not recommended. See this if you need to do it.

    EDIT: I think I misunderstood what you wanted so here's a high-level glossing over of what goes on with the aforementioned solution:

    If you turn off Anonymous Authentication, and turn on Asp.Net Impersonation, IIS will do a 401 Challenge whenever somebody visits the site.
    If everything is on the same domain, the web browser will send your credentials to IIS, IIS will validate them against it's Active Directory, and then AD will give IIS an Identity to work with.

    When you have Asp.Net Impersonation turned on, IIS will then bind that Identity to the current thread/request. So after authentication happens, you can just grab the username from the current thread identity, and then query Active Directory like:

    using System.Threading;
    using System.DirectoryServices;
    using System.DirectoryServices.AccountManagement;
    
    ......
    
    PrincipalContext pc = null;
    UserPrincipal principal = null;
    
    try
    {
        var username = Thread.CurrentPrincipal.Identity.Name;
        pc = new PrincipalContext(ContextType.Domain, "active.directory.domain.com");
        principal = UserPrincipal.FindByIdentity(pc, username);
    
        var firstName = principal.GivenName ?? string.Empty
        var lastName = principal.Surname ?? string.Empty
        return string.Format("Hello {0} {1}!", firstName, lastName);
    }
    catch ...
    finally
    {
        if (principal != null) principal.Dispose();
        if (pc != null) pc.Dispose();
    }
    
    0 讨论(0)
  • 2020-12-31 20:08

    Try this if you are using forms authentication with active directory:

    Context.User.Identity.Name
    

    //code snippet

    sub Page_Load(sender as object, e as EventArgs)
      lblName.Text = "Hello " + Context.User.Identity.Name & "."
      lblAuthType.Text = "You were authenticated using " &   Context.User.Identity.AuthenticationType & "."
    end sub
    

    Ref:
    Active Directory Authentication from ASP .NET
    How to authenticate against the Active Directory by using forms authentication and Visual Basic .NET Building Secure ASP.NET Applications: Authentication, Authorization, and Secure Communication

    Ref: You can use Windows authentication with ASP.NET in a number of ways:

    • Windows authentication without impersonation. This is the default setting. ASP.NET performs operations and accesses resources by using your application's process identity, which by default is the Network Service account on Windows Server 2003.

    • Windows authentication with impersonation. With this approach, you impersonate the authenticated user and use that identity to perform operations and access resources.

    • Windows authentication with fixed-identity impersonation. With this approach, you impersonate a fixed Windows account to access resources using a specific identity. On Windows Server 2003, you should avoid this impersonation approach; instead, use a custom application pool with a custom service identity.

    As per the documentation you can obtain the authenticated user's Windows token.

    IIdentity WinId= HttpContext.Current.User.Identity;
    WindowsIdentity wi = (WindowsIdentity)WinId;
    

    If there is something wrong then check your application impersonation method as per the MSDN documentation of How To: Use Windows Authentication in ASP.NET 2.0

    Refer ScottGu's article Recipe: Enabling Windows Authentication within an Intranet ASP.NET Web application

    0 讨论(0)
  • 2020-12-31 20:15

    The .Net apps I've written where I've used windows authentication I can still use User.Identity.Name to get the AD username. This usually includes the DC of course, and returns the users SAM Account name. I was not trying to implement both at the same time but User.Identity.Name for sure works separately

    0 讨论(0)
提交回复
热议问题