Alternative to cookie based session/authentication

前端 未结 2 681
时光取名叫无心
时光取名叫无心 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:42

    @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);
                    }
                });
        }
    }
    

提交回复
热议问题