How to use Windows Authentication in WPF?

允我心安 提交于 2019-12-02 19:45:51

Itowlson's answer was correct, but also, in order to use the PrincipalPermissionAttribute on any method, you have to first make the windows principal the current principal by calling:

AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal)

The reason this doesn't work in WPF is that these services are implemented in VB's WindowsFormsApplicationBase class, which isn't used in WPF applications. To do the same thing yourself:

Call WindowsIdentity.GetCurrent() to get the Windows user identity. You can get the name from this.

If you specifically want to set the thread principal the way the VB Windows Authentication option does, call Thread.CurrentPrincipal = new WindowsPrincipal(WindowsIdentity.GetCurrent()) -- this is exactly what WindowsFormsApplicationBase does internally.

EDIT: If you prefer the My.User API, it looks like you should be able to do the same thing by calling My.User.InitializeWithWindowsUser(). I haven't tested this though.

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