A better way to get a Windows Username using Forms Authentication?

前端 未结 2 1664
名媛妹妹
名媛妹妹 2021-01-07 00:09

I\'ve inherited a project that uses forms authentication, but a recent feature request requires me to get the Windows username of some users.

It\'s a website that us

相关标签:
2条回答
  • 2021-01-07 00:38

    This article contained the answer, (thanks vinodpthmn): http://msdn.microsoft.com/en-us/library/ms972958.aspx I'd found links to this article in my research, but none of them worked! Glad I was finally able to read it and solve my problem.

    As I mentioned I only needed to get the windows username of clients, but that turned out to be quite troublesome, thankfully the actual solution was relatively simple.

    Firstly, you need to create an additional login page (I called mine winlogin.aspx) and set that as the default login page in your Web.Config file, like this:

    <authentication mode="Forms">
          <forms name="something" defaultUrl="default.aspx" loginUrl="winlogin.aspx" protection="All" slidingExpiration="true" timeout="90"/>
        </authentication>
    

    Inside the winlogin.aspx.cs file is where you authenticate windows users and use

    FormsAuthentication.RedirectFromLoginPage(username, false/true);
    

    To redirect them to wherever they were going. The actual winlogin.aspx page should be blank, users will never see it.

    You need to publish to your testing web server for this next part: You access the file properties of winlogin.aspx in IIS manager and set WindowsAuthentication to true and Anonymous Authentication to false. You also need to create a custom 401 error page pointer (mine points to my old Login.aspx page).

    Users that can login with windows authentication will do so, everybody else will be redirected to the old login page.

    Voila!

    There are a couple of issues however, you lose your return URL (you can't use "=" in the link to a custom 401 error page, so nothing can be parsed) so you'll probably want to set a cookie whenever people are redirected to the winlogin page and access that cookie in your forms login page to redirect the user appropriately.

    If anybody has any questions, I suggest reading the article linked above, or feel free to ask questions here.

    Thanks everybody for your help!

    0 讨论(0)
  • 2021-01-07 00:58

    You could use directory services

    PrincipalContext pc = null;
    UserPrincipal principal = null;
    var username = User.Identity.Name;
    pc = new PrincipalContext(ContextType.Domain, "give your domain name here");
    principal = UserPrincipal.FindByIdentity(pc, userName);
    var firstName = principal.GivenName ?? string.Empty;
    var lastName = principal.Surname ?? string.Empty;
    

    please add reference for System.DirectoryServices.AccountManagement

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