Authentication with OAuth2 and OpenID Connect (OIDC) in .NET Core with an Item API
Addon security for your API and your users.
Authentication is a critical part of modern web applications, and OAuth2 combined with OpenID Connect (OIDC) provides a robust and secure method for user authentication. In this blog, we'll explore how to implement OAuth2 and OIDC authentication in a .NET Core application, using an Item API as an example.
What is OAuth2?
OAuth2 is an open standard for access delegation, commonly used for token-based authentication. It allows third-party services to exchange credentials for access tokens, which can then be used to access protected resources on behalf of a user.
What is OpenID Connect (OIDC)?
OIDC is an identity layer built on top of OAuth2. It adds authentication by allowing clients to verify the identity of the user based on the authentication performed by an authorization server. OIDC also provides additional information about the user in the form of an ID token.
Why Use OAuth2 and OIDC?
Security: OAuth2 and OIDC provide secure mechanisms for authentication and authorization.
Standardization: These protocols are widely adopted and supported by many providers (e.g., Google, Microsoft, Facebook).
Decoupling: OAuth2 allows separation between the client application and the authentication mechanism, enabling the use of third-party authentication providers.
Implementing OAuth2 and OIDC in a .NET Core Application
Let's implement OAuth2 and OIDC authentication in a .NET Core application using the Item API as an example. We'll use a popular identity provider like Azure Active Directory (AAD) or Auth0, but the concepts apply to other providers as well.
1. Setting Up an Identity Provider
Before we begin coding, you need to register your application with an identity provider that supports OAuth2 and OIDC, such as Azure AD, Google, or Auth0. This process typically involves:
Creating an application in the provider's portal.
Configuring redirect URIs.
Obtaining the client ID and client secret.
2. Configuring Authentication in .NET Core
Once you have your client ID and secret, configure OAuth2 and OIDC in your .NET Core application by adding the required services in the Startup.cs
file.
Install the Necessary Packages
First, ensure you have the required NuGet packages:
dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer
dotnet add package Microsoft.IdentityModel.Protocols.OpenIdConnect
Configure Services in Startup.cs
Next, configure the authentication services:
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.Authority = "https://YOUR_AUTHORITY_URL"; // e.g., https://login.microsoftonline.com/{tenant}
options.Audience = "YOUR_CLIENT_ID"; // e.g., Client ID from your identity provider
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidIssuer = "https://YOUR_AUTHORITY_URL",
ValidateAudience = true,
ValidAudience = "YOUR_CLIENT_ID",
ValidateLifetime = true
};
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
In this configuration:
DefaultAuthenticateScheme
andDefaultChallengeScheme
are set toJwtBearerDefaults.AuthenticationScheme
, indicating that the app will use JWT (JSON Web Token) bearer tokens for authentication.Authority
points to the identity provider's endpoint, which is responsible for issuing tokens.Audience
is set to your application's client ID, ensuring that the token is intended for your application.
3. Securing the Item API with OAuth2 and OIDC
Now that authentication is configured, we can secure the Item API by adding the [Authorize]
attribute to the controller or specific actions.
Securing the Controller
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Linq;
namespace ItemApi.Controllers
{
[Route("api/[controller]")]
[ApiController]
[Authorize]
public class ItemsController : ControllerBase
{
private static List<Item> Items = new List<Item>
{
new Item { Id = 1, Name = "Item1", Description = "First item" },
new Item { Id = 2, Name = "Item2", Description = "Second item" },
};
[HttpGet]
public ActionResult<IEnumerable<Item>> GetItems()
{
return Ok(Items);
}
[HttpGet("{id}")]
public ActionResult<Item> GetItem(int id)
{
var item = Items.FirstOrDefault(i => i.Id == id);
if (item == null)
{
return NotFound();
}
return Ok(item);
}
// Other CRUD actions...
}
}
The [Authorize]
attribute ensures that only authenticated users can access the API. If a user tries to access the API without a valid token, they will receive a 401 Unauthorized response.
4. Testing the Authentication Flow
To test the authentication flow, you'll need to:
Obtain an access token from your identity provider. This typically involves redirecting the user to the provider's login page and then receiving an authorization code or token in return.
Use the access token in the
Authorization
header when making requests to the API.
Here’s an example of using the Authorization
header with a bearer token in a request:
GET /api/items HTTP/1.1
Host: localhost:5001
Authorization: Bearer YOUR_ACCESS_TOKEN
If the token is valid and correctly configured, the request will succeed and return the list of items.
Conclusion
Implementing authentication with OAuth2 and OpenID Connect (OIDC) in .NET Core is a powerful way to secure your applications while leveraging the security features provided by modern identity providers. By following the steps in this blog, you can integrate OAuth2 and OIDC into your .NET Core applications, ensuring that only authenticated users have access to your APIs.
The example of the Item API demonstrates how to configure authentication, secure endpoints, and handle tokens in .NET Core. Whether you're building a small API or a large-scale application, OAuth2 and OIDC provide the flexibility and security needed for modern web applications.