2

I've set up a ServiceStack api with a custom auth provider. This all works fine and I can authenticate and use the api as I like.

I've got a seperate MVC4 application with FormsAuthentication that will use this api to validate it's users. After the username/password was validated by the Api, I want to keep all the subsequent requests from the client validated. I know that the client gets cookies set in the CookieContainer and if I keep the same client all requests will stay validated.

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

But I don't want to post the auth to the api everytime I want to do a request (although this is an option). I found this gist https://gist.github.com/danmiser/1701803 (old version of ServiceStack I think) where that happens.

I've also thought about setting the cookies that are returned on the client side of the MVC4 app and adding them to the CookieContainer of the client for subsequent requests after authentication.

Is there a better/standard way to do this? Am I missing something obvious?

4

1 回答 1

3

I've used a 'helper method' to return a JsonServiceClient that is authenticated with a session cookie. You'll need to figure out a way to store and supply the authenticated cookie value**. I think the easiest way would be to store it in the MVC Session.

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

** you can get the value from the client you use for authenticating against the ServiceStack API...something like Session["someKey"] = client.CookieContainer.GetCookies(uri)["ss-id"].Value

于 2013-07-22T22:31:27.887 回答