2

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

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

4

1 回答 1

5

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

仅当用户会话 Id 中存储了经过身份验证的会话时,用户才经过身份验证。此 SessionId 通常在 HTTP 客户端 Cookie 中发送,这些 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 进行身份验证和检索 Session的示例,以确定用户是否通过调用来进行身份验证/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
}
于 2015-01-26T19:26:47.393 回答