JWT Authentication English STEP by STEP
JWT Authentication English STEP by STEP
Jean-Christophe Cherid / [email protected] [.Net 8 JSON Web Authentication] Windev & C#/.Net
.Net TIPS JSON Web Authentication (JWT)
Summary
I – Introduction ................................................................................................................................................................................. 4
Jean-Christophe Cherid / [email protected] [.Net 8 JSON Web Authentication] Windev & C#/.Net
.Net TIPS JSON Web Authentication (JWT)
IX Added the “Login” method in the “AuthenticateController” controller .............................................................................. 37
IX-A The code for the public method "Login" .............................................................................................................................. 37
Jean-Christophe Cherid / [email protected] [.Net 8 JSON Web Authentication] Windev & C#/.Net
.Net TIPS JSON Web Authentication (JWT)
I – Introduction
Jean-Christophe Cherid / [email protected] [.Net 8 JSON Web Authentication] Windev & C#/.Net
.Net TIPS JSON Web Authentication (JWT)
Jean-Christophe Cherid / [email protected] [.Net 8 JSON Web Authentication] Windev & C#/.Net
.Net TIPS JSON Web Authentication (JWT)
My .Net version is 8.0.3: you need to choose the correct NuGet version from the list.
Jean-Christophe Cherid / [email protected] [.Net 8 JSON Web Authentication] Windev & C#/.Net
.Net TIPS JSON Web Authentication (JWT)
II-B Reminder: How to find out the .Net version of the solution
Double-click on the
“API.Response.Dynamic.Model.Infrastructures” project: you
will see the current version of .Net used by the project.
Jean-Christophe Cherid / [email protected] [.Net 8 JSON Web Authentication] Windev & C#/.Net
.Net TIPS JSON Web Authentication (JWT)
Chain to copy
Jean-Christophe Cherid / [email protected] [.Net 8 JSON Web Authentication] Windev & C#/.Net
.Net TIPS JSON Web Authentication (JWT)
In the "Program.cs" class, the code below will initiate database creation.
Note: The database will only be created if it does NOT already exist.
// - - - - - - - - - - - - - - -
// > Automatic database creation <
// - - - - - - - - - - - - - - -
using (var scope = app.Services.CreateScope())
{
// -- Loading tables defined in the context-
var dbContext = scope.ServiceProvider.GetService<DataContext>();
// -- Creating tables--
dbContext.Database.EnsureCreated();
}
Jean-Christophe Cherid / [email protected] [.Net 8 JSON Web Authentication] Windev & C#/.Net
.Net TIPS JSON Web Authentication (JWT)
You must declare the key that will be used for the token calculation algorithm in the
appsettings.json file.
"Jwt": {
"key": "A4e78145A369874AAjrt@128545!p@AyQ"
},
10
Jean-Christophe Cherid / [email protected] [.Net 8 JSON Web Authentication] Windev & C#/.Net
.Net TIPS JSON Web Authentication (JWT)
11
Jean-Christophe Cherid / [email protected] [.Net 8 JSON Web Authentication] Windev & C#/.Net
.Net TIPS JSON Web Authentication (JWT)
12
Jean-Christophe Cherid / [email protected] [.Net 8 JSON Web Authentication] Windev & C#/.Net
.Net TIPS JSON Web Authentication (JWT)
When you click on “Install-Package System.IdentityModel.Tokens.Jwt”, you arrive on the page
below:
Link : https://www.nuget.org/packages/System.IdentityModel.Tokens.Jwt/
13
Jean-Christophe Cherid / [email protected] [.Net 8 JSON Web Authentication] Windev & C#/.Net
.Net TIPS JSON Web Authentication (JWT)
Right-click on the
“API.Response.Dynamic.Model” project
14
Jean-Christophe Cherid / [email protected] [.Net 8 JSON Web Authentication] Windev & C#/.Net
.Net TIPS JSON Web Authentication (JWT)
Jean-Christophe Cherid / [email protected] [.Net 8 JSON Web Authentication] Windev & C#/.Net
.Net TIPS JSON Web Authentication (JWT)
The NuGet
"Microsoft.AspNetCore.Authentication.JwtBearer"
is successfully added to the
"API.Response.Dynamic.Model" project
16
Jean-Christophe Cherid / [email protected] [.Net 8 JSON Web Authentication] Windev & C#/.Net
.Net TIPS JSON Web Authentication (JWT)
17
Jean-Christophe Cherid / [email protected] [.Net 8 JSON Web Authentication] Windev & C#/.Net
.Net TIPS JSON Web Authentication (JWT)
IV-E-2 Code of the “AddCustomAuthentication” method: This is where the key is
used to calculate the Token
namespace API.Response.Dynamic.Model.SecurityMethods
{
public static class SecurityMethods
{
#region properties
// > Key statement for the construction of the Token <
private static string MyKeyJwt { get; set; }
#endregion
/// <summary>
/// Building the JWT Authentication Process
/// </summary>
/// <param name="_builder"></param>
/// <returns></returns>
public static object AddCustomAuthentication( object _builder)
{
// > 1/ Creating a "configurationBuilder" <
ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
// > 4 If the parameter passed is not null, then we retrieve its contents <
if ( _builder is not null)
{
// > We parse "_builder" with the "WebApplicationBuilder" class <
builder = (WebApplicationBuilder) _builder; ;
}
18
Jean-Christophe Cherid / [email protected] [.Net 8 JSON Web Authentication] Windev & C#/.Net
.Net TIPS JSON Web Authentication (JWT)
// =-=-=-=-=-=-=-=-=-=-
// = = = = START Phase Validation of the <Json Web Token> =-=-=-=
// =-=-=-=-=-=-=-=-=-=-
// > On détermine ici quelle est la façon de communiquer des Headers...
// ...dans la partie authentification.
builder.Services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
// > This is where you configure jwt with all the parameters.<
{
// > We save the Token so we can use it later <
options.SaveToken = true;
ValidateAudience = false,
ValidateIssuer = false,
ValidateActor = false,
};
}
});
// =-=-=-=-=-=-=-=-=-=-
// =-=-=- END Phase Validation of the <Json Web Token> =-=-=-=
// =-=-=-=-=-=-=-=-=-=-
return builder;
}
}
}
19
Jean-Christophe Cherid / [email protected] [.Net 8 JSON Web Authentication] Windev & C#/.Net
.Net TIPS JSON Web Authentication (JWT)
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
// ### *** JWT .Net 8 *** ####
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
SecurityMethods.AddCustomAuthentication(builder);
20
Jean-Christophe Cherid / [email protected] [.Net 8 JSON Web Authentication] Windev & C#/.Net
.Net TIPS JSON Web Authentication (JWT)
21
Jean-Christophe Cherid / [email protected] [.Net 8 JSON Web Authentication] Windev & C#/.Net
.Net TIPS JSON Web Authentication (JWT)
Step 3 ➔Don’t forget to choose the correct target version of .Net (the solution is in .Net 8.2)
22
Jean-Christophe Cherid / [email protected] [.Net 8 JSON Web Authentication] Windev & C#/.Net
.Net TIPS JSON Web Authentication (JWT)
23
Jean-Christophe Cherid / [email protected] [.Net 8 JSON Web Authentication] Windev & C#/.Net
.Net TIPS JSON Web Authentication (JWT)
Add a controller
24
Jean-Christophe Cherid / [email protected] [.Net 8 JSON Web Authentication] Windev & C#/.Net
.Net TIPS JSON Web Authentication (JWT)
Add a controller
25
Jean-Christophe Cherid / [email protected] [.Net 8 JSON Web Authentication] Windev & C#/.Net
.Net TIPS JSON Web Authentication (JWT)
C
Add a controller
26
Jean-Christophe Cherid / [email protected] [.Net 8 JSON Web Authentication] Windev & C#/.Net
.Net TIPS JSON Web Authentication (JWT)
using Asp.Versioning;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
namespace API.Response.Dynamic.Model.Controllers.V1_DB2400
{
[ApiController]
[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/[controller]")]
public class AuthenticateController : ControllerBase
{
#region fields
// - - - - - - - - - - - -
// ### Authentication Start ###
// - - - - - - - - - - - -
// > Declares a "UserManager" <
private UserManager<IdentityUser> _userManager = null;
27
Jean-Christophe Cherid / [email protected] [.Net 8 JSON Web Authentication] Windev & C#/.Net
.Net TIPS JSON Web Authentication (JWT)
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
namespace API.Response.Dynamic.Model.Controllers.V1_DB2400
{
[Route("api/[controller]")]
[ApiController]
public class AuthenticateController : ControllerBase
{
#region fields
// - - - - - - - - - - - -
// ### Authentication Start ###
// - - - - - - - - - - - -
// > Declares a "UserManager" <
private UserManager<IdentityUser> _userManager = null;
// > We extract the value of the key "JWT:Key" from the "AppSettings"<
ElemKey = config.GetValue<string>("Jwt:Key");
}
#endregion
}
}
28
Jean-Christophe Cherid / [email protected] [.Net 8 JSON Web Authentication] Windev & C#/.Net
.Net TIPS JSON Web Authentication (JWT)
29
Jean-Christophe Cherid / [email protected] [.Net 8 JSON Web Authentication] Windev & C#/.Net
.Net TIPS JSON Web Authentication (JWT)
If the login is successful (see the "Login" method of the "AuthenticateController" controller), the calculated Token is
returned (via the "Token" property).
30
Jean-Christophe Cherid / [email protected] [.Net 8 JSON Web Authentication] Windev & C#/.Net
.Net TIPS JSON Web Authentication (JWT)
31
Jean-Christophe Cherid / [email protected] [.Net 8 JSON Web Authentication] Windev & C#/.Net
.Net TIPS JSON Web Authentication (JWT)
32
Jean-Christophe Cherid / [email protected] [.Net 8 JSON Web Authentication] Windev & C#/.Net
.Net TIPS JSON Web Authentication (JWT)
namespace API.Response.Dynamic.Model.Applications.DTOs
{
public class AuthenticateUserDto
{
#region properties
#endregion
}
}
33
Jean-Christophe Cherid / [email protected] [.Net 8 JSON Web Authentication] Windev & C#/.Net
.Net TIPS JSON Web Authentication (JWT)
#region methods
[Route("Register")]
[HttpPost]
public async Task<IActionResult> Register([FromBody] AuthenticateUserDto userDto)
{
// > By default, pessimistic<
IActionResult result = this.BadRequest();
// ---------------------------
// ## START - Constructs the "user" object ##
// ---------------------------
var user = new IdentityUser(userDto.Login);
user.Email = userDto.Login;
user.UserName = userDto.Name;
// ---------------------------
// ## END - Constructs the "user" object ##
// ---------------------------
if (success.Succeeded)
{
try
{
// > We retrieve the Token calculated by the "GenerateJwtToken" method <
userDto.Token = this.GenerateJwtToken(user);
finally
{}
}
34
Jean-Christophe Cherid / [email protected] [.Net 8 JSON Web Authentication] Windev & C#/.Net
.Net TIPS JSON Web Authentication (JWT)
// > Something went wrong <
// - Incorrect password: does NOT comply with the predefined rules,
// or
// - A user with this login already exists...
else
{
StringBuilder sb = new StringBuilder();
userDto.ErrorMsge = sb.ToString();
result = this.BadRequest(userDto);
}
return result;
}
35
Jean-Christophe Cherid / [email protected] [.Net 8 JSON Web Authentication] Windev & C#/.Net
.Net TIPS JSON Web Authentication (JWT)
This method “GenerateJwtToken” is responsible for calculating the Token: it is returned in the DTO “AuthenticateUserDto”.
Here is the code for “GenerateJwtToken” which is called by the “Login” method (see below), and therefore also the “Register” method.
// -----------------------------
// --- Token Description ----
// -----------------------------
// > We need to use "claims"...
// ...which are properties in our token that provide...
// ...information about the token belonging to the user...
// ...and so we have information such as the user's ID,...
// ...the user's name, their email address...
// ...The good thing is that this information is generated by...
// ...our server and our identity framework, which are valid and reliable.
36
Jean-Christophe Cherid / [email protected] [.Net 8 JSON Web Authentication] Windev & C#/.Net
.Net TIPS JSON Web Authentication (JWT)
Note: The "Login" method of the "AuthenticateController" controller performs a login test with the password contained in the
"AuthenticateUserDto" DTO which will be in the "body" ("[FromBody ]") of the http request.
Note: Remember to add the using " using API.Response.Dynamic.Model.Applications.DTOs; ;" in the
"AuthenticateController" controller.
[Route("Login")]
[HttpPost]
public async Task<IActionResult> Login([FromBody] AuthenticateUserDto DtoUser)
{
// > By default, pessimistic <
IActionResult result = this.BadRequest();
// > We'll verify the profile using the email address and password <
// > The idea is to be able to authenticate with the login that...
// ...IS the email address. <
// > Since we're searching using the email address (contained in...
// ...the login, we use the "FindByEmailAsync" method <
if (user != null)
{
// > We will check the password <
var verif = await this._userManager.CheckPasswordAsync(user, DtoUser.Password);
if (verif)
{
// > We load the DTO with the calculation of the token returned by the method...
// ..."GenerateJwtToken" <
result = this.Ok(new AuthenticateUserDto()
{
Login = user.Email,
Name = user.UserName,
Token = this. GenerateJwtToken(user),
});
}
37
Jean-Christophe Cherid / [email protected] [.Net 8 JSON Web Authentication] Windev & C#/.Net
.Net TIPS JSON Web Authentication (JWT)
else
{
StringBuilder sb = new StringBuilder();
// > Identification of the message code <
sb.Append("JWT_ERR_LOGIN_A1 - Invalid email address or password");
result = this.BadRequest(new AuthenticateUserDto()
{
Login = user.Email,
Name = user.UserName,
// > Calls the "GenerateJwtToke" method, which is responsible for...
// ...calculating a new Token <
Token = null,
ErrorMsge = sb.ToString()
});
}
}
// > We return the result <
return result;
}
38
Jean-Christophe Cherid / [email protected] [.Net 8 JSON Web Authentication] Windev & C#/.Net
.Net TIPS JSON Web Authentication (JWT)
39
Jean-Christophe Cherid / [email protected] [.Net 8 JSON Web Authentication] Windev & C#/.Net
.Net TIPS JSON Web Authentication (JWT)
In the “API.Response.Dynamic.Model.Infrastructures”
project, add the “Configurations” folder (1).
40
Jean-Christophe Cherid / [email protected] [.Net 8 JSON Web Authentication] Windev & C#/.Net
.Net TIPS JSON Web Authentication (JWT)
41
Jean-Christophe Cherid / [email protected] [.Net 8 JSON Web Authentication] Windev & C#/.Net
.Net TIPS JSON Web Authentication (JWT)
42
Jean-Christophe Cherid / [email protected] [.Net 8 JSON Web Authentication] Windev & C#/.Net
.Net TIPS JSON Web Authentication (JWT)
43
Jean-Christophe Cherid / [email protected] [.Net 8 JSON Web Authentication] Windev & C#/.Net
.Net TIPS JSON Web Authentication (JWT)
44
Jean-Christophe Cherid / [email protected] [.Net 8 JSON Web Authentication] Windev & C#/.Net
.Net TIPS JSON Web Authentication (JWT)
45
Jean-Christophe Cherid / [email protected] [.Net 8 JSON Web Authentication] Windev & C#/.Net
.Net TIPS JSON Web Authentication (JWT)
46
Jean-Christophe Cherid / [email protected] [.Net 8 JSON Web Authentication] Windev & C#/.Net
.Net TIPS JSON Web Authentication (JWT)
The call to the action (here "DynamicReques") works with the correct token.
(We're now entering the breakpoint).
47
Jean-Christophe Cherid / [email protected] [.Net 8 JSON Web Authentication] Windev & C#/.Net
.Net TIPS JSON Web Authentication (JWT)
builder.Services.AddSwaggerGen(options =>
{
// > Add a custom operation filter that sets default values <
options.OperationFilter<SwaggerDefaultValues>();
});
In = ParameterLocation.Header,
},
new List<string>()
}
});
});
48
Jean-Christophe Cherid / [email protected] [.Net 8 JSON Web Authentication] Windev & C#/.Net