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

余生长醉 提交于 2019-12-01 00:48:53

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!

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!