Alternative to cookie based session/authentication

前端 未结 2 675
时光取名叫无心
时光取名叫无心 2021-02-09 12:20

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 th

2条回答
  •  清酒与你
    2021-02-09 12:55

    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.

提交回复
热议问题