gpt4 book ai didi

.net - 在 Winforms 中为所有线程设置 CurrentPrincipal

转载 作者:行者123 更新时间:2023-12-03 00:45:56 25 4
gpt4 key购买 nike

在 .NET 3.5 Winforms 应用程序中,在用户提供用户名和密码后,我在 CurrentPrincipal 属性中设置自定义主体,如下所示:

My.User.CurrentPrincipal = Service.GetPrincipal(username)

这是在使用 Invoke 调用的方法中完成的,因为原始线程不是 UI 线程:

Invoke(New Action(AddressOf doLogin))

但是当我单击 Winforms 应用程序中的按钮时,CurrentPrincipal 属性已恢复为其默认值,即当前 Windows 用户。

Dim lPrincipal = My.User.CurrentPrincipal ' not my custom principal

显然,在设置主体时使用 Invoke 并不能解决问题。是否有另一种方法可以为应用程序中的所有线程设置 CurrentPrincipal 属性?

重现问题的源代码:

Imports System.Security.Principal
Imports System.Threading

Public Class Form1

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim lThread As New Thread(AddressOf doLogin)
lThread.Start()
End Sub

Private Sub doLogin()
Invoke(New Action(AddressOf setPrincipal))
End Sub

Private Sub setPrincipal()
My.User.CurrentPrincipal = New CustomPrincipal
MsgBox(My.User.CurrentPrincipal.Identity.AuthenticationType) ' Custom
End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
MsgBox(My.User.CurrentPrincipal.Identity.AuthenticationType) ' Default
End Sub
End Class

Public Class CustomPrincipal
Implements IPrincipal

Public ReadOnly Property Identity() As IIdentity Implements IPrincipal.Identity
Get
Return New CustomIdentity()
End Get
End Property

Public Function IsInRole(ByVal role As String) As Boolean Implements IPrincipal.IsInRole
Return True
End Function
End Class

Public Class CustomIdentity
Implements IIdentity

Public ReadOnly Property AuthenticationType() As String Implements IIdentity.AuthenticationType
Get
Return "Custom"
End Get
End Property

Public ReadOnly Property IsAuthenticated() As Boolean Implements IIdentity.IsAuthenticated
Get
Return True
End Get
End Property

Public ReadOnly Property Name() As String Implements IIdentity.Name
Get
Return "CustomName"
End Get
End Property
End Class

最佳答案

使用 AppDomain.SetThreadPrincipal,而不是 Thread.CurrentPrincipal (My.User.CurrentPrincipal):

AppDomain.CurrentDomain.SetThreadPrincipal(principal)

关于.net - 在 Winforms 中为所有线程设置 CurrentPrincipal,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4592692/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com