使.net客户端识别身份验证会话cookie



我使用" memorme =true",并希望我的服务客户端重用开放会话,如果它是可用的。我从下面的链接中获得了大部分代码-这段代码工作,但每次身份验证都失败,并重新进行身份验证。我一定要发送那个该死的cookie吗?

还有一点:这是一个WinForms客户端访问我的servicestack服务

ServiceStack JsonServiceClient OnAuthenticationRequired

我的代码
    Private Shared _UserName As String = "xxxxx"
    Private Shared _Password As String = "yyyyy"
    Private Shared _clientAuthenticationRequested As New Action(Of WebRequest)(AddressOf InteractiveAuthentication)
    Public Shared ReadOnly Property ServiceClient() As JsonServiceClient
        Get
            If _serviceClient Is Nothing Then
                _serviceClient = New JsonServiceClient(ServiceContext.ServiceUrl)
                _serviceClient.OnAuthenticationRequired = _clientAuthenticationRequested
                _serviceClient.UserName = _UserName
                _serviceClient.Password = _Password
                //service requiring authentication
                Dim v = _serviceClient.Get(Of Tonto.Svc.Model.AppConstants)(
                    New Tonto.Svc.Model.AppConstants())
            End If
            Return _serviceClient
        End Get
    End Property
    Private Shared Sub InteractiveAuthentication(sourcerequest As System.Net.WebRequest)
        Dim v = _serviceClient.Send(Of ServiceStack.AuthenticateResponse)(
            New ServiceStack.Authenticate() With {
                .UserName = _UserName,
                .Password = _Password,
                .RememberMe = True})             
    End Sub

您不能让客户端在创建客户端之间记住您的会话。RememberMe选项在这里不起作用,因为客户端不像web浏览器那样具有持久的cookie存储。

但是,您可以访问客户端的cookie存储,在您通过身份验证后,然后读取会话值cookie,并在将来的客户端实例中恢复它。实际上,您提供了持久层。

对不起,这是c#不是VB。但我认为概念应该足够清晰。

  var host = "http://localhost:9001";
  JsonServiceClient client = new JsonServiceClient(host);
  // Authenticate with the service
  client.Post(new Authenticate { UserName = "test", Password = "password" });
  // Read the session cookie after successfully authenticating
  var cookies = client.CookieContainer.GetCookies(new Uri(host));
  var sessionCookieValue = cookies["ss-id"].Value;
  // Store the value of sessionCookieValue, so you can restore this session later
  client = null; 

因此,如果您要将ss-id值保存到一个文件中,您可以在应用程序启动时恢复该值,然后在发出请求之前将其添加回客户机的cookie存储中。

  // Another client instance ... we will reuse the session
  JsonServiceClient anotherClient = new JsonServiceClient(host);
  // Restore the cookie
  anotherClient.CookieContainer.Add(new Cookie("ss-id", sessionCookieValue, "/", "localhost"));
  // Try access a secure service
  anotherClient.Get(new TestRequest());

最新更新