Gleeman.JwtGenerator 2.0.0

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

// Install Gleeman.JwtGenerator as a Cake Tool
#tool nuget:?package=Gleeman.JwtGenerator&version=2.0.0                

Gleeman.JwtGenerator

| Package | Version | Popularity | | ------- | ----- | ----- | | Gleeman.JwtGenerator | NuGet | Nuget <br>

dotnet CLI

> dotnet add package Gleeman.JwtGenerator --version 1.0.1

HOW TO USE ?

appsettings.json

 "TokenSetting": {
    "SaveToken": true, // true or false
    "ValidateIssuer": false, // true or false
    "ValidateAudience": false, // true or false
    "ValidateLifetime": true, // true or false
    "Issuer": null, // string
    "Audience": null, // string
    "SigningKey": "You should be write here your security key!" // string
  }

Program.cs

builder.Services.AddJwtGenerator(builder.Configuration);
app.UseAuthentication();
app.UseAuthorization();

EXAMPLE

appsettings.json

"TokenSetting": {
    "SaveToken": true,
    "ValidateIssuer": true,
    "ValidateAudience": true,
    "ValidateLifetime": true,
    "Issuer": "http://localhost:5021",
    "Audience": "http://localhost:5021",
    "SigningKey": "ee98db58bc6847b189f04937b6cb30e3"
  }

Program.cs

builder.Services.AddDbContext<AppDbContext>(opt => opt.UseInMemoryDatabase("TestDb"));
builder.Services.AddJwtGenerator(builder.Configuration);
builder.Services.AddScoped<IUserService, UserService>();
Database.AddUserData(app);
app.UseAuthentication();
app.UseAuthorization();
Service

public interface IUserService
{
    Task<LoginResponse> LoginAsync(LoginRequest loginRequest);
}

public class UserService : IUserService
{
    private readonly ITokenGenerator _tokenGenerator;
    private readonly AppDbContext _dbContext;
    public UserService(ITokenGenerator tokenGenerator, AppDbContext dbContext)
    {
        _tokenGenerator = tokenGenerator;
        _dbContext = dbContext;
    }

    public async Task<LoginResponse> LoginAsync(LoginRequest loginRequest)
    {
        var user = await _dbContext.Users
            .Where(x => x.Email == loginRequest.Email && x.Password == loginRequest.Password)
            .Include(x => x.Role)
            .SingleOrDefaultAsync();

        if (user == null)
        {
            return new LoginResponseMessage("Email or Password is wrong!") { Success = false };
        }

        var userParameters = new UserParameters(
            userId: user.Id.ToString(),
            email: user.Email,
            username: user.UserName ?? null,
            dateofBirth: user.DateOfBirth.ToString(),
            mobilePhone: user.PhoneNumber);


        /******************************** If user has more role ******************************
         
        var roleParameters = new List<RoleParameters>();
        roleParameters = user.Roles.Select(x => new RoleParameters
        {
            Role = x.RoleName
        }).ToList();

        var accessToken = _tokenGenerator.GenerateAccessToken(userParameters, roleParameters,
                          ExpireType.Minute,
                          5);
         *************************************************************************************/



        /******************************** If user has a role ***********************************
          var roleParameter = new RoleParameters();
          roleParameter.Role = user.Role.RoleName;

          var accessToken = _tokenGenerator.GenerateAccessToken(userParameters,roleParameter,
                            ExpireType.Minute,
                            5);
         ***************************************************************************************/



        // If user has no a role
        var accessToken = _tokenGenerator.GenerateAccessToken(userParameters,
            ExpireType.Minute,
            5);

        user.Token = refreshToken.Token;
        user.TokenExpire = refreshToken.ExpireDate;
        _dbContext.Update(user);
        await _dbContext.SaveChangesAsync();
        return new LoginResponse
        {
            AccessToken = accessToken.Token,
            AccessExpires = accessToken.ExpireDate,
            RefreshToken = refreshToken.Token,
            RefreshExpires = refreshToken.ExpireDate,
            Success = true
        };
    }
}
Controller
[Route("api/[controller]")]
[ApiController]
public class AuthController : ControllerBase
{
    private readonly IUserService _userService;

    public AuthController(IUserService userService)
    {
        _userService = userService;
    }

    [HttpPost]
    public async Task<IActionResult> Login(LoginRequest loginRequest)
    {
        var result = await _userService.LoginAsync(loginRequest);
        if (result.Success)
        {
            return Ok(new { AccessToken = result.AccessToken, AccessExpire = result.AccessExpires, RefreshToken = result.RefreshToken, RefreshExpires = result.RefreshExpires });
        }

        return BadRequest(result.Message);
    }
}

Response

Product Compatible and additional computed target framework versions.
.NET net7.0 is compatible.  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
8.0.0 210 2/9/2024
7.0.0 124 2/9/2024
2.0.1 259 10/16/2023
2.0.0 129 9/29/2023
1.0.1 121 9/15/2023

Multiple role based token generating feature has been added