Hi everybody, I am going to try to explain the definition of JWT and how to use in our .Net Core project. Lets look at the definition.
What is JWT?
JWT(JSON Web Token), is a standard of RFC7519. is designed to communicate with client-server as a JSON object. Generally, it is a way to use for authentication. We can list the advantages of using JWT as follows;
- Uses JSON,
- Transfer on URL
- Not necessary to use cookies
- Method and logic is easy and fast to verification
- Uses each client that can make a request HTTP with generated token
- Not need th HTTP session for web applciation and be appropriate for usage of stateless
- Ensuring data integrity
As you can see on below, there is three section in genrated key. These sections is coded with Base64 JSON object and they are seperated with .(dot). Red section is the header, black section is the data and last section is sign.
Example of generated token;
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1bmlxdWVfbmFtZSI6IjEiLCJuYmYiOjE1OTYyODE2MTMsImV4cCI6MTU5Njg4NjQxMywiaWF0IjoxNTk2MjgxNjEzfQ.GK6PALIFqOp2v_OWHiIgJx_Cq1_AnXns_D8uv2xzYBA
Verification of JWT
It is simple to verify it like its structure. Actually, it is applied the opposite of below method. Header of token which is send from client and data section which secret key on our server, are signed. And It means that it is related the third section. If signs are same, token is valid and connection is given.
Making Project
I used and you need the following tools for application development:
- Visual Studio 2019 Community Edition
- .Net Core SDK 3.1
- Microsoft AspNetCore Authentication JwtBearer 3.1.6
First of all, we create a project as a ASP.NET Core Web Application Project and give a name, I gave core-jwt-authentication. Before starting development, we need to install some nuget packages.
Microsoft.AspNetCore.Authentication.JwtBearer package is necessary to use JWTBearer in our application.
/Users/authenticate: It wants to username and password information in a JSON format and it has [AllowAnonymous] attiribute. So, it recieves any request. After the user confirmation, it returns user information and token.
Let's try it;
First of all, we need to get Postman application. If you don't have in your computer, you can download in this link.
After opening new tab, choose POST in the sending type combo.
And we send post request to "https://localhost:44337/Users/Authenticate". with body content.
{
"Username":"test",
"Password":"test"
}
Important thing: If you don't add content type: application/json, you face the unsupported media error.
I created a model that contains user information as a User.cs. Entity structure uses in the application to communicate with different sections. Also, It is used to recieve http request with controller. We can think it like a table in the database. We use entities classes to create a table in Entityframework with Code First approach.
public class User
{
public int Id { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public string Token { get; set; }
}
Startup class is a class, how to proccess the whole request of application.
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
services.AddControllers();
// We get the value of secret in appsettings.json and bring it appsettings class.
var appSettingSection = Configuration.GetSection("AppSettings");
services.Configure<AppSettings>(appSettingSection);
var appSettings = appSettingSection.Get<AppSettings>();
var key = Encoding.ASCII.GetBytes(appSettings.Secret);
// We set default value AuthenticationScheme in scheme which are not defined [Authorize].
services.AddAuthentication(x =>
{
x.DefaultAuthenticateScheme =
JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme =
JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(x => {
x.RequireHttpsMetadata = false;
x.SaveToken = true;
x.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key), //We set generated key as a security key.
ValidateIssuer = false,
ValidateAudience = false
};
});
// Dependency
Injection
services.AddScoped<IUserService,
UserService>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request
pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseCors(a =>
a.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
app.UseAuthentication();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
Comments
Post a Comment