Convert Figma logo to code with AI

openiddict logoopeniddict-core

Flexible and versatile OAuth 2.0/OpenID Connect stack for .NET

4,324
506
4,324
16

Top Related Projects

The most flexible and standards-compliant OpenID Connect and OAuth 2.x framework for ASP.NET Core

OpenID Connect and OAuth 2.0 Framework for ASP.NET Core

IdentityModel extensions for .Net

.NET standard helper library for claims-based identity, OAuth 2.0 and OpenID Connect.

ASP.NET Core is a cross-platform .NET framework for building modern cloud-based web applications on Windows, Mac, or Linux.

Quick Overview

OpenIddict is a versatile OpenID Connect server and OAuth 2.0 authorization server framework for ASP.NET Core. It provides a comprehensive solution for implementing authentication and authorization in .NET applications, supporting various flows and extensions of the OpenID Connect and OAuth 2.0 protocols.

Pros

  • Highly customizable and extensible architecture
  • Supports multiple flows including authorization code, implicit, hybrid, client credentials, and resource owner password credentials
  • Integrates well with ASP.NET Core Identity and Entity Framework Core
  • Active development and community support

Cons

  • Steep learning curve for beginners due to its extensive feature set
  • Documentation can be overwhelming for newcomers
  • Requires careful configuration to ensure security best practices
  • May be overkill for simple authentication scenarios

Code Examples

  1. Configuring OpenIddict services:
public void ConfigureServices(IServiceCollection services)
{
    services.AddOpenIddict()
        .AddCore(options =>
        {
            options.UseEntityFrameworkCore()
                   .UseDbContext<ApplicationDbContext>();
        })
        .AddServer(options =>
        {
            options.SetAuthorizationEndpointUris("/connect/authorize")
                   .SetTokenEndpointUris("/connect/token");

            options.AllowAuthorizationCodeFlow()
                   .AllowRefreshTokenFlow();

            options.AddDevelopmentEncryptionCertificate()
                   .AddDevelopmentSigningCertificate();

            options.UseAspNetCore()
                   .EnableTokenEndpointPassthrough()
                   .EnableAuthorizationEndpointPassthrough();
        });
}
  1. Implementing an authorization endpoint:
[HttpGet("~/connect/authorize")]
public async Task<IActionResult> Authorize()
{
    var request = HttpContext.GetOpenIddictServerRequest() ??
        throw new InvalidOperationException("The OpenID Connect request cannot be retrieved.");

    var result = await HttpContext.AuthenticateAsync(CookieAuthenticationDefaults.AuthenticationScheme);
    if (result?.Succeeded != true)
    {
        return Challenge(
            authenticationSchemes: CookieAuthenticationDefaults.AuthenticationScheme,
            properties: new AuthenticationProperties
            {
                RedirectUri = Request.PathBase + Request.Path + QueryString.Create(
                    Request.HasFormContentType ? Request.Form.ToList() : Request.Query.ToList())
            });
    }

    var claims = new List<Claim>
    {
        new Claim(OpenIddictConstants.Claims.Subject, result.Principal.Identity.Name),
        new Claim("some_claim", "some_value").SetDestinations(OpenIddictConstants.Destinations.AccessToken)
    };

    return SignIn(
        new ClaimsPrincipal(new ClaimsIdentity(claims, OpenIddictServerAspNetCoreDefaults.AuthenticationScheme)),
        OpenIddictServerAspNetCoreDefaults.AuthenticationScheme);
}
  1. Validating a token:
public class ResourceController : Controller
{
    [Authorize(AuthenticationSchemes = OpenIddictValidationAspNetCoreDefaults.AuthenticationScheme)]
    [HttpGet("~/api/resource")]
    public IActionResult GetResource()
    {
        var claim = User.FindFirst("some_claim");
        if (claim == null)
        {
            return BadRequest();
        }

        return Content($"Value: {claim.Value}");
    }
}

