Link to home
Start Free TrialLog in
Avatar of mark clayton
mark clayton

asked on

how to impersonate the user with httpclient in netcore?

What is the best way to get a httpclient to impersonate the current httpcontext in .net core 2?

I have a core mvc application that is calling a core 2 webapi with httpclient. I have attached a cookiecontainer but there seems to be no easy way to pass the container the existing users browser cookies so it can correctly authenticate.
Avatar of ambience
ambience
Flag of Pakistan image

Are you able to debug and see if the required cookies are being passed to the API and what exactly is failing? The cookie path must be set to say "/" to enable all paths to see that cookie.

Alternatives


If the API is internal then can you use BasicAuthentication, passing plain user/pwd as header? A better approach however is to use JWT.

I wont be able to provide code example, but theoretically this situation calls for the use of JWT (JSON web Token) based authorization, if possible.  The ideal case is separating auth server from resource servers (something like single signon). See this for example

http://bitoftech.net/2014/09/24/decouple-owin-authorization-server-resource-server-oauth-2-0-web-api/

However, even in the case of having the API and MVC together, you can just copy Request's "Bearer" (or "Token") header into the HttpClient and let the API authenticate that JWT. A simple google search will provide explanations like

http://hamidmosalla.com/2017/10/19/policy-based-authorization-using-asp-net-core-2-and-json-web-token-jwt/

This may however require your client (if using Angular/Other for example) to be aware of JWT based authentication. ASP.NET core also allows you to use multiple Authentication schemes for different parts of the app, so for example the API part may require JWT but for the rest whatever is already in place can work.

I hope this gives you some pointers ..
Avatar of mark clayton
mark clayton

ASKER

Thanks for you pointers. The will look at the articles and come back asap.

To Illustrate the issue.

HttpContext.Request.Cookies = 6 cookies

I Instantiate a new HttpClient with a new Cookie Container > CookieCount = 0

I make the API Call . HttpClient Cookie Container Count = 1

HttpContext.Request.Cookies = 6 Cookies not 7

I current see no way to automatically pass the cookies from Request.Cookies to Cookie Container and vice versa.
This question needs an answer!
Become an EE member today
7 DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform.
View membership options
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.