2013-07-18 131 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

相关问题