Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternative to cookie based session/authentication

Is there an alternative to the session feature plugin in servicestack? In some scenarios I cannot use cookies to match the authorized session in my service implementation. Is there a possibility to resolve the session using a token in http header of the request? What is the preferred solution for that in case the browser is blocking cookies?

like image 419
crazyRaisy Avatar asked May 22 '13 11:05

crazyRaisy


2 Answers

I'm using ServiceStack without the built-in auth and session providers.

I use a attribute as request filter to collect the user information (id and token), either from a cookie, request header or string parameter. You can provide this information after the user takes login. You append a new cookie to the response and inject the id and token info on clientside when rendering the view, so you can use for http headers and query parameters for links.

public class AuthenticationAttribute : Attribute, IHasRequestFilter 
{
    public void RequestFilter(IHttpRequest request, IHttpResponse response, object dto)
    {
        var userAuth = new UserAuth { };
        if(!string.IsNullOrWhiteSpace(request.GetCookieValue("auth"))
        {
            userAuth = (UserAuth)request.GetCookieValue("auth");

        } 
        else if (!string.IsNullOrEmpty(request.Headers.Get("auth-key")) &&
            !string.IsNullOrEmpty(request.Headers.Get("auth-id")))
        {
            userAuth.Id = request.Headers.Get("id");
            userAuth.Token = request.Headers.Get("token");
        }
        authenticationService.Authenticate(userAuth.Id, userAuth.token);
    }
    public IHasRequestFilter Copy()
    {
        return new AuthenticationAttribute();
    }
    public int Priority { get { return -3; } } // negative are executed before global requests 
}

If the user isn't authorized, i redirect him at this point.

My project supports SPA. If the user consumes the API with xmlhttprequests, the authentication stuff is done with headers. I inject that information on AngularJS when the page is loaded, and reuse it on all request (partial views, api consuming, etc). ServiceStack is powerful for this type of stuff, you can easily configure your AngularJS app and ServiceStack view engine to work side by side, validating every requests, globalizing your app, etc.

In case you don't have cookies and the requests aren't called by javascript, you can support the authentication without cookies if you always generate the links passing the id and token as query parameters, and pass them through hidden input on forms, for example.

like image 81
Gui Avatar answered Oct 20 '22 02:10

Gui


@Guilherme Cardoso: In my current solution I am using a PreRequestFilters and the built-in session feature.

My workflow/workaround is the following:

When the user gets authorized I took the cookie and send it to the client by using an http header. Now the client can call services if the cookie is set in a http-header (Authorization) of the request.

To achieve this I redirect the faked authorization header to the cookie of the request using a PreRequestFilter. Now I am able to use the session feature. Feels like a hack but works for the moment ;-)

public class CookieRestoreFromAuthorizationHeaderPlugin : IPlugin
{
    public void Register(IAppHost appHost)
    {
        appHost.PreRequestFilters.Add((req, res) =>
            {
                var cookieValue = req.GetCookieValue("ss-id");

                if(!string.IsNullOrEmpty(cookieValue))
                    return;

                var authorizationHeader = req.Headers.Get("Authorization");

                if (!string.IsNullOrEmpty(authorizationHeader) && authorizationHeader.ToLower().StartsWith("basictoken "))
                {
                    var cookie = Encoding.UTF8.GetString(Convert.FromBase64String(authorizationHeader.Split(' ').Last()));

                    req.Cookies.Add("ss-id",new Cookie("ss-id",cookie));
                    req.Items.Add("ss-id",cookie);
                }
            });
    }
}
like image 35
crazyRaisy Avatar answered Oct 20 '22 03:10

crazyRaisy