Getting Started

  1. Install the NuGet packages:

    dotnet add package OpenIddict.AspNetCore
    dotnet add package OpenIddict.EntityFrameworkCore
    
  2. Configure OpenIddict in Startup.cs:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddOpenIddict()
            .AddCore(options => 
            {
                options.UseEntityFrameworkCore()
                       .UseDbContext<ApplicationDbContext>();
            })
    

Competitor Comparisons

The most flexible and standards-compliant OpenID Connect and OAuth 2.x framework for ASP.NET Core

Pros of IdentityServer

  • More comprehensive documentation and extensive community support
  • Offers additional features like device flow and CIBA (Client Initiated Backchannel Authentication)
  • Provides a more polished UI for management and administration

Cons of IdentityServer

  • Commercial licensing required for production use
  • Steeper learning curve due to its extensive feature set
  • Less flexibility in customization compared to OpenIddict

Code Comparison

OpenIddict:

services.AddOpenIddict()
    .AddCore(options => { /* ... */ })
    .AddServer(options => { /* ... */ })
    .AddValidation(options => { /* ... */ });

IdentityServer:

services.AddIdentityServer()
    .AddInMemoryApiScopes(Config.ApiScopes)
    .AddInMemoryClients(Config.Clients)
    .AddDeveloperSigningCredential();

Both frameworks offer similar configuration approaches, but OpenIddict provides more granular control over individual components. IdentityServer's setup is more concise but may require additional configuration for advanced scenarios.

While IdentityServer offers a more complete out-of-the-box solution with robust features, OpenIddict provides greater flexibility and is free for all use cases. The choice between the two depends on specific project requirements, budget constraints, and desired level of customization.

OpenID Connect and OAuth 2.0 Framework for ASP.NET Core

Pros of IdentityServer4

  • More mature and widely adopted in the industry
  • Extensive documentation and community support
  • Offers a broader range of features out-of-the-box

Cons of IdentityServer4

  • Licensing changes (now requires a commercial license for production use)
  • More complex setup and configuration
  • Steeper learning curve for beginners

Code Comparison

IdentityServer4 configuration:

services.AddIdentityServer()
    .AddInMemoryClients(Config.Clients)
    .AddInMemoryApiScopes(Config.ApiScopes)
    .AddInMemoryIdentityResources(Config.IdentityResources)
    .AddDeveloperSigningCredential();

OpenIddict configuration:

services.AddOpenIddict()
    .AddCore(options => options.UseEntityFrameworkCore().UseDbContext<ApplicationDbContext>())
    .AddServer(options => options.UseAspNetCore().EnableTokenEndpoint("/connect/token"))
    .AddValidation();

Both IdentityServer4 and OpenIddict-core are powerful OpenID Connect and OAuth 2.0 frameworks for ASP.NET Core. IdentityServer4 has been around longer and offers more features, but its recent licensing changes have led some developers to consider alternatives like OpenIddict. OpenIddict is gaining popularity due to its simplicity and open-source nature. The choice between the two depends on specific project requirements, budget constraints, and desired level of control over the authentication process.

IdentityModel extensions for .Net

Pros of azure-activedirectory-identitymodel-extensions-for-dotnet

  • Extensive support for Azure AD and Microsoft identity platform
  • Robust token validation and handling capabilities
  • Well-documented and maintained by Microsoft

Cons of azure-activedirectory-identitymodel-extensions-for-dotnet

  • More focused on Microsoft-specific scenarios, less flexible for other providers
  • Steeper learning curve for developers not familiar with Azure AD
  • Potentially heavier dependency for projects not already using Azure services

Code Comparison

azure-activedirectory-identitymodel-extensions-for-dotnet:

var validationParameters = new TokenValidationParameters
{
    ValidateIssuer = true,
    ValidIssuer = "https://sts.windows.net/tenant-id/",
    ValidateAudience = true,
    ValidAudience = "client-id"
};

openiddict-core:

services.AddOpenIddict()
    .AddServer(options =>
    {
        options.SetIssuer(new Uri("https://auth-server.com"));
        options.SetAuthorizationEndpointUris("/connect/authorize");
    });

