OAuth 2.0 and JWT Authorization in C#: A Practical Guide

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

Introduction: Why OAuth 2.0 and JWT are Needed in Modern Applications?

\n

In modern web development, data security and access management come to the forefront. Every day, millions of users log into applications via Google, Facebook, or corporate systems without directly sharing their passwords. This is where the OAuth 2.0 protocol and JWT (JSON Web Tokens) technology come into play.

\n

OAuth 2.0 is an industry standard for delegated access. It allows applications to obtain limited access to user resources without revealing their credentials. JWT, in turn, is a compact and self-contained token format that contains all the necessary information for authentication and authorization.

\n

In this article, we will practically explore how to implement OAuth 2.0 and JWT authorization in C# using ASP.NET Core. You will learn how to set up an authorization server, generate tokens, and protect your API endpoints. All code examples are ready for use in real projects.

\n\n

1. Setting Up an Authorization Server with IdentityServer4

\n

To implement OAuth 2.0, we will use the popular library IdentityServer4 — a framework for ASP.NET Core that implements the OpenID Connect and OAuth 2.0 protocols. Let's start by creating a minimal authorization server.

\n\n

Step 1: Installing Packages and Creating the Project

\n

Create a new ASP.NET Core Web Application (empty template) and install the required NuGet packages:

\n
dotnet add package IdentityServer4\ndotnet add package Microsoft.AspNetCore.Authentication.JwtBearer
\n\n

Step 2: Configuring Clients and Resources

\n

Define test users, clients, and protected resources. Create a Config.cs class:

\n
public static class Config\n{\n    public static IEnumerable<IdentityResource> IdentityResources =>\n        new[] { new IdentityResources.OpenId(), new IdentityResources.Profile() };\n\n    public static IEnumerable<ApiScope> ApiScopes =>\n        new[] { new ApiScope("api1", "My API") };\n\n    public static IEnumerable<Client> Clients =>\n        new[]\n        {\n            new Client\n            {\n                ClientId = "client",\n                AllowedGrantTypes = GrantTypes.ClientCredentials,\n                ClientSecrets = { new Secret("secret".Sha256()) },\n                AllowedScopes = { "api1" }\n            }\n        };\n}
\n\n

Step 3: Registering Services in Startup.cs

\n

Configure IdentityServer in the ConfigureServices method:

\n
public void ConfigureServices(IServiceCollection services)\n{\n    services.AddIdentityServer()\n        .AddInMemoryIdentityResources(Config.IdentityResources)\n        .AddInMemoryApiScopes(Config.ApiScopes)\n        .AddInMemoryClients(Config.Clients)\n        .AddTestUsers(TestUsers.Users);\n\n    services.AddAuthentication()\n        .AddJwtBearer("Bearer", options =>\n        {\n            options.Authority = "https://localhost:5001";\n            options.TokenValidationParameters = new TokenValidationParameters\n            {\n                ValidateAudience = false\n            };\n        });\n}
\n

In the Configure method, add the call app.UseIdentityServer().

\n\n

2. Implementing JWT Tokens: Generation and Validation

\n

A JWT token consists of three parts: header, payload, and signature. In .NET, JWT generation and validation are handled using built-in mechanisms.

\n\n

Manual JWT Token Generation

\n

Sometimes you need to create a token manually, for example, for testing. Use the following code:

\n
using System.IdentityModel.Tokens.Jwt;\nusing Microsoft.IdentityModel.Tokens;\nusing System.Security.Claims;\nusing System.Text;\n\npublic string GenerateJwtToken(string userI                

Blogs

Book Recommendations