DEV Community

Cover image for OAuth2 in Microservices
Daniel Azevedo
Daniel Azevedo

Posted on

OAuth2 in Microservices

Hi devs,
In a microservices architecture, managing authentication and authorization can be complex. With multiple services communicating with each other and external clients, it's crucial to have a secure and standardized mechanism for handling user credentials and permissions. This is where OAuth2 shines.

In this post, we'll explore:

  • What is OAuth2?
  • How does it work in a microservices environment?
  • Implementing OAuth2 with practical examples in .NET.

What is OAuth2?

OAuth2 is an open authorization framework that enables secure access delegation. Instead of sharing credentials directly with third-party applications, users can grant limited access to their resources.

Key components of OAuth2:

  • Resource Owner: The user who owns the data.
  • Client: The application requesting access to the data.
  • Resource Server: The server hosting the user's data (e.g., an API).
  • Authorization Server: Responsible for verifying users and issuing access tokens.

Why Use OAuth2 in Microservices?

In a microservices architecture, OAuth2 provides a unified and secure approach to authentication and authorization. Benefits include:

  1. Centralized Authentication: OAuth2 allows authentication to be managed by a dedicated authorization server, reducing redundancy.
  2. Scalability: Each microservice validates access tokens independently, ensuring scalability.
  3. Security: Access tokens expire and can be scoped, minimizing risks.
  4. Separation of Concerns: Authentication logic is decoupled from business logic.

OAuth2 Flow in Microservices

Here’s how OAuth2 typically works in a microservices architecture:

  1. User Authentication:

    The client application sends the user to the authorization server for authentication.

  2. Token Issuance:

    After successful authentication, the authorization server issues an access token to the client.

  3. Token Validation:

    The client sends the access token to the resource server (microservices) for access.

  4. Access Granted:

    The resource server validates the token and grants or denies access.


Implementation Example: OAuth2 in .NET Microservices

Let’s build a simple OAuth2 implementation with:

  • IdentityServer4 as the Authorization Server.
  • A Resource API and a Client Application.

1. Setting Up the Authorization Server

Install IdentityServer4 via NuGet:

dotnet add package IdentityServer4
Enter fullscreen mode Exit fullscreen mode

Configure the server in Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    services.AddIdentityServer()
        .AddInMemoryClients(new[]
        {
            new Client
            {
                ClientId = "client-app",
                AllowedGrantTypes = GrantTypes.ClientCredentials,
                ClientSecrets = { new Secret("secret".Sha256()) },
                AllowedScopes = { "api1" }
            }
        })
        .AddInMemoryApiScopes(new[] { new ApiScope("api1", "My API") })
        .AddDeveloperSigningCredential();
}

public void Configure(IApplicationBuilder app)
{
    app.UseIdentityServer();
}
Enter fullscreen mode Exit fullscreen mode

Run the server and it will handle authentication and token issuance.


2. Creating the Resource API

Add a new microservice to act as the resource server. Install the Microsoft.AspNetCore.Authentication.JwtBearer package:

dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer
Enter fullscreen mode Exit fullscreen mode

Configure token validation in Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthentication("Bearer")
        .AddJwtBearer("Bearer", options =>
        {
            options.Authority = "http://localhost:5000"; // Authorization server
            options.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateAudience = false
            };
        });

    services.AddAuthorization();
    services.AddControllers();
}

public void Configure(IApplicationBuilder app)
{
    app.UseRouting();
    app.UseAuthentication();
    app.UseAuthorization();
    app.UseEndpoints(endpoints => endpoints.MapControllers());
}
Enter fullscreen mode Exit fullscreen mode

Create a secured endpoint:

[ApiController]
[Route("api/resource")]
public class ResourceController : ControllerBase
{
    [HttpGet]
    [Authorize]
    public IActionResult Get()
    {
        return Ok("Protected resource accessed.");
    }
}
Enter fullscreen mode Exit fullscreen mode

3. Building the Client Application

Install the IdentityModel library for token requests:

dotnet add package IdentityModel
Enter fullscreen mode Exit fullscreen mode

Request a token and access the resource:

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

var client = new HttpClient();
var tokenResponse = await client.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest
{
    Address = "http://localhost:5000/connect/token",
    ClientId = "client-app",
    ClientSecret = "secret",
    Scope = "api1"
});

client.SetBearerToken(tokenResponse.AccessToken);
var response = await client.GetAsync("http://localhost:5001/api/resource");
Console.WriteLine(await response.Content.ReadAsStringAsync());
Enter fullscreen mode Exit fullscreen mode

Use Case: OAuth2 in HR Systems

Consider a Human Resources (HR) system with the following microservices:

  • Employee Service: Stores employee details.
  • Payroll Service: Manages salaries.
  • Leave Management Service: Handles leave requests.

How OAuth2 fits in:

  • The Authorization Server issues tokens to HR staff.
  • Each service validates tokens before processing requests.
  • Access scopes ensure users only access data they are authorized for.

Conclusion

OAuth2 is a robust framework that simplifies authentication and authorization in microservices. By centralizing token issuance and validation, it ensures scalability, security, and ease of maintenance.

Top comments (0)