Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ServiceStack Razor Authentication

I am looking at the Rockstars example and ServiceStack.Razor.

How do I go about fitting authentication into, say, secure.cshtml page. So I can redirect user to Login.cshtml if required.

I only understand from SocialBootstrapApi example if I mix MVC hybird, I can put [authenticate()] at ServiceStackController to achieve that.

But what if I just want a pure SS project without .net MVC?

like image 488
Tom Avatar asked Sep 28 '12 13:09

Tom


1 Answers

The Authenticate attribute is just a plain ServiceStack Request Filter Attribute, i.e. it works in both MVC and ServiceStack.

Applying this filter will return a 401 UnAuthorized response for all non-HTML requests. e.g. If you called this with Ajax, you could detect this error response and do the redirect on the client.

From v3.9.23+ of ServiceStack the [Authenticate] attribute will automatically redirect all Authentication errors to ~/login url by default.

You can override this url when you register the AuthFeature, e.g:

Plugins.Add(new AuthFeature(...) { HtmlRedirect = "/path/to/my/login" });

Which will apply globally to all [Authenticate] attributes or you can override this on an adhoc basis with:

[Authenticate(HtmlRedirect="/path/to/my/login")]

Note: Attributes are inheritable so you can add this once to a SecuredService class and all subclasses will inherit its behaviour.

Redirecting manually

To redirect an UnAuthorized HTML request manually you can do your own checking + redirection with:

public object Secured(Request request) {
    if (!base.SessionAs<MyCustomSession>().IsAuthenticated)
        return new HttpResult(HttpStatusCode.Redirect, "Un Authorized") { 
           Headers = { {"Location", "/path/to/login" } } };
}

There is also a DRY wrapper around the above redirect which you can use instead:

public object Secured(Request request) {
    if (!base.SessionAs<MyCustomSession>().IsAuthenticated)
        return HttpResult.Redirect("/path/to/login");
}
like image 152
mythz Avatar answered Nov 08 '22 15:11

mythz