Both libraries provide robust OAuth and OpenID Connect implementations, but openiddict-core offers a more flexible and protocol-agnostic approach. It's better suited for custom identity providers and non-Microsoft scenarios. azure-activedirectory-identitymodel-extensions-for-dotnet excels in Azure AD integrations and Microsoft-centric environments, providing seamless compatibility with Azure services.

.NET standard helper library for claims-based identity, OAuth 2.0 and OpenID Connect.

Pros of IdentityModel

  • Lightweight and focused library for OpenID Connect and OAuth 2.0
  • Extensive support for various token types and flows
  • Easy integration with existing .NET applications

Cons of IdentityModel

  • Less comprehensive than OpenIddict for full identity server implementation
  • Requires more manual configuration for complex scenarios
  • Limited built-in UI components for authentication flows

Code Comparison

IdentityModel:

var client = new HttpClient();
var disco = await client.GetDiscoveryDocumentAsync("https://demo.identityserver.io");
var tokenResponse = await client.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest
{
    Address = disco.TokenEndpoint,
    ClientId = "client",
    ClientSecret = "secret",
    Scope = "api1"
});

OpenIddict:

services.AddOpenIddict()
    .AddCore(options =>
    {
        options.UseEntityFrameworkCore()
               .UseDbContext<ApplicationDbContext>();
    })
    .AddServer(options =>
    {
        options.SetTokenEndpointUris("/connect/token");
        options.AllowClientCredentialsFlow();
    });

Both libraries provide robust solutions for implementing OpenID Connect and OAuth 2.0 in .NET applications. IdentityModel is more focused on client-side operations and token handling, while OpenIddict offers a more comprehensive server-side implementation with additional features for identity management.

ASP.NET Core is a cross-platform .NET framework for building modern cloud-based web applications on Windows, Mac, or Linux.

Pros of aspnetcore

  • Comprehensive framework for building web applications and services
  • Extensive documentation and large community support
  • Seamless integration with other .NET technologies

Cons of aspnetcore

  • Steeper learning curve for beginners
  • Can be overkill for smaller projects or microservices
  • Less flexibility in terms of customization compared to OpenIddict

Code Comparison

OpenIddict:

services.AddOpenIddict()
    .AddCore()
    .AddServer()
    .AddValidation();

aspnetcore:

services.AddAuthentication()
    .AddJwtBearer(options =>
    {
        options.Authority = "https://localhost:5001";
    });

OpenIddict provides a more concise setup for OpenID Connect and OAuth 2.0, while aspnetcore requires more configuration for similar functionality. OpenIddict offers greater flexibility in customizing the authentication and authorization process, whereas aspnetcore provides a more standardized approach within the broader ASP.NET Core framework.

Both projects are actively maintained and offer robust solutions for authentication and authorization in .NET applications. The choice between them depends on specific project requirements, desired level of customization, and integration needs with other ASP.NET Core features.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

# OpenIddict

The OpenID Connect stack you'll be addicted to.

Build status

What is OpenIddict?

OpenIddict aims at providing a versatile solution to implement OpenID Connect client, server and token validation support in .NET applications.

[!TIP] While the client, server and token validation features can be used in any ASP.NET 4.6.1+ or ASP.NET Core 2.1+ web application, the client feature can also be used in Android, iOS, Linux, Mac Catalyst, macOS and Windows applications to integrate with OpenIddict-based identity providers or any other OAuth 2.0/OpenID Connect-compliant implementation.

OpenIddict fully supports the code/implicit/hybrid flows, the client credentials/resource owner password grants and the device authorization flow.

OpenIddict natively supports Entity Framework Core, Entity Framework 6 and MongoDB out-of-the-box and custom stores can be implemented to support other providers.


Getting started

To implement a custom OpenID Connect server using OpenIddict, read Getting started.

Samples demonstrating how to use OpenIddict with the different OAuth 2.0/OpenID Connect flows can be found in the dedicated repository.

Developers looking for a simple and turnkey solution are strongly encouraged to use OrchardCore and its OpenID module, which is based on OpenIddict, comes with sensible defaults and offers a built-in management GUI to easily register OpenID client applications.

