如何FormsAuthentication Cookie添加到HttpClient的Htt的prequestMessage [英] How to add FormsAuthentication cookie to HttpClient HttpRequestMessage
问题描述
我想通过调用FormsAuthentication.SetAuthCookie(指someUser,FALSE)集成测试里验证;结果
从那以后,我确实需要调用的WebAPI因为我已授权应用的属性没有得到授权例外。
我用这code创建AUTH的cookie:
I am trying to authenticate inside integration test by calling FormsAuthentication.SetAuthCookie("someUser", false);
After that I do need to call WebAPI and not receive unauthorized exception because I have authorized attribute applied.
I am using this code to create auth cookie :
var cookie = FormsAuthentication.GetAuthCookie(name, rememberMe);
var ticket = FormsAuthentication.Decrypt(cookie.Value);
var newTicket = new FormsAuthenticationTicket(ticket.Version, ticket.Name, ticket.IssueDate, ticket.Expiration,
ticket.IsPersistent, userData.ToJson(), ticket.CookiePath);
var encTicket = FormsAuthentication.Encrypt(newTicket);
/// Use existing cookie. Could create new one but would have to copy settings over...
cookie.Value = encTicket;
现在我想这个cookie添加到Htt的prequestMessage内新的HttpClient并在集成测试我的正常发送请求这一点。
Now I want to add this cookie to HttpRequestMessage inside new HttpClient and send this with my regular request in integration test.
我不知道如何处理身份验证Cookie添加到Htt的prequestMessage?
I don't know how to add that auth cookie to HttpRequestMessage ?
推荐答案
有关操纵饼干,你需要使用的 WebRequestHandler 与的HttpClient
。例如,
For manipulating cookies, you need to use WebRequestHandler along with HttpClient
. For example,
var handler = new WebRequestHandler();
var client = new HttpClient(handler);
// use handler to configure request such as add cookies to send to server
<一个href=\"http://msdn.microsoft.com/en-us/library/system.net.http.httpclienthandler.cookiecontainer.aspx\"相对=nofollow> CookiContainer 属性将允许访问Cookies集合。
CookiContainer property will allow to access cookies collection.
在不同的说明,我怀疑在客户端创建FormsAuthentication cookie将正常工作。将需要客户端/服务器上的相同的加密密钥。最好的办法是重播实际的Web API登录请求 - 最有可能,这将是使用用户凭据登录页面POST。观察同样在浏览器中使用的工具,如提琴手和构建你的HTTP客户端内同样的要求。
On different note, I doubt if creating FormsAuthentication cookie on client will work. A same encryption key would be needed on both client/server. The best approach would be to replay the login request for actual web API - most probably, it would be a POST to login page with user credentials. Observe the same over browser using tool such as Fiddler and construct the same request within your http client.
这篇关于如何FormsAuthentication Cookie添加到HttpClient的Htt的prequestMessage的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!