//************** 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(validOn: AttributeTargets.Class)]
public class ApiKeyAttribute : Attribute, IAsyncActionFilter
{
private const string APIKEYNAME = "ApiKey";
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
if (!context.HttpContext.Request.Headers.TryGetValue(APIKEYNAME, out 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 { get; set; }
}
}
//******** 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 { get; set; }
public string ProductName { get; set; }
public Nullable<int> SupplierID { get; set; }
public Nullable<int> CategoryID { get; set; }
public string QuantityPerUnit { get; set; }
public Nullable<decimal> UnitPrice { get; set; }
public Nullable<short> UnitsInStock { get; set; }
public Nullable<short> UnitsOnOrder { get; set; }
public Nullable<short> ReorderLevel { get; set; }
public bool Discontinued { get; set; }
}
}
//******************* 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
Yorum Gönder