OAuth client for C# (.NET): IdentityModel library and OAuth 2.0 integration

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

IdentityModel library for OAuth 2.0 and OpenID Connect in C# (.NET)



When developing modern web applications, mobile clients, or server-side APIs on the .NET platform, there is almost always a need to integrate with external authentication providers (Google, GitHub, Microsoft, etc.) or your own authorization server. IdentityModel is a lightweight yet powerful library for C# that provides a convenient OAuth client for working with OAuth 2.0 and OpenID Connect protocols. It is the de facto standard in the .NET ecosystem for implementing authorization flows.



In this article, we will detail how to use IdentityModel to create an OAuth client, obtain access tokens, and refresh them. Code examples will be in C# (.NET 6+).



Installation and setup



To get started, install the package via NuGet Package Manager:



dotnet add package IdentityModel


Or via the Package Manager Console:



Install-Package IdentityModel


After installation, you gain access to HttpClient extensions, DiscoveryClient, TokenClient classes, and other helper utilities.



Basic scenario: obtaining a token via Client Credentials



This flow is used for server-to-server authentication, where the client (your application) requests a token on its own behalf, not on behalf of a user.



Example of OAuth client setup:



using IdentityModel.Client;using System.Net.Http;using System.Threading.Tasks;

public async Task<string> GetAccessTokenAsync(){ var client = new HttpClient();

// 1. Get the discovery document from the authorization server var disco = await client.GetDiscoveryDocumentAsync("https://your-auth-server.com"); if (disco.IsError) { throw new Exception($"Error getting discovery: {disco.Error}"); }

// 2. Request a token using client_id and client_secret var tokenResponse = await client.RequestClientCredentialsTokenAsync( new ClientCredentialsTokenRequest { Address = disco.TokenEndpoint, ClientId = "your-client-id", ClientSecret = "your-client-secret", Scope = "api1 api2" // requested permissions });

if (tokenResponse.IsError) { throw new Exception($"Error getting token: {tokenResponse.Error}"); }

return tokenResponse.AccessToken;}


In this example, we use extension methods from the IdentityModel.Client namespace. The library automatically handles JSON serialization, headers, and response parsing.



Authorization Code flow (with user involvement)



For applications with a user interface (ASP.NET Core MVC, Blazor, desktop), the authorization code is more commonly used. IdentityModel integrates with Microsoft.AspNetCore.Authentication.OpenIdConnect, but also provides low-level tools for manual implementation.



Example of obtaining a token after a redirect with a code:



public async Task<TokenResponse> ExchangeCodeForTokenAsync(string authorizationCode, string redirectUri){    var client = new HttpClient();    var disco = await client.GetDiscoveryDocumentAsync("https://your-auth-server.com");

var tokenResponse = await client.RequestAuthorizationCodeTokenAsync( new AuthorizationCodeTokenRequest { Address = disco.TokenEndpoint, ClientId = "your-client-id", ClientSecret = "your-client-secret", Code = authorizationCode, RedirectUri = redirectUri });

return tokenResponse;}


Token refresh (Refresh Token)



Access tokens typically have a short lifespan (e.g., 1 hour).

Recommendations