【问题标题】:How to check if user is authenticated in Service Stack Client?如何检查用户是否在服务堆栈客户端中进行了身份验证?
【发布时间】:2014-02-17 23:15:44
【问题描述】:

我有自托管的 Service Stack 服务器。在客户端应用程序中,它是 Windows 窗体,我想在用户未通过身份验证时显示登录表单。一种方法是尝试发送请求并捕获 WebServiceException,就像在 AuthTest 中一样。

我正在寻找与客户端等效的 @if(Request.IsAuthenticated)SocialBootstrapApi 示例)。

【问题讨论】:

    标签: authentication servicestack-bsd


    【解决方案1】:

    简短的回答是无法在客户端确定用户是否已通过身份验证,因为确定客户端是否已通过身份验证的状态存储在服务器上。

    只有当存在Authenticated Session stored in the Users session Id 时,用户才会被验证。此 SessionId 通常在 HTTP 客户端 Cookie 中发送,在成功的身份验证尝试后填充,例如:

    var client = JsonServiceClient(BaseUrl);
    var authResponse = client.Send(new Authenticate
    {
        provider = CredentialsAuthProvider.Name,
        UserName = "user",
        Password = "p@55word",
        RememberMe = true,
    });
    

    您现在可以使用相同的客户端(已填充其 Cookie)向仅身份验证服务发出经过身份验证的请求。虽然请注意,如果服务器出于任何原因清除用户会话,则客户端不再经过身份验证并将抛出 401 UnAuthorized HTTP 异常,此时他们将不得不重新进行身份验证。

    MVC LiveDemo 显示了使用 ajax 在客户端上通过调用/auth 来确定用户是否通过身份验证的身份验证和检索会话的示例,例如:

    $.getJSON("/api/auth", function (r) {
        var html = "<h4 class='success'>Authenticated!</h4>"
            + "<table>"
            + $.map(r, function(k, v) {
                return "<tr><th>" + v + "<th>"
                    + "<td>" 
                    + (typeof k == 'string' ? k : JSON.stringify(k)) 
                    + "</td></tr>";
            }).join('')
            + "</table>";
        $("#status").html(html);
    }).error(function () {
        $("#status").html("<h4 class='error'>Not Authenticated</h4>");
    

    与 C# 等价的是:

    try
    {
        var response = client.Get(new Authenticate());
        //Authenticated
    } 
    catch (WebServiceException)
    {
        //Not Authenticated
    }
    

    【讨论】:

      猜你喜欢
      • 2017-06-02
      • 2015-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多