KenJwtAuth 1.1.0
dotnet add package KenJwtAuth --version 1.1.0
NuGet\Install-Package KenJwtAuth -Version 1.1.0
<PackageReference Include="KenJwtAuth" Version="1.1.0" />
<PackageVersion Include="KenJwtAuth" Version="1.1.0" />
<PackageReference Include="KenJwtAuth" />
paket add KenJwtAuth --version 1.1.0
#r "nuget: KenJwtAuth, 1.1.0"
#:package KenJwtAuth@1.1.0
#addin nuget:?package=KenJwtAuth&version=1.1.0
#tool nuget:?package=KenJwtAuth&version=1.1.0
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 | Versions 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. |
-
.NETCoreApp 2.1
- Microsoft.AspNetCore.Authentication (>= 2.1.0)
- Microsoft.AspNetCore.Authentication.JwtBearer (>= 2.1.0)
- Microsoft.AspNetCore.Identity.EntityFrameworkCore (>= 2.1.0)
- Microsoft.Extensions.DependencyInjection.Abstractions (>= 2.1.0)
- System.IdentityModel.Tokens.Jwt (>= 5.2.4)
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 |
---|