Kirpichyov.FriendlyJwt 1.0.2

There is a newer version of this package available.
See the version list below for details.
dotnet add package Kirpichyov.FriendlyJwt --version 1.0.2                
NuGet\Install-Package Kirpichyov.FriendlyJwt -Version 1.0.2                
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="Kirpichyov.FriendlyJwt" Version="1.0.2" />                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add Kirpichyov.FriendlyJwt --version 1.0.2                
#r "nuget: Kirpichyov.FriendlyJwt, 1.0.2"                
#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 Kirpichyov.FriendlyJwt as a Cake Addin
#addin nuget:?package=Kirpichyov.FriendlyJwt&version=1.0.2

// Install Kirpichyov.FriendlyJwt as a Cake Tool
#tool nuget:?package=Kirpichyov.FriendlyJwt&version=1.0.2                

Overview

main workflow Coverage Status NuGet

FriendlyJwt is the custom JWT token authentication services wrapper library for ASP.NET Core 5.0.

Get started

🎯 Download the NuGet package.

🎯 Register services in the Startup.cs.

    public void ConfigureServices(IServiceCollection services)
    {
        // ......
        
        services.AddHttpClient();
        services.AddHttpContextAccessor();

        services.AddFriendlyJwt(); // <-- FriendlyJwt services registration
        
        // ......
    }

🎯 Register authorization services in the Startup.cs.

    public void ConfigureServices(IServiceCollection services)
    {
    
        // ......
    
        services.AddControllers()
                // FriendlyJwt authorization services registration below
                .AddFriendlyJwtAuthentication(configuration =>
                {
                    configuration.Audience = "someaudience.com";
                    configuration.Issuer = "someissuer";
                    configuration.Secret = "SecretYGPV8XC6bPJhQCUBV2LtDSharp";
                });
                
        // ......
    }

💡Audience and Issuer are optional. If values not provided, then validation will be disabled.

💡 Method has the second parameter (postSetupDelegate), that allows to perform post configuration for authentication.

⚠️⚠️ Ensure that UseAuthentication and UseAuthorization was called in Startup.cs.

    // ......

    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseRouting();
    
    app.UseAuthentication(); // <--
    app.UseAuthorization(); // <--
    
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
        endpoints.MapGet("/healthcheck", async context =>
        { 
            await context.Response.WriteAsync($"Healthy! [{DateTime.Now}]");
        });
    });

    // ......

How to create token

You can find the example below:

    TimeSpan lifeTime = TimeSpan.FromMinutes(1);
    string secret = "SecretYGPV8XC6bPJhQCUBV2LtDSharp";

    GeneratedTokenInfo generatedTokenInfo =
        new JwtTokenBuilder(lifeTime, secret)
            .WithIssuer("someissuer")
            .WithAudience("someaudience")
            .WithUserRolesPayloadData(new[] { "admin", "supervisor" });
            .WithUserIdPayloadData("13567")
            .WithUserEmailPayloadData("usermail@example.com")
            .WithPayloadData("time_zone", "Mid-Atlantic Standard Time")
            .WithPayloadData("custom_key", "some custom value")
            .Build();

Builder will return the GeneratedTokenInfo object that will contain the token and related information like expiration date and token identifier (jti).

💡 In case if you does not want to use GUID based token id (jti) you can use custom, just use the method .WithCustomTokenId("your_value").

💡 Constructor contains the required parameters, so you can just call new JwtTokenBuilder.Build() to get token, if you does not need the additional information or validation.

How to read the token payload values

🎯 Inject IJwtTokenReader service via constructor:

    public SomeService(IJwtTokenReader jwtTokenReader, .....)
    {
       //......
    }

Now you can use different methods and properties to access the payload data:

    //......
    
    // will return true if user authenticated
    bool isLogged = _jwtTokenReader.IsLoggedIn;

    // will retrieve the email if default key was used (via WithUserEmailPayloadData() method)
    string userEmail = _jwtTokenReader.UserEmail;

    // will retrieve the user id if default key was used (via WithUserIdPayloadData() method)
    string userId = _jwtTokenReader.UserId;
    
    // will retrieve the user roles if default key was used (via WithUserRolesPayloadData() method)
    string[] userRoles = _jwtTokenReader.UserRoles;

    // will retrieve the value via key passed to indexer
    // will throw exception if key is not present
    string someValue = _jwtTokenReader["my_key"];

    // will retrieve the value via key passed to method
    // will throw exception if key is not present
    string someOtherValue = _jwtTokenReader.GetPayloadValue("my_key");

    // will retrieve the value via key passed to method
    // will return null if key is not present
    string someVeryOtherValue = _jwtTokenReader.GetPayloadValueOrDefault("my_key");

    // will retrieve the all values for passed key
    // will return empty array if key is not present
    string[] someManyValues = _jwtTokenReader.GetPayloadValues("my_shared_key");

    // will return the all payload entries
    (string Key, string Value)[] allValues = _jwtTokenReader.GetPayloadData();

    //......

How to validate the issued token (refresh token approach)

🎯 Inject IJwtTokenVerifier service via constructor:

    public SomeService(IJwtTokenVerifier jwtTokenVerifier, .....)
    {
       //......
    }

🎯 Call the verification method:

    JwtVerificationResult verificationResult =_jwtTokenVerifier.Verify(refreshTokenDto.Token);

JwtVerificationResult will contain the IsValid property and retrieved TokenId and UserId.

💡 You should pass the values for tokenIdPayloadKey and userIdPayloadKey properties in case if you are using custom payload keys to store this values.

Product Compatible and additional computed target framework versions.
.NET net5.0 is compatible.  net5.0-windows was computed.  net6.0 was computed.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  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
1.0.8 121 9/20/2024
1.0.7 13,772 1/18/2023
1.0.6 822 7/8/2022
1.0.5 437 7/8/2022
1.0.4 446 7/8/2022
1.0.3 477 3/31/2022
1.0.2 586 1/12/2022
1.0.1 476 1/11/2022
1.0.0 451 1/11/2022

- Fixed found bugs