Вопрос

I have self hosted Service Stack server. In client application, it is Windows Form, I want to display login form when user is not authenticated. One way is to try send request and catch WebServiceException like in AuthTest.

I'm looking for @if(Request.IsAuthenticated) (SocialBootstrapApi example) equivalent for client side.

Это было полезно?

Решение

Short answer is there is no way to determine on the client if the User is authenticated or not as the state that determines whether or not a client is Authenticated is stored on the Server.

A user is only Authenticated if there's an Authenticated Session stored in the Users session Id. This SessionId is generally sent in the HTTP Client Cookies which get populated after a successful Authentication attempt, e.g:

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

You can now use the same client (which has its Cookies populated) to make Authenticated Requests to Auth Only Services. Although note if the Server clears out the Users session for any reason the client is no longer authenticated and will throw 401 UnAuthorized HTTP Exceptions at which point they will have to re-Authenticate.

The MVC LiveDemo shows examples of Authentication and retrieving Session on the client with ajax to determine whether the user is authenticated or not by calling /auth, e.g:

$.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>");

The equivalent with C# is:

try
{
    var response = client.Get(new Authenticate());
    //Authenticated
} 
catch (WebServiceException)
{
    //Not Authenticated
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top