Intercode.Toolbox.AspNetCore.Extensions 2.1.5

There is a newer version of this package available.
See the version list below for details.
dotnet add package Intercode.Toolbox.AspNetCore.Extensions --version 2.1.5                
NuGet\Install-Package Intercode.Toolbox.AspNetCore.Extensions -Version 2.1.5                
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Intercode.Toolbox.AspNetCore.Extensions" Version="2.1.5" />                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add Intercode.Toolbox.AspNetCore.Extensions --version 2.1.5                
#r "nuget: Intercode.Toolbox.AspNetCore.Extensions, 2.1.5"                
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install Intercode.Toolbox.AspNetCore.Extensions as a Cake Addin
#addin nuget:?package=Intercode.Toolbox.AspNetCore.Extensions&version=2.1.5

// Install Intercode.Toolbox.AspNetCore.Extensions as a Cake Tool
#tool nuget:?package=Intercode.Toolbox.AspNetCore.Extensions&version=2.1.5                

Intercode.Toolbox.AspNetCore.Extensions

A trimmable, AOT-compatible .NET library that contains types that provide functionality commonly used in ASP.NET Core applications.


JsonWebTokenBuilder class

The JsonWebTokenBuilder class provides a fluent interface to create JSON Web Tokens (JWT) using the System.IdentityModel.Tokens.Jwt library.

Usage

To create a JWT, create a JsonWebTokenBuilder instance class and call the BuildEncoded method after setting the token's properties. The BuildEncoded method returns a Result<string> object containing the JWT if the provided token information is valid; otherwise, it returns a failure result with one or more JwtValidationResultError objects.

var builder = new JsonWebTokenBuilder( "<<<My secret signing key>>>" )
builder.SetIssuer( "MyIssuer" )
       .AddAudience( "MyAudience" )
       .SetSubject( "sub-012345" )
       .SetTokenId( "my-JTI-value" )
       .SetLifetime( TimeSpan.FromMinutes( 30 ) )
       .AddRole( "Admin" )
       .AddClaim( "my-custom-claim", "my-claim-value" );

var result = builder.BuildEncoded();
if ( result.IsSuccess )
{
    string token = result.Value;
    // Use the token...
}
else
{
    // Handle the validation errors...
    var errors = result.Errors;
}

To obtain a JwtSecurityToken instance, call the Build method instead, which returns a Result<JwtSecurityToken> instance:

var builder = new JsonWebTokenBuilder( "<<<My secret signing key>>>" );
// Set token values...
var result = builder.Build();
if ( result.IsSuccess )
{
    JwtSecurityToken token = result.Value;
    // Use the JwtSecurityToken instance...
}
else
{
    // Handle the validation errors...
    var errors = result.Errors;
}

Reference

Constructors
  • Pass the secret key used to sign the JWT. Optionally, you can specify the signature algorithm and a custom time provider. By default, the builder uses the SecurityAlgorithms.HmacSha512Signature algorithm and the TimeProvider.System time provider. The default signature algorithm can be changed by setting the DefaultSignatureAlgorithm static property.
JsonWebTokenBuilder(
    string signingKey,
    string? signatureAlgorithm = null,
    TimeProvider? timeProvider = null )
  • Pass the SigningCredentials instance used to sign the JWT. Optionally, you can specify a custom time provider.
JsonWebTokenBuilder(
    SigningCredentials signingCredentials,
    TimeProvider? timeProvider = null )

Methods

  • Set the token's identifier (jti) claim.
JsonWebTokenBuilder SetTokenId( string tokenId )
  • Set the token's issuer (iss) claim
JsonWebTokenBuilder SetIssuer( string issuer )
  • Set the token's issued at (iat) claim. If not set, the current date and time is used.
JsonWebTokenBuilder SetIssuedAt( DateTime? issuedAt )
JsonWebTokenBuilder SetIssuedAt( DateTimeOffset? issuedAt )
  • Sets the token's expiration time (exp) claim.
JsonWebTokenBuilder SetValidTo( DateTime? validTo )
JsonWebTokenBuilder SetValidTo( DateTimeOffset? validTo )
  • Set the token's lifetime by specifying the expiration time relative to issuedAt date and time.
JsonWebTokenBuilder SetLifeTime( TimeSpan lifeTime )
  • Set the token's not before (nbf) claim.
JsonWebTokenBuilder SetValidFrom( DateTime? validFrom )
JsonWebTokenBuilder SetValidFrom( DateTimeOffset? validFrom )
  • Add an audience (aud) claim to the token.
JsonWebTokenBuilder AddAudience( string audience )
  • Set the token's subject (sub) claim.
JsonWebTokenBuilder SetSubject( string subject )
  • Add a ClaimTypes.Role claim to the token.
JsonWebTokenBuilder AddRole( string role )
  • Add a custom claim to the token.