Looking to integrate with a SAML2P Identity Provider (IDP) or Service Provider (SP)? Rock Solid Knowledge, a sponsor of OpenIddict, is developing a range of identity components to enhance your OpenIddict solution. The first of these is their popular SAML2P component.


Certification

Unlike many other identity providers, OpenIddict is not a turnkey solution but a framework that requires writing custom code to be operational (typically, at least an authorization controller), making it a poor candidate for the certification program.

While a reference implementation could be submitted as-is, this wouldn't guarantee that implementations deployed by OpenIddict users would be standard-compliant.

Instead, developers are encouraged to execute the conformance tests against their own deployment once they've implemented their own logic.

[!TIP] The samples repository contains a dedicated sample specially designed to be used with the OpenID Connect Provider Certification tool and demonstrate that OpenIddict can be easily used in a certified implementation. To allow executing the certification tests as fast as possible, that sample doesn't include any membership or consent feature (two hardcoded identities are proposed for tests that require switching between identities).


Resources

Looking for additional resources to help you get started with OpenIddict? Don't miss these interesting blog posts:

OpenIddict-based projects maintained by third parties:


Security policy

Security issues and bugs should be reported privately by emailing security@openiddict.com. You should receive a response within 24 hours. If for some reason you do not, please follow up via email to ensure we received your original message.


Support

If you need support, please first make sure you're sponsoring the project. Depending on the tier you selected, you can open a GitHub ticket or send an email to contact@openiddict.com for private support.

Alternatively, you can also post your question on Gitter.

[!IMPORTANT] With OpenIddict 5.x now being generally available, the previous version, OpenIddict 4.x, stops being supported and won't receive bug fixes or security updates. As such, it is recommended to migrate to OpenIddict 5.x to continue receiving bug and security fixes.

There are, however, two exceptions to this policy:

  • ABP Framework 7.x users will still receive patches for OpenIddict 4.x for as long as ABP Framework 7.x itself is supported by Volosoft (typically a year following the release of ABP 8.x), whether they have a commercial ABP license or just use the free packages.

  • OpenIddict sponsors who have opted for a $250+/month sponsorship are now offered extended support:

    • $250/month sponsors get full support for OpenIddict 4.x until June 18, 2024 (6 months).
    • $500/month sponsors get full support for OpenIddict 4.x until December 18, 2024 (12 months).
    • $1,000/month sponsors get full support for OpenIddict 4.x until December 18, 2025 (24 months).

Nightly builds

If you want to try out the latest features and bug fixes, there is a MyGet feed with nightly builds of OpenIddict. To reference the OpenIddict MyGet feed, create a NuGet.config file (at the root of your solution):

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <packageSources>
    <add key="nuget" value="https://api.nuget.org/v3/index.json" />
    <add key="openiddict" value="https://www.myget.org/F/openiddict/api/v3/index.json" />
  </packageSources>
</configuration>

Contributors

OpenIddict is actively maintained by Kévin Chalet. Contributions are welcome and can be submitted using pull requests.

Special thanks to our sponsors for their incredible support:

Volosoft logo

OpenIddict Components Logo

Sébastien RosSchmitt ChristianFlorian WachsSebastian StehleCommunicatie CockpitJasmin SavardDigitalOps Co. Ltd.EYERIDE Fleet Management SystemJulien DebacheStian HåveRavindu LiyanapathiranaHieronymusBlazeAkhan ZhakiyanovBarry DorransDevQ S.r.l.GrégoireForterroMarcelJens WillmerBlauhaus Technology (Pty) LtdJan TrejbalAviationexam s.r.o.MonoforRatiodata SEDennis van ZettenJeroenElfsterLombiq Technologies Ltd.PureBlazorAndrew BabbittKarl Schrieksoftaware gmbhSingular SystemsSCP-srlJacob ClarkRealisable SoftwareJesús SC

License

This project is licensed under the Apache License. This means that you can use, modify and distribute it freely. See http://www.apache.org/licenses/LICENSE-2.0.html for more details.