Get Logged In User

强颜欢笑 提交于 2019-12-24 00:26:30

问题


My company has a large application we are finishing up. It utilizes WCF as the back-bone with Active Directory for authentication. This works perfectly for one of the two sites as the authentication model is Windows and you have to be part of the domain to sign into the site. The question I have relates to the other site which is externally accessible. It sets ClientCredentials.Windows.ClientCredential for the proxy call with a specific user/pass for impersonation of an AD-user so the full security model works. This all works exactly as expected too.

The question I have is, on the web I can use HttpContext.Current.User.Identity.Name to get the currently logged in user from the Forms authentication piece, but to do this I have to make sure a System.Web reference exists against the DLL I'm currently working in. Our base objects come from a simplistic class that doesn't know about System.Web. Is there a way to find out the Forms user who is logged in inside that base object project? I tried System.Security.Principal but that only gives me access to the Windows accounts from what I could tell and won't do me any good.

I know an option is to just reference System.Web and be done with it but that sounds really klugy to me and not the best option so I'm hoping for some tips here.


回答1:


Thread.CurrentPrincipal.Identity will do the exact same thing as HttpContext.CurrentContext...

It will return the identity associated with the current executing thread, which in most cases, is the logged on user*.

Note: *If you are using delegation/impersonation or running as a service account, it will return the account of which ever identity the thread is under, but in your case, it doesn't sound like you are doing any context identity switching.




回答2:


If user name as a string is enough for you,

Environment.UserName
// Environment.UserDomainName and MachineName can also be useful

From MSDN:

Gets the user name of the person who started the current thread.



来源:https://stackoverflow.com/questions/1407932/get-logged-in-user

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