TheWebGuy
TheWebGuy

Reputation: 12515

Web API 2 and HttpClient

I have a web api and MVC project,

The web api is deployed at api.domain.com The MVC app is deployed at domain.com

I recently secured certain methods on the API, it requires authentication (grant type: password).

I want to have the token passed around in the code behind of the MVC app and not javascript, to keep it secure and away from someone sniffing angular js traffic.

I did some research and I should use the HttpClient class. If this is the case how does this client handle refresh tokens? Right now the token expires after 8 hours, I know a refresh token is also issued but does the HttpClient automatically handle this or do I have to write my own logic to check if a request was denied due to an expired token.

Thank you!

Upvotes: 0

Views: 543

Answers (2)

abhisheknirmal
abhisheknirmal

Reputation: 116

I think using a HttpMessageHandler can help you.

The way this is wired up to an HttpClient is by using the HttpClient constructor that takes a HttpMessagHandler:

1: // Create client and insert an OAuth message handler in the message path that

2: // inserts an OAuth authentication header in the request

3: HttpClient client = new HttpClient(new OAuthMessageHandler(new HttpClientHandler()));

The HttpClientHandler is the default “network” handler provided by HttpClient that actually sends the request and received the response from the network.

Refer this for complete detail: https://blogs.msdn.microsoft.com/henrikn/2012/02/16/extending-httpclient-with-oauth-to-access-twitter/

Upvotes: 2

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

I did some research and I should use the HttpClient class. If this is the case how does this client handle refresh tokens?

The HttpClient class is, as its name suggest, an HTTP protocol client. It knows strictly nothing about OAuth 2.0 and in this respect nothing about refresh tokens. So you should write this logic yourself. Basically the flow you should follow is something along those lines:

  1. Send an HTTP request t othe target endpoint using the HttpClient and including your existing OAuth Bearer token in the Authorization header field.
  2. If the request succeeds then you are good to go. If the request fails with 401, then you should use your refresh token in order to renew your access token and then repeat step 1 with your new access token.

Upvotes: 3

Related Questions