Convert Figma logo to code with AI

AzureAD logoazure-activedirectory-identitymodel-extensions-for-dotnet

IdentityModel extensions for .Net

1,050
395
1,050
174

Top Related Projects

OpenID Connect and OAuth 2.0 Framework for ASP.NET Core

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

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

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

Quick Overview

Azure Active Directory IdentityModel Extensions for .NET is a set of .NET assemblies designed to provide developers with tools for implementing authentication and authorization in their applications using Azure AD and other identity providers. It includes support for JSON Web Tokens (JWT), OpenID Connect, and WS-Federation protocols.

Pros

  • Comprehensive support for modern authentication protocols
  • Seamless integration with Azure AD and other identity providers
  • Regular updates and maintenance by Microsoft
  • Extensive documentation and community support

Cons

  • Learning curve for developers new to identity and access management
  • Complexity in handling advanced scenarios
  • Potential performance overhead in some use cases
  • Dependency on Microsoft's ecosystem

Code Examples

  1. Validating a JWT token:
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;

var tokenHandler = new JwtSecurityTokenHandler();
var validationParameters = new TokenValidationParameters
{
    ValidateIssuer = true,
    ValidIssuer = "https://sts.windows.net/your-tenant-id/",
    ValidateAudience = true,
    ValidAudience = "your-client-id",
    ValidateLifetime = true,
    IssuerSigningKey = new SymmetricSecurityKey(Convert.FromBase64String("your-signing-key"))
};

try
{
    var claimsPrincipal = tokenHandler.ValidateToken(jwtToken, validationParameters, out var validatedToken);
    // Token is valid, you can now use the claims
}
catch (SecurityTokenException)
{
    // Token validation failed
}
  1. Creating a JWT token:
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;

var claims = new[]
{
    new Claim(ClaimTypes.Name, "John Doe"),
    new Claim(ClaimTypes.Email, "john@example.com")
};

var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("your-secret-key"));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

var token = new JwtSecurityToken(
    issuer: "your-issuer",
    audience: "your-audience",
    claims: claims,
    expires: DateTime.Now.AddMinutes(30),
    signingCredentials: creds);

var tokenString = new JwtSecurityTokenHandler().WriteToken(token);
  1. Configuring OpenID Connect authentication in ASP.NET Core:
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.Identity.Web;

public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
        .AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureAd"));

    services.AddControllersWithViews();
}

Getting Started

  1. Install the NuGet package:

    dotnet add package Microsoft.IdentityModel.Tokens
    
  2. Add the necessary using statements:

    using Microsoft.IdentityModel.Tokens;
    using System.IdentityModel.Tokens.Jwt;
    
  3. Configure the token validation parameters and use the JwtSecurityTokenHandler to validate tokens as shown in the code examples above.

  4. For more advanced scenarios, refer to the official documentation and samples provided in the GitHub repository.

Competitor Comparisons

OpenID Connect and OAuth 2.0 Framework for ASP.NET Core

Pros of IdentityServer4

  • Open-source and highly customizable
  • Supports a wide range of authentication protocols (OpenID Connect, OAuth 2.0)
  • Active community and extensive documentation

Cons of IdentityServer4

  • Requires more setup and configuration compared to Azure AD extensions
  • May need additional infrastructure for hosting and management
  • Less integrated with Azure services

Code Comparison

IdentityServer4:

services.AddIdentityServer()
    .AddInMemoryClients(Config.Clients)
    .AddInMemoryIdentityResources(Config.IdentityResources)
    .AddInMemoryApiResources(Config.ApiResources)
    .AddTestUsers(Config.TestUsers)
    .AddDeveloperSigningCredential();

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

services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
    .AddAzureAD(options => Configuration.Bind("AzureAd", options));

services.Configure<OpenIdConnectOptions>(AzureADDefaults.OpenIdScheme, options =>
{
    options.Authority = $"{Configuration["AzureAd:Instance"]}{Configuration["AzureAd:TenantId"]}";
    options.ClientId = Configuration["AzureAd:ClientId"];
});

IdentityServer4 provides more flexibility and control over the authentication process, while azure-activedirectory-identitymodel-extensions-for-dotnet offers simpler integration with Azure AD services. The choice between them depends on specific project requirements and the desired level of customization.

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

Pros of OpenIddict

  • More flexible and customizable, allowing for greater control over the authentication process
  • Supports a wider range of OAuth 2.0 and OpenID Connect scenarios
  • Actively maintained with frequent updates and community contributions

Cons of OpenIddict

  • Steeper learning curve due to its extensive customization options
  • Less direct integration with Azure AD services compared to the Microsoft-maintained library

Code Comparison

OpenIddict:

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

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

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.Authority = "https://login.microsoftonline.com/{tenant}/v2.0";
        options.Audience = "{client_id}";
    });

The OpenIddict example shows its flexibility in configuring various aspects of the authentication process, while the Azure AD example demonstrates a more straightforward setup specifically for Azure AD integration.

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

Pros of aspnetcore

  • Broader scope, covering the entire ASP.NET Core framework
  • More active community with frequent updates and contributions
  • Comprehensive documentation and extensive examples

Cons of aspnetcore

  • Larger codebase, potentially more complex for specific identity-related tasks
  • May include unnecessary components for projects focused solely on identity management
  • Steeper learning curve for developers new to ASP.NET Core

Code Comparison

aspnetcore (Authentication middleware setup):

public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddJwtBearer(options => {
            // JWT bearer configuration
        });
}

azure-activedirectory-identitymodel-extensions-for-dotnet (Token validation):

public static ClaimsPrincipal ValidateToken(string token, TokenValidationParameters validationParameters)
{
    JwtSecurityTokenHandler handler = new JwtSecurityTokenHandler();
    return handler.ValidateToken(token, validationParameters, out SecurityToken validatedToken);
}

The aspnetcore repository provides a more integrated approach to authentication within the ASP.NET Core framework, while azure-activedirectory-identitymodel-extensions-for-dotnet focuses specifically on identity model extensions and token handling for Azure Active Directory scenarios.

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

Pros of IdentityModel

  • More lightweight and focused on OpenID Connect and OAuth 2.0 protocols
  • Easier to use for general-purpose identity and access token handling
  • Actively maintained with frequent updates and community support

Cons of IdentityModel

  • Less comprehensive Azure AD-specific features
  • May require additional libraries for full Azure AD integration
  • Smaller ecosystem compared to Microsoft's offering

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"
});

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

var configurationManager = new ConfigurationManager<OpenIdConnectConfiguration>("https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration", new OpenIdConnectConfigurationRetriever());
var openIdConfig = await configurationManager.GetConfigurationAsync();
var tokenHandler = new JwtSecurityTokenHandler();
var validationParameters = new TokenValidationParameters
{
    ValidAudience = "your_client_id",
    ValidIssuer = openIdConfig.Issuer,
    IssuerSigningKeys = openIdConfig.SigningKeys
};

Both libraries provide functionality for working with OpenID Connect and OAuth 2.0, but IdentityModel offers a more streamlined approach for general use cases, while azure-activedirectory-identitymodel-extensions-for-dotnet provides more comprehensive Azure AD-specific features and integration.

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

IdentityModel Extensions for .NET

Nuget

IdentityModel Extensions for .NET provide assemblies that are interesting for web developers that wish to use federated identity providers for establishing the caller's identity.

Versions

You can find the release notes for each version here. Older versions can be found here.

IdentityModel 7x

We are excited to announce the release of IdentityModel 7x, a major update to our popular .NET auth validation library. This new version introduces several improvements related to serialization and consistency in the API, which will provide a better user experience for developers, as well as full AOT compatibility on .NET, and huge perf improvements compared to 6x.

Note about 6.x

We bumped the release from 6.x to 7.x. We are maintaining two releases from two different branches. dev - 7.x dev6x - 6.x

dev6x will be maintained until March 2024, at which point, you will need to move to 7x to continue to get the latest and greatest improvements and security updates.

Samples and Documentation

The scenarios supported by IdentityModel extensions for .NET are described in Scenarios. The libraries are in particular used part of ASP.NET security to validate tokens in ASP.NET Web Apps and Web APIs. To learn more about token validation, and find samples, see:

Community Help and Support

We leverage Stack Overflow to work with the community on supporting Microsoft Entra and its SDKs, including this one! We highly recommend you ask your questions on Stack Overflow (we're all on there!) Also browse existing issues to see if someone has had your question before.

We recommend you use the "identityModel" tag so we can see it! Here is the latest Q&A on Stack Overflow for IdentityModel: https://stackoverflow.com/questions/tagged/identityModel

Have a design proposal? Please submit a design proposal before starting work on a PR to ensure it means the goals/objectives of this library and it's priorities.

Security Reporting

See SECURITY.md

Security Vulnerability in Microsoft.IdentityModel.Tokens 5.1.0

IdentityModel Extensions library Microsoft.IdentityModel.Tokens has a known security vulnerability affecting version 5.1.0. Please update to >= 5.1.1 immediately. An updated package is available on NuGet. For more details, see the security notice.

Contributing

All code is licensed under the MIT license and we triage actively on GitHub. We enthusiastically welcome contributions and feedback. See Contributing.md for guidelines, branch information, build instructions, and legalese.

License

Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License (the "License");

We Value and Adhere to the Microsoft Open Source Code of Conduct

This project has adopted the Microsoft Open Source Code of Conduct. For more information see the Code of Conduct FAQ or contact opencode@microsoft.com with any additional questions or comments.