KenJwtAuth 1.1.0

The owner has unlisted this package. This could mean that the package is deprecated, has security vulnerabilities or shouldn't be used anymore.
dotnet add package KenJwtAuth --version 1.1.0
                    
NuGet\Install-Package KenJwtAuth -Version 1.1.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="KenJwtAuth" Version="1.1.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="KenJwtAuth" Version="1.1.0" />
                    
Directory.Packages.props
<PackageReference Include="KenJwtAuth" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add KenJwtAuth --version 1.1.0
                    
#r "nuget: KenJwtAuth, 1.1.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.
#:package KenJwtAuth@1.1.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=KenJwtAuth&version=1.1.0
                    
Install as a Cake Addin
#tool nuget:?package=KenJwtAuth&version=1.1.0
                    
Install as a Cake Tool

Ken Jwt Auth

KenJwtAuth provides a way to generate basic bearer token with required claims. It's easy to setup with Asp.net core Identity.

Step 1: Create Project

Create Asp.net core 2.1 project with Individual User Accounts.

Step 2: Add JSON Configuration

Add following json in appsettings.json

"Bearer": {
    "SecretKey": "your secret key",
    "Issuer": "your issuer",
    "Audience": "your audience"
  }

Step 3: Add KenJwtAuth

Install the package using package manager console

Install-Package KenJwtAuth

Or using dot net CLI

dotnet add package KenJwtAuth

Step 4: Setup Token Handler in Startup.cs

Add following code snippet in startup.cs in method ConfigureServices

//Adds database context with Sql Server
services.AddDbContext<ApplicationDbContext>(options =>
	options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
//Adding Identity with DbContext
services.AddDefaultIdentity<IdentityUser>()
	.AddEntityFrameworkStores<ApplicationDbContext>();
//Adding JwtBearer with TokenHandler
services.AddAuthentication()
	.AddJwtBearerWithTokenHandler(JwtBearerDefaults.AuthenticationScheme, jwtOptions =>
	{
		jwtOptions.TokenValidationParameters = new TokenValidationParameters
		{
			ValidateIssuer = true,
			ValidateAudience = true,
			ValidateLifetime = true,
			ValidateIssuerSigningKey = true,
			ClockSkew = TimeSpan.Zero,
			ValidIssuer = Configuration.GetSection("Bearer:Issuer").Value,
			ValidAudience = Configuration.GetSection("Bearer:Audience").Value,
			IssuerSigningKey = new SymmetricSecurityKey(
                Encoding.ASCII.GetBytes(Configuration.GetSection("Bearer:SecretKey").Value)),
        };
        jwtOptions.IncludeErrorDetails = true;
        jwtOptions.SaveToken = true;
    },expiry:DateTime.Now.AddDays(3));

Step 5: Get ITokenHandler from DI

Create an account controller and get ITokenHandler from Dependency Injection.

private readonly UserManager<IdentityUser> _userManager;
private readonly SignInManager<IdentityUser> _signInManager;
private readonly ITokenHandler _tokenHandler;
//Getting ITokenHandler from DI
public AccountController(UserManager<IdentityUser> userManager,
                         SignInManager<IdentityUser> signInManager,
                         ITokenHandler tokenHandler)
{
    _userManager = userManager;
    _signInManager = signInManager;
    _tokenHandler = tokenHandler;
}

Step 6: Create Login and Signup Actions

Create Login and signup action.

[HttpPost("[action]")]
public async Task<IActionResult> SignIn([FromBody] LoginModel model)
{
    var user = await _userManager.FindByEmailAsync(model.Email);
    if (user == null)
    {
        ModelState.AddModelError("email", $"No user exists with email {model.Email}");
        return BadRequest(ModelState);
    }
    var result = await _signInManager.CheckPasswordSignInAsync(user, model.Password, false);
    if (result.Succeeded)
    {
        //Getting token with specified claims.
        var token = _tokenHandler.GenerateTokenForUser(user, claims=>
        {
        	claims.Add(new Claim(ClaimTypes.Email, user.Email));
        });
        return Ok(new { token, user.UserName });
    }
    ModelState.AddModelError("password", $"Invalid password");
    return BadRequest(ModelState);
}
[HttpPost("[action]")]
public async Task<IActionResult> Register([FromBody] RegisterModel model)
{
    var user = await _userManager.FindByEmailAsync(model.Email);
    if (user != null)
    {
        ModelState.AddModelError("email", $"User already exists with email {model.Email}");
        return BadRequest(ModelState);
    }
    var myuser = new IdentityUser { UserName = model.UserName, Email = model.Email };
    var SignUpresult = await _userManager.CreateAsync(myuser, model.Password);
    if (SignUpresult.Succeeded)
    {
        return Ok(new { data = "Signup successful" });
    }
    ModelState.AddModelError("username", $"Username {model.UserName} is taken");
    return BadRequest(ModelState);
}

Step 6: Test

Test the api by signing up and then logging in using POSTMAN.

Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  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.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
.NET Core netcoreapp2.1 is compatible.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 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