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

时间:2014-03-17 14:36:04

标签: authentication servicestack

我正在使用" RememberMe = true",并希望我的服务客户端重新使用开放会话(如果可用)。我从下面的链接获得了大部分代码 - 这段代码可以工作,但每次开始时身份验证都会失败并重新进行身份验证。我是否必须以某种方式发送ss-pid cookie?

还有一点需要注意:这是一个访问我的servicestack服务的 WinForms 客户端。

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

1 个答案:

答案 0 :(得分:4)

您无法让客户在开箱即用的客户端创建之间记住您的会话。 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());