Implementing Client Credentials Grant Type Using Owin In ASP.NET Web API


This article demonstrates implementation of Client Credentials Grant Type to authorize WebAPI.This grant type would be useful in case of machine-to-machine communication and when client and resource owner are the same entity and separate user entity is not involved.
To implement this we will use Microsoft.OwinNuget Packages into ASP.NET WebAPI project to configure OAuth.
This is one of the approaches to support OAuth2.0 into legacy applications where user activity is not directly involved and client application to server application interaction has been performed. Depending on the use case and requirement, we can choose different type of grants.However, modern application generally used OpenID Connect implementation using IdentityServer4.
Related Reads

Configuring OAuth Provider Using Owin

Let’s create a sample ASP.NET WebAPI project. We are going to create two endpoints to test the token, which are /oauth2/token and api/getvalues. Client app will call “/oauth2/token” endpoint to generate access token.
Once default WebAPI project template is loaded, install Nuget packages that are required to set up our OWIN server.
  • Owin.Security.OAuth
  • Owin.Host.SystemWeb
Add a new folder named "Providers" to the project then add new class named "OAuthProvider", paste the below code snippet to it where "OAuthProvider" class inherits from class "OAuthAuthorizationServerProvider".
  1. using System;  
  2. using System.Configuration;  
  3. using System.Security.Claims;  
  4. using System.Threading.Tasks;  
  5. using Microsoft.Owin.Security.OAuth;  
  6. namespace OAuth2App.Provider {  
  7.     public class OAuthProvider: OAuthAuthorizationServerProvider {  
  8.         public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context) {  
  9.             string clientId;  
  10.             string clientSecret;  
  11.             Guid client IdGuid;  
  12.             if (!context.TryGetBasicCredentials(outclientId, outclientSecret)) {  
  13.                 context.TryGetFormCredentials(outclientId, outclientSecret);  
  14.             }  
  15.             if (null == context.ClientId || null == clientSecret || !Guid.TryParse(clientId, outclientIdGuid)) {  
  16.                 context.SetError("invalid_credentials""A valid client_Id and client_Secret must be provided.");  
  17.                 context.Rejected();  
  18.                 return;  
  19.             }  
  20.             //validate aginstdb or config: GetClient(clientIdGuid, clientSecret);  
  21.             bool is Valid Client = Configuration Manager.AppSettings["ClientId"] == clientId && Configuration Manager.AppSettings["ClientSecret"] == clientSecret;  
  22.             if (!isValidClient) {  
  23.                 context.SetError("invalid_credentials""A valid client_Id and client_Secret must be provided.");  
  24.                 context.Rejected();  
  25.                 return;  
  26.             }  
  27.             awaitTask.Run(() => context.Validated(clientId));  
  28.         }  
  29.         public override async Task GrantClientCredentials(OAuthGrantClientCredentialsContext context) {  
  30.             GuidclientId;  
  31.             Guid.TryParse(context.ClientId, outclientId);  
  32.             //validate aginstdb or config: GetByClientId(clientId);  
  33.             bool client = ConfigurationManager.AppSettings["ClientId"] == clientId.ToString().ToUpper();  
  34.             if (!client) {  
  35.                 context.SetError("invalid_grant""Invaild client.");  
  36.                 context.Rejected();  
  37.                 return;  
  38.             }  
  39.             var claims Identity = newClaimsIdentity(context.Options.AuthenticationType);  
  40.             claims Identity.AddClaim(new Claim("LoggedOn", DateTime.Now.ToString()));  
  41.             await Task.Run(() => context.Validated(claimsIdentity));  
  42.         }  
  43.         public override Task TokenEndpoint(OAuthTokenEndpointContext context) {  
  44.             if (context.TokenIssued) {  
  45.                 context.Properties.ExpiresUtc = DateTimeOffset.UtcNow.AddSeconds(3600);  
  46.             }  
  47.             return Task.FromResult < object > (null);  
  48.         }  
  49.     }  
  50. }  
Here, we have overridden three methodsc alled "ValidateClientAuthentication", "GrantClientCredentials" and “TokenEndpoint”.
  • The "ValidateClientAuthentication" method is responsible for validating client id and client secret against web.config or DB.Inside it, "TryGetBasicCredentials" used to retrieve the values of the client credential from basic authorization header. In addition, "TryGetFormCredentials" used to retrieve client id and secret as form-encoded POST parameters.
  • The "GrantClientCredentials" method is responsible to validate the client id before adding claims details into the access token. Based on the need, we can add different sets of claims.
  • The "TokenEndpoint" method is responsible to override token lifetime. If you have multiple clients,  app and token lifetime varies based on the client, then this override method will be useful to set it. 
Every OWIN application has a startup class. Add "OWIN Startup" class in which we specify components for the application pipeline.
Implementing Client Credentials Grant Type Using Owin In ASP.NET Web API 
Here we are using the OwinStartup Attribute to connect to the startup class with the hosting runtime.
  1. using Microsoft.Owin;  
  2. using Microsoft.Owin.Security.OAuth;  
  3. using OAuth2App.Provider;  
  4. using Owin;  
  5. using System;  
  6. [assembly: OwinStartup(typeof(OAuth2App.Startup))]  
  7. namespace OAuth2App {  
  8.     public class Startup {  
  9.         public void Configuration(IAppBuilder app) {  
  10.             Configure Auth(app);  
  11.         }  
  12.         public void ConfigureAuth(IAppBuilder app) {  
  13.             var oAuthOptions = new OAuthAuthorizationServerOptions {  
  14.                 Allow InsecureHttp = true// need set to false in PROD  
  15.                     Token EndpointPath = newPathString("/oauth2/token"),  
  16.                     Access Token ExpireTimeSpan = TimeSpan.FromMinutes(60), //token expiration time  
  17.                     Provider = new OAuthProvider(),  
  18.             };  
  19.             app.UseOAuthBearerTokens(oAuthOptions);  
  20.             app.UseOAuthAuthorizationServer(oAuthOptions);  
  21.         }  
  22.     }  
  23. }  
Here we created a new instance of the "OAuthAuthorizationServerOptions" class where we set token endpoint path ashttp://localhost:port/oauth2/token and token expiry time as 60 minutes.We have also specified custom class called “OAuthProvider” to validate the client. This class has already  been created in earlier steps.

OAuth Client Registration

Before using OAuth, client application must be registered into authorization server.
Once the client is being registered, authorization server will provide Client ID and Client secret to client, and then the client will use this while requesting access token.
The client id is the publicly exposed string that is used by the authorization server to identify the client application. In my case, I used GUID.
The client secret must be kept private between client and authorization server and used to authenticate client app when client is requesting for user resources. In my case, I created a cryptographic string using the below code.
  1. Random Number Generator crypto RandomDataGenerator = newRNGCryptoServiceProvider();  
  2. byte[] buffer = newbyte[32];  
  3. cryptoRandomDataGenerator.GetBytes(buffer);  
  4. string clientSecret = Convert.ToBase64String(buffer);  

Creating and Authorizing an API

Now create an action method called "GetValues" and added [Authorize] attribute into it so that we can validate access token. Here, we will retrieve claims from token that we added during token generation.
  1. [Authorize]  
  2. [HttpGet]  
  3. [Route("getvalues")]  
  4. public IHttp Action Result GetValues() {  
  5.     var identity = (ClaimsIdentity) User.Identity;  
  6.     var LogTime = identity.Claims.FirstOrDefault(c => c.Type == "LoggedOn").Value;  
  7.     return Ok("Hi, You are Authorized! Your LoggedOn Time: " + LogTime);  
  8. }  Generating Access Token from Postman and Used for API access
Aright! Now we are ready to run WebAPI application and test API from Postman.
If we access API https://localhost:44374/getvalues without access token, we will get unauthorizedresponse with code 401.
Implementing Client Credentials Grant Type Using Owin In ASP.NET Web API 
Let’s generate access token with valid credentials. Here, we will get status code 200 Ok and access token value, token type as Bearer and the token expire time in seconds in the Response section.
Implementing Client Credentials Grant Type Using Owin In ASP.NET Web API 
When requesting a token with invalid client credentials.
Implementing Client Credentials Grant Type Using Owin In ASP.NET Web API 
Now we use valid access token and add it to Authorization header while accessing API.
Implementing Client Credentials Grant Type Using Owin In ASP.NET Web API 

Sample Http Request from .NET application using Access Token

Create the following Token class, which will used to de-serialize token object.
  1. internal class Token {  
  2.     [JsonProperty("access_token")]  
  3.     public string AccessToken {  
  4.         get;  
  5.         set;  
  6.     }  
  7.     [JsonProperty("token_type")]  
  8.     public string TokenType {  
  9.         get;  
  10.         set;  
  11.     }  
  12.     [JsonProperty("expires_in")]  
  13.     public int ExpiresIn {  
  14.         get;  
  15.         set;  
  16.     }  
  17. }  
To generate access token first, An HTTP POST request made to the URL "/oauth2/token" endpoint with grant_type parameter "client_credentials"; then we will pass this token to API access.
  1. string base Address = "https://localhost:44374";  
  2. var client = newHttpClient();  
  3. var form = new Dictionary < string,  
  4.     string > {  
  5.         {  
  6.             "grant_type",  
  7.             "client_credentials"  
  8.         },  
  9.         {  
  10.             "client_id",  
  11.             ConfigurationManager.AppSettings["ClientId"]  
  12.         },  
  13.         {  
  14.             "client_secret",  
  15.             ConfigurationManager.AppSettings["ClientSecret"]  
  16.         },  
  17.     };  
  18. var tokenResponse = client.PostAsync(baseAddress + "/oauth2/token", newFormUrlEncodedContent(form)).Result;  
  19. var token = tokenResponse.Content.ReadAsAsync < Token > (new [] {  
  20.     newJsonMediaTypeFormatter()  
  21. }).Result;  
  22. client.DefaultRequestHeaders.Authorization = newAuthenticationHeaderValue("Bearer", token.AccessToken);  
  23. var authorizedResponse = client.GetAsync(baseAddress + "/api/getvalues").Result;  


In this article, we have implemented client credentials grant type using Owin packages. In addition, we have seen how we add claims into access token and retrieve the same while accessing the API. Hope you find this article short and simple! Happy Reading!