2013-05-22 68 views
7

有沒有在servicestack會議功能插件的替代品?在某些情況下,我無法使用Cookie來匹配服務實施中的授權會話。是否有可能使用請求的http標頭中的令牌來解析會話?如果瀏覽器阻止Cookie,那麼首選解決方案是什麼?替代基於Cookie的會話/認證

回答

7

我使用ServiceStack沒有內置的身份驗證和會話提供商。

我使用屬性作爲請求過濾器收集用戶信息(ID和令牌),無論是從一個cookie,請求報頭或字符串參數。 用戶登錄後可以提供此信息。您可以在響應中附加一個新的cookie,並在呈現視圖時在客戶端注入id和token信息,以便您可以使用http標題和查詢鏈接參數。

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 
} 

如果用戶未被授權,我在此時重定向他。

我的項目支持SPA。如果用戶使用xmlhttprequests來使用API​​,那麼認證內容將使用標題完成。我在加載頁面時將這些信息注入到AngularJS中,並在所有請求(部分視圖,api消費等)上重用它。 ServiceStack對於這種類型的功能非常強大,您可以輕鬆配置您的AngularJS應用程序和ServiceStack視圖引擎並行工作,驗證每個請求,全球化您的應用程序等。

如果您沒有Cookie,請求不會被javascript調用,如果您始終生成傳遞id和token作爲查詢參數的鏈接,並且通過表單上的隱藏輸入傳遞它們,則可以支持不使用cookie的身份驗證。

4

@Guilherme Cardoso:在我目前的解決方案中,我使用了PreRequestFilters和內置的會話功能。

我的工作流程/解決方法如下:

當用戶獲得授權我拿餅乾,並通過使用HTTP標頭將其發送給客戶端。現在,如果cookie被設置在請求的http-header(Authorization)中,客戶端可以調用服務。

爲了達到這個目的,我使用PreRequestFilter將僞造的授權頭重定向到請求的cookie。現在我可以使用會話功能。感覺就像一個黑客,但工作的時刻;-)此

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); 
       } 
      }); 
    } 
} 
+0

謝謝,這是我CORS通過Ajax實現的最後一塊/角,讓我對我的驗證調用返回的會話ID,將其作爲自定義標題添加到相應的Ajax調用中,然後不必在服務堆棧中創建自定義身份驗證提供程序,以便在標準預期cookie時接收標頭。 –

相關問題