Web API Security in .Net6

 What is Web API Security

  • Web API Security is a mechanism to ensure that the APIs are not to be accessed without proper authentication and authorization.
  • This is required to ensure that the APIs are not misused.
  • Authentication is a mechanism to ensure that the user is a valid user and authorization to ensure that the user has all the right permission to access a method.

Adding Authentication at Controller and Action Level

  • We can do this by adding [Authorize] attribute at the controller level. This ensures that all the method of this controller can only be accessed by an authenticated user.
  • If we want to exclude a specific method from Authentication and Authorization process then we need to write [AllowAnonymous] at the action method level.
  • If we do not want to apply Authentication and Authorization to all the methods of a controller and want it to do for any specific method, then we can write [Authorize] attribute on the top of that method instead of writing it at the controller level.
  • We can also do authorization by user name, role or policy

// Restrict by user:

[Authorize(Users="Alice,Bob")]

// Restrict by role:

[Authorize(Roles="Administrators")]


Steps to Implement Security in Web API

  • Create a Web API Project with the name AuthProvider (This will be used to generate token for Multiple Web API Projects)
  • Add a class UserApiModel



  • Install Package System.IdentityModel.Tokens.Jwt
  • Add JWT Issuer, Audience and Secret Key in appsettings.JSON
  • Issuer is Auth server URL , audience in the consumer API URL and token is a unique token
  • Write a method to generate token based on User Claims, Issuer and Audience
  • Create second Web API project with the name WebAPIOne
  • Add the JWT section in appsettings.json file and only mention the app specific Audience and Secret Key

  • Install the package Microsoft.AspNetCore.Authentication.JwtBearer
  • Add the authentication dependency from program.cs file
  • Write [Authorize] attribute on top of the controller and the project is ready to be used using bearer authentication

Git Hub Link for Demo Code

Comments

Popular posts from this blog

Publish .Net Core Web API to Linux Host

Entity Relationship Using EF Core Code First Approach

Web API Using EF Core