Introduction: Why OAuth 2.0 and JWT are Needed in Modern Applications?
\nIn 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.
\nOAuth 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.
\nIn 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\n1. Setting Up an Authorization Server with IdentityServer4
\nTo 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\nStep 1: Installing Packages and Creating the Project
\nCreate a new ASP.NET Core Web Application (empty template) and install the required NuGet packages:
\ndotnet add package IdentityServer4\ndotnet add package Microsoft.AspNetCore.Authentication.JwtBearer\n\nStep 2: Configuring Clients and Resources
\nDefine test users, clients, and protected resources. Create a Config.cs class:
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\nStep 3: Registering Services in Startup.cs
\nConfigure IdentityServer in the ConfigureServices method:
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}\nIn the Configure method, add the call app.UseIdentityServer().
2. Implementing JWT Tokens: Generation and Validation
\nA JWT token consists of three parts: header, payload, and signature. In .NET, JWT generation and validation are handled using built-in mechanisms.
\n\nManual JWT Token Generation
\nSometimes you need to create a token manually, for example, for testing. Use the following code:
\nusing System.IdentityModel.Tokens.Jwt;\nusing Microsoft.IdentityModel.Tokens;\nusing System.Security.Claims;\nusing System.Text;\n\npublic string GenerateJwtToken(string userI