Anton Hasan
Anton Hasan

Reputation: 551

Authentication in servicestack.razor

I try to create complete web apps using ServiceStack.Razor. but got problem how to handle authentication in service and page.

handle unauthorized access in service quite easy as we can set authentication attributes. I have config authentication using credentialsAuthProvider and success authenticated using query string to /auth?username=&password and successfully access secured serviced.

but how to handle unauthorized access to services. currently it return 401 unauthorized access. so when user access the page it only shown blank page.. i have try to setup customhttphandler for unauthorized access to redirect to login page but not success

SetConfig(new EndpointHostConfig {
    DebugMode = true,
    CustomHttpHandlers = {
      { HttpStatusCode.NotFound, new RazorHandler("/notfound") },
      { HttpStatusCode.Unauthorized, new RazorHandler("/login") },
    }
});

Servicestack.razor allow creating Razor Page like Asp.Net WebPages but there is no sample how to handle authorization in page like using Request.IsAuthenticated. i have try that, but throw method not exists error.

And how to logout or destroy authentication session

Update: I am using ServiceStack.Razor with SelfHosting

Upvotes: 1

Views: 1706

Answers (2)

Justin Stenning
Justin Stenning

Reputation: 1837

In a ServiceStack Self Host scenario I was able to get access to the session within the Razor view like this:

@{
    var user = Request.GetSession();
}

Authenticated: @user.IsAuthenticated

Upvotes: 3

Anton Hasan
Anton Hasan

Reputation: 551

Have to answer my self.. since no one come to answer and it will be a reference for others..

Service with Authorize attribute now redirected to login page, instead return black page now. please update latest servicestack release.

After trying many possibility to handle authentication on razor page, it can be achieve by accessing the cache in razor page.

@{
    var user = Cache.Get<AuthUserSession>(SessionKey);
}

@if (user != null && user.IsAuthenticated) {
    <h1>User @user.DisplayName is Logged</h1>
}

but with limitation that this only working in Asp.Net WebHost only. i still finding the way to make it working in Self Host.

For logout process can be achieve by create logout service where it remove session and redirected to login page.

    [Route("logout")]
public class Logout { }

public class UserService : Service
{
    public object Any (Logout r)
    {
        this.RemoveSession();
        return this.Redirect("/login");
    }
}

i'll try to make sample project with it and publish soon

Upvotes: 2

Related Questions