2013-07-18 186 views
2

我已經使用自定義身份驗證提供程序設置了ServiceStack api。這一切工作正常,我可以認證並使用api,因爲我喜歡。MVC 4表單身份驗證中的持久ServiceStack身份驗證

我有一個單獨的MVC4應用程序與FormsAuthentication,將使用此API來驗證它的用戶。在Api驗證了用戶名/密碼後,我想保留客戶端的所有後續請求。我知道客戶端在CookieContainer中設置Cookie,如果我保留相同的客戶端,所有請求都將保持有效。

var client = new JsonServiceClient(AppConfig.Settings.ApiEndpoint); 
client.Headers.Add("X-ApiKey", AppConfig.Settings.ApiKey); 
auth.RememberMe = true; 
AuthResponse authResponse = client.Post(auth); 

但是我不想在每次我想要做一個請求(儘管這是一個選項)時發送auth到api。我發現這個要點https://gist.github.com/danmiser/1701803(ServiceStack的舊版本我認爲)發生了。

我也想過設置MVC4應用程序的客戶端返回的cookie,並將它們添加到客戶端的CookieContainer中,以便後續請求進行身份驗證。

有沒有更好的/標準的方法來做到這一點?我錯過了明顯的東西嗎?

回答

3

我已經使用'輔助方法'來返回一個JSONServiceClient,它使用會話cookie進行身份驗證。您需要找出一種方法來存儲和提供經過驗證的cookie值**。我認爲最簡單的方法是將其存儲在MVC會話中。

public JsonServiceClient GetAuthenticatedClient() 
    { 
     //Need to get an authenticated session key/token from somewhere 
     //this can be used when MVC and ServiceStack are running together-> var sessionKey = SessionFeature.GetSessionKey().Replace("urn:iauthsession:", ""); 
     //maybe add the key/token to a Session variable after your first successful authentication??? 
     var sessionKey = Session["someKey"] 

     var client = new JsonServiceClient("http://" + HttpContext.Request.Url.Authority + "/api") 
     { 
      LocalHttpWebRequestFilter = (r) => 
      { 
       var c = new CookieContainer(); 
       c.Add(new Uri("http://" + HttpContext.Request.Url.Authority + "/api"), new Cookie() { Name = "ss-id", Value = sessionKey }); 
       r.CookieContainer = c; 
      } 
     }; 

     return client; 
    } 

**,你可以從你client用於驗證對ServiceStack API值...像Session["someKey"] = client.CookieContainer.GetCookies(uri)["ss-id"].Value

+0

這正是我怎麼會做,存儲當前的的CookieContainer登錄用戶。忘了添加我自己的答案,但因爲你的答案完全一樣,所以我會接受這個答案。 – Taesti

相關問題