简短的回答是无法在客户端确定用户是否已通过身份验证,因为确定客户端是否已通过身份验证的状态存储在服务器上。
只有当存在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
}