JsonWebTokenBuilder AddClaim( string claimName, object value )
  • Generate a JwtSecurityToken instance from the builder's current state. The requiredClaims parameter specifies which claims are required to be present in the token.
Result<JwtSecurityToken> Build( RequiredClaim requiredClaims = RequiredClaim.Default )
  • Generate a JWT string from the builder's current state. The requiredClaims parameter specifies which claims are required to be present in the token.
Result<string> BuildEncoded( RequiredClaim requiredClaims = RequiredClaim.Default )

RequiredClaim enumeration

The RequireClaim flag enumeration specifies which claims are required to be present in the JWT.

Values

  • None - No claims are required.
  • Subject - The subject (sub) claim is required.
  • Issuer - The issuer (iss) claim is required.
  • Audience - At least one audience (aud) claim is required.
  • Role - At least one role (ClaimTypes.Role) claim is required.
  • Jti - The token identifier (jti) claim is required; a Guid will be automatically generated if not explicitly set.
  • Default - The subject, issuer, JTI, and at least one audience and role claims are required.

OpenApiInfoBuilder class

The OpenApiInfoBuilder class provides a fluent interface for the creation of OpenApiInfo instances used to configure the OpenAPI document in ASP.NET Core applications.

Usage

To create an OpenApiInfo instance, create an OpenApiInfoBuilder instance and set the desired properties. The Build method returns a Result<OpenApiInfo> object containing a OpenApiInfo instance if it was valid according to the ValidationRuleSet that was provided; otherwise, it returns a failure result with one or more OpenApiValidationResultError objects.

var builder = new OpenApiInfoBuilder( "My API title", "v1" );
builder.AddContact( "Contact Name", "contact@example.com", "https://example.com/contact" )
       .AddDescription( "This is an example API" )
       .AddExtension( "x-example-extension", "example-extension-value" )")
       .AddLicense( "MyLicense", "https://example.com/license" )
       .AddTermsOfService( "https://example.com/terms-of-service" );

var result = builder.Build();
if ( result.IsSuccess )
{
    OpenApiInfo info = result.Value;
    // Use the OpenApiInfo instance...
}
else
{
    // Handle the validation errors...
    var errors = result.Errors;
}

Reference

  • Creates a new instance of the OpenApiInfoBuilder class with the specified title and version.
OpenApiInfoBuilder( string title, string version )
  • Set the API's contact information, you can specify the contact's name, email, URL, and optionally add contact custom extensions.
OpenApiInfoBuilder AddContact( string? name, string? email, string? url = null, 
                               IDictionary<string, IOpenApiExtension>? extensions = null )
OpenApiInfoBuilder AddContact( string? name, string? email, Uri? uri = null, 
                               IDictionary<string, IOpenApiExtension>? extensions = null )
  • Set the API's description.
OpenApiInfoBuilder AddDescription( string description )
  • Append custom extensions to the API.
OpenApiInfoBuilder AddExtensions( IDictionary<string, IOpenApiExtension>? extensions )
  • Append a custom extension to the API.
OpenApiInfoBuilder AddExtension( string key, IOpenApiExtension extension )
  • Set the API's license information; you can specify the license's name, URL, and optionally add license custom extensions.
OpenApiInfoBuilder AddLicense( string? name, string? url,
                               IDictionary<string, IOpenApiExtension>? extensions = null )
  • Set the link to the API's terms of service.
OpenApiInfoBuilder AddTermsOfService( string? url )
OpenApiInfoBuilder AddTermsOfService( Uri? uri )
  • Build the OpenApiInfo instance from the builder's current state. The ruleSet parameter specifies the set of validation rules to apply to the builder's properties. By default, the builder validates using the rule set returned by ValidationRuleSet.GetDefaultRuleSet(). If no validation is to be performed, pass ValidationRuleSet.GetEmptyRuleSet() as the ruleSet parameter.<br> A Result<OpenApiInfo> containing the built OpenApiInfo object if it is valid; otherwise a failure result with one or more OpenApiValidationResultError objects.
Result<OpenApiInfo> Build( ValidationRuleSet? ruleSet = null )

OpenApiValidationResultError class

The OpenApiValidationResultError class represents a validation error that occurred while building an OpenApiInfo instance using the OpenApiInfoBuilder class. The actual OpenApiError validation error is found in the Metadata property, using the error key

class OpenApiValidationResultError
{
  // Initializes a new instance of the <see cref="OpenApiValidationResultError" /> class.
  public OpenApiValidationResultError( OpenApiError error )
  
  // Gets the error message.
  public string Message { get; }

  // Gets the metadata associated with the error.
  public Dictionary<string, object> Metadata { get; }

  // Gets the list of reasons for the error.
  public List<IError> Reasons { get; }
}

License

This project is licensed under the MIT License.

Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
2.5.0 71 11/13/2024
2.1.5 118 7/22/2024
2.1.4 111 7/16/2024