Web API Security/Authentcation

This page talks about how to secure the web api we are creating to get and create licenses.

The most recommended way to secure a ASP.NET Core Web API Framework is to use OAuth.

Wha is OAuth?

It means Open Authorization Framework. It is an open authorization protocol that allows secure a web api.

How does it work?

It uses JWT authentication. To read more about it go to https://jwt.io/introduction/

First, we should add some JWT settings in our app settings:

"JWT": {  
    "ValidAudience": "http://localhost:4200",  
    "ValidIssuer": "http://localhost:61955",  
    "Secret": "ByYM000OLlMQG6VVVp1OH7Xzyr7gHuw1qvUC5dcGt3SNM"  
  }  

To adapt this framework wu should create some class models and a controller to manage the authentication and authorization. This is a representation of the standard model recommended by Microsoft:

Then, we should add the following configuration in the startup class:

            // For Identity  
            services.AddIdentity<ApplicationUser, IdentityRole>()  
                .AddEntityFrameworkStores<ApplicationDbContext>()  
                .AddDefaultTokenProviders();  
  
            // Adding Authentication  
            services.AddAuthentication(options =>  
            {  
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;  
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;  
                options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;  
            })  
  
            // Adding Jwt Bearer  
            .AddJwtBearer(options =>  
            {  
                options.SaveToken = true;  
                options.RequireHttpsMetadata = false;  
                options.TokenValidationParameters = new TokenValidationParameters()  
                {  
                    ValidateIssuer = true,  
                    ValidateAudience = true,  
                    ValidAudience = Configuration["JWT:ValidAudience"],  
                    ValidIssuer = Configuration["JWT:ValidIssuer"],  
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JWT:Secret"]))  
                };  
            });  

Once this is implemented, we can put the Authorize attribute in our controllers to manage who can consume the API. It can be in the controller or for every method because it might be possible that getting a license from a key is open to everybody.

Database

This model makes us create a database to manage users and roles which later will allow us to have the authentication working in the API. Thje database should look lke this:

This database will be consumed by the Identity Framework to manage authentication and authorization.

Last updated