Custom Authorization In .NET Core 5.0

In this, Article we are going to learn how to implement custom authorization in .Net Core 5.0

Prerequisites

As in the previous article, we learn how to implement basic authentication in the application, but sometimes there might be a situation in which you must implement your custom authorization to access API.

This article will explain how to create your custom authorization Class and retrieve the values. you can apply it to all APIs in that controller, or you can use it to each API independently.

Let us understand it by example.

First, open Visual Studio 2019 and create a .NET Core 5.0 application.

Create UsersController in the controller folder and paste the below code.

[CustomAuthorization]
 [Route("api/Users")]
 [ApiController]
 public class UsersController : Controller
 {
   private IUserServices _userService;
   public UsersController(IUserServices userService)
   {
     _userService = userService;
   }

   [HttpGet]
   [Route("GetAllUsers")]
   public async Task<IActionResult> GetAllUsers()
   {
     var users = await _userService.GetAllUsers();
     return Ok(users);
   }
 }

Create User class in a Model folder and paste the below code.

public class User
{
  public int Id { get; set; }
  public string Username { get; set; }
  public string Password { get; set; }
}

Create IUserServices in the Service folder and paste the below code.

public interface IUserServices
{
  Task<User> Authenticate(string username, string password);
  Task<IEnumerable<User>> GetAllUsers();
}

Create CustomAuthorization class in an AuthHelper folder and paste the below code.

[AttributeUsage(AttributeTargets.Class)]
 public class CustomAuthorization : Attribute, IAuthorizationFilter
 {
   public void OnAuthorization(AuthorizationFilterContext filterContext)
   {
     if (filterContext != null)
     {
       Microsoft.Extensions.Primitives.StringValues UserName;
       Microsoft.Extensions.Primitives.StringValues Password;
       filterContext.HttpContext.Request.Headers.TryGetValue("username", out UserName);
       filterContext.HttpContext.Request.Headers.TryGetValue("password", out Password);

       var username = UserName.FirstOrDefault();
       var password = Password.FirstOrDefault();

       var uname = "admin";
       var pass = "admin";
       if (username == uname && password == pass)
       {
         return;
       }
       else
       {
         filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.ExpectationFailed;
         filterContext.HttpContext.Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = "UnAuthorized";
         filterContext.Result = new JsonResult("UnAuthorized")
         {
           Value = new
           {
             Status = "Error",
             Message = "Please Enter Corret username and password"
           },
         };
       }
     }
   }
 }

Create UserServices in the services folder and paste the below code.

public class UserServices : IUserServices
 {
       private List<User> _users = new List<User>
       {
           new User { Id = 1, Username = "admin", Password = "admin" }
       };

   public async Task<User> Authenticate(string username, string password)
   {

     var user = await Task.Run(() => _users.SingleOrDefault(x => x.Username == username && x.Password == password));
     if (user == null)
       return null;
     return user;
   }

   public async Task<IEnumerable<User>> GetAllUsers()
   {
     return await Task.Run(() => _users);
   }
 }

Output

Also check, Basic Authentication In .NET Core 5.0

Submit a Comment

Your email address will not be published.

Subscribe

Select Categories