How to write OAuth2 Web API Client in Asp.net MVC
To support the client credentials grant type, your best option is probably to directly use HttpClient
:
var request = new HttpRequestMessage(HttpMethod.Post, "http://server.com/token");request.Content = new FormUrlEncodedContent(new Dictionary<string, string> { { "client_id", "your client_id" }, { "client_secret", "your client_secret" }, { "grant_type", "client_credentials" }});var response = await client.SendAsync(request);response.EnsureSuccessStatusCode();var payload = JObject.Parse(await response.Content.ReadAsStringAsync());var token = payload.Value<string>("access_token");
For interactive flows (like the authorization code flow), there are two better approaches:
If your authorization server supports OpenID Connect (which is based on OAuth2), you can simply use the OpenID Connect middleware for OWIN/Katana 3 developed by Microsoft: https://www.nuget.org/packages/Microsoft.Owin.Security.OpenIdConnect/
If OpenID Connect is not supported by your authorization server, one option is to create your own OAuth2 client middleware. You can take a look at the last part of this SO answer for more information: Registering Web API 2 external logins from multiple API clients with OWIN Identity