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.
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.
ASKER
Thanks for you pointers. The will look at the articles and come back asap.
To Illustrate the issue.
HttpContext.Request.Cookie s = 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.Cookie s = 6 Cookies not 7
I current see no way to automatically pass the cookies from Request.Cookies to Cookie Container and vice versa.
To Illustrate the issue.
HttpContext.Request.Cookie
I Instantiate a new HttpClient with a new Cookie Container > CookieCount = 0
I make the API Call . HttpClient Cookie Container Count = 1
HttpContext.Request.Cookie
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 TRIALMembers 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.
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 ..