ServiceStack JsonServiceClient OnAuthenticationRequired

标签 servicestack

这是 StackOverflow 上的第一篇文章,所以如果有任何错误,请耐心等待。

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

这里是我尝试使用的一些示例代码(它是 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 委托(delegate)被正确触发并运行良好,允许客户端进行身份验证并避免 Unauthorized 异常。

总结一下:

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

希望这对其他人有用。

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

关于ServiceStack JsonServiceClient OnAuthenticationRequired,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18761937/

相关文章:

c# - 过期日期对 MemoryCacheClient 有影响吗?

c# - 是否可以使用 servicestack 上传文件和发布数据?

ServiceStack - 自动查询请求日志问题

c# - 如何解决 Funq IoC 中的循环依赖?

servicestack - 自定义 ServiceStack 身份验证

c# - XML 反序列化仅适用于 xml 中的命名空间

c# - 使用 Redis ServiceStack 的事务时如何创建多个序列号

c# - 在 ServiceStack 应用程序中使用时,Application Insights 不跟踪异常

c# - Servicestack 期望较低的程序集版本

http - Servicestack 请求 header 不包含 cookie