Securing WebApi classes with Attributes (e.g. [ApiKey]) .netcore5 webapi project


 

//************** Products controller

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using WebApi_SecuringAttributes.Attributes;
using WebApi_SecuringAttributes.Data;

namespace WebApi_SecuringAttributes.Controllers
{
    [Route("api/[controller]")]
    [ApiController
    [ApiKey]
    public class ProductsController : ControllerBase
    {

        private readonly dbContextNW _context;

        public ProductsController(dbContextNW context)
        {
            _context = context;
        }

        [HttpGet]
      
        public async Task<ActionResult<IEnumerable<Products>>> GetProducts()
        {
            return await _context.Products.ToListAsync();
        }

         
        [HttpGet("{id}")]
        public async Task<ActionResult<Products>> GetProduct(int id)
        {
            var products = await _context.Products.FindAsync(id);

            if (products == null)
            {
                return NotFound();
            }

            return products;
        }

    }
}

//*************************** ApiKey attribute
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Threading.Tasks;

namespace WebApi_SecuringAttributes.Attributes
{
    [AttributeUsage(validOnAttributeTargets.Class)]
    public class ApiKeyAttribute : AttributeIAsyncActionFilter
    {
        private const string APIKEYNAME = "ApiKey";
        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            if (!context.HttpContext.Request.Headers.TryGetValue(APIKEYNAMEout var extractedApiKey))
            {
                context.Result = new ContentResult()
                {
                    StatusCode = 401,
                    Content = "Api Key was not provided"
                };
                return;
            }

            var appSettings = context.HttpContext.RequestServices.GetRequiredService<IConfiguration>();

            var apiKey = appSettings.GetValue<string>(APIKEYNAME);

            if (!apiKey.Equals(extractedApiKey))
            {
                context.Result = new ContentResult()
                {
                    StatusCode = 401,
                    Content = "Unauthorized client"
                };
                return;
            }

            await next();
        }
    }
}

//******************* dbcontext NW - nortwind sample database
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace WebApi_SecuringAttributes.Data
{
    public partial class dbContextNW : DbContext
    {
        public dbContextNW(DbContextOptions<dbContextNW> options) : base(options)
        {

        }


        public DbSet<Products> Products { getset; }


    }
}
//******** products model
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;

namespace WebApi_SecuringAttributes.Data
{
    public class Products
    {

        public Products()
        {
            
        }

        [Key]
        public int ProductID { getset; }
        public string ProductName { getset; }
        public Nullable<int> SupplierID { getset; }
        public Nullable<int> CategoryID { getset; }
        public string QuantityPerUnit { getset; }
        public Nullable<decimal> UnitPrice { getset; }
        public Nullable<short> UnitsInStock { getset; }
        public Nullable<short> UnitsOnOrder { getset; }
        public Nullable<short> ReorderLevel { getset; }
        public bool Discontinued { getset; }
 
    }
}

//******************* appsettings json
{
  "Logging": {
    "LogLevel": {
      "Default""Information",
      "Microsoft""Warning",
      "Microsoft.Hosting.Lifetime""Information"
    }
  },
  "AllowedHosts""*",
  "ApiKey""12345678",
  "ConnectionStrings": {
    "DBConnection""Server=LOCALHOST;Database=NORTHWND;Trusted_Connection=True;MultipleActiveResultSets=True;"
  }
}


//***** Github public :
https://github.com/doktoralban/WebApi_SecuringAttributes



Yorumlar