ServiceStack JsonServiceClient OnAuthenticationRequired

2023-12-29

这是 StackOverflow 上的第一篇文章,所以如果我做错了什么,请耐心等待。

我正在使用 ServiceStack 创建 RESTful Web 服务。 在开发示例 Windows 客户端时,我发现了 JsonServiceClient.OnAuthenticationRequired 属性,但无法使其正常工作。 我没有找到有关它的文档 - 我假设这是一种委托方法,用于在服务器需要身份验证时提供用户凭据 - 但我无法让它工作。

这里是我尝试使用的一些示例代码(它是 VB.Net,但对于 C# 爱好者来说也应该非常容易阅读)。

Private _clientAuthenticationRequested As New Action(Of WebRequest)(AddressOf InteractiveAuthentication)

Private Sub Login
....
    _client = New JsonServiceClient(WEBSERVER_ADDRESS)
    _client.OnAuthenticationRequired = _clientAuthenticationRequested
....
End Sub
Private Sub InteractiveAuthentication(SourceRequest As WebRequest)
    SourceRequest.Credentials= ... set some valid credentials
End Sub

即使客户端启动需要身份验证的请求,也永远不会触发“InteractiveAuthentication”。

有人知道属性的含义和用法吗?

非常感谢 阿尔贝托


感谢 Marfarma 为我指明了正确的方向。

经过对源代码的一些研究后,我发现只有在提供用户名和密码时 ShouldAuthenticate 才会返回 true。在这种情况下,OnAuthenticationRequired 委托被正确触发并且运行得非常好,允许客户端进行身份验证并避免未经授权的异常。

只是总结一下:

Private _clientAuthenticationRequested As New Action(Of WebRequest)(AddressOf InteractiveAuthentication)

Private Sub Login
....
    _client = New JsonServiceClient(WEBSERVER_ADDRESS)
    _client.OnAuthenticationRequired = _clientAuthenticationRequested
    'Requided in order to allow ShouldAuthenticate to return true and trigger OnAuthenticationRequired
    _client.UserName = "usr"
    _client.Password = "pwd"
....
'Now - I can execute my request: which will initially fail and trigger the InteractiveAuthentication delegate
response = _client.Get(Of MKXData.MKXPriceResponse)(New MKXData.MKXPricesRequest With {.Ticker = "US10YY"})

End Sub
Private Sub InteractiveAuthentication(SourceRequest As WebRequest)
    'here I start the full authentication procedure (simulating the interactive User to provide his\her credentials)

    Dim authResponse As Auth
    AuthResponse = _client.Send(Of Auth)(New Auth With {.provider = CredentialsAuthProvider.Name,
                                                .UserName = "User",
                                                .Password = "Password",
                                                .RememberMe = True})
    'after successfully executing the authentication, my former request is executed successfully and the results are returned.

End Sub

希望这对其他人有用。

非常感谢您的帮助 阿尔贝托

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

ServiceStack JsonServiceClient OnAuthenticationRequired 的相关文章

随机推荐