How to add FormsAuthentication cookie to HttpClient HttpRequestMessage

守給你的承諾、 提交于 2019-12-06 12:39:23

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

CookiContainer property will allow to access cookies collection.

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.

Almost 6 years late, but still may be helpful. The solution based on this one: https://blogs.taiga.nl/martijn/2016/03/10/asp-net-web-api-owin-authenticated-integration-tests-without-authorization-server/

First, while creating Owin TestServer you have to create DataProtector:

    private readonly TestServer _testServer;
    public IDataProtector DataProtector { get; private set; }

    public Server(OwinStartup startupConfig)
    {
        _testServer = TestServer.Create(builder =>
        {
            DataProtector = builder.CreateDataProtector(
                typeof(CookieAuthenticationMiddleware).FullName, DefaultAuthenticationTypes.ApplicationCookie, "v1");

            startupConfig.Configuration(builder);
        });
    }

Then generate cookie like this (use DataProtector created in previous step):

    public string GeterateCookie()
    {
        var claims = new List<Claim>
        {
            new Claim(ClaimTypes.Role, "your-role"),
            new Claim(ClaimTypes.UserData, "user-data"),
            new Claim(ClaimTypes.Name, "your-name")
        };

        var identity = new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie, ClaimTypes.Name, ClaimTypes.Role);

        var tdf = new TicketDataFormat(DataProtector);
        var ticket = new AuthenticationTicket(identity, new AuthenticationProperties {ExpiresUtc = DateTime.UtcNow.AddHours(1)});

        var protectedCookieValue = tdf.Protect(ticket);

        var cookie = new CookieHeaderValue("yourCookie", protectedCookieValue)
        {
            Path = "/",
            HttpOnly = true
        };

        return cookie.ToString();
    }

Make sure to set required claims, initialize ClaimsIdentity according to settings provided to UseCookieAuthentication method, and setting correct CookieName.

The last step is to add CookieHeader to your request:

    public Task<HttpResponseMessage> RequestAsync(HttpRequestMessage request)
    {
        request.Headers.Add("cookie", GenerateCookie());
        return _client.SendAsync(request);
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!