42
loading...
This website collects cookies to deliver better user experience
GET /{resource}/something-else
PUT /users/{userId}
using Acl.Net.Backends;
using Acl.Net.Entities;
using Acl.Net.Interfaces;
using MongoDB.Driver;
namespace ConsoleApp
{
internal class Program
{
static void Main()
{
string mongoUrl = "mongodb://localhost:27017/Acl";
string databaseName = "Acl";
MongoClient db = new MongoClient(mongoUrl);
IBackend backend = new Mongodb(db, databaseName);
IAcl acl = new Acl.Net.Acl(backend);
acl.Allow(
new Role()
{
Name = "Administrator",
Resources = new[]
{
new Resource()
{
Name = "Users",
Permissions = new[] { "View", "Create", "Update", "Delete" }
},
new Resource()
{
Name = "Devices",
Permissions = new[] { "View", "Create", "Update" }
}
}
}
);
string username = "YourUser";
acl.AddUserRole(username, "Administrator");
bool isAllowedToViewAndCreateUsers = acl.IsAllowed(username, new Resource() { Name = "Users", Permissions = new[] { "View", "Create" } });
// Result: True
bool isAllowedDeleteUsers = acl.IsAllowed(username, new Resource() { Name = "Users", Permissions = new[] { "Delete" } });
// Result: True
bool isAllowedDeleteDevices = acl.IsAllowed(username, "Devices", "Delete");
// Result: False
bool isAllowedViewDevices = acl.IsAllowed(username, "Devices", "View");
// Result: True
}
}
}
using Acl.Net.Backends;
using Acl.Net.Interfaces;
using Microsoft.AspNetCore.Http;
using MongoDB.Driver;
using System.Net;
using System.Threading.Tasks;
namespace WebApplication
{
public class PermissingGuardMiddleware
{
private readonly RequestDelegate _next;
private readonly Acl.Net.Acl _acl;
public PermissingGuardMiddleware(RequestDelegate next)
{
string mongoUrl = "mongodb://localhost:27017/Acl";
string databaseName = "Acl";
MongoClient db = new MongoClient(mongoUrl);
IBackend backend = new Mongodb(db, databaseName);
this._acl = new Acl.Net.Acl(backend);
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
string authHeader = context.Request.Headers["Authentication"].ToString();
string[] paths = ((string)context.Request.Path).Split('/');
string permission = TransforMethodToPermission(context.Request.Method);
if (permission == null || paths[0] == null)
{
await Unauthorize(context);
return;
}
try
{
bool isAllowed = this._acl.IsAllowed(authHeader, paths[0], permission);
if (!isAllowed)
{
await Unauthorize(context);
return;
}
await _next(context);
}
catch (System.Exception)
{
await Unauthorize(context);
return;
}
}
private string TransforMethodToPermission(string method)
{
switch (method.ToUpper())
{
case "POST":
return "Creare";
case "GET":
return "View";
case "DELETE":
return "Delete";
case "PUT":
case "UPDATE":
return "Update";
default:
return null;
}
}
private async Task Unauthorize(HttpContext context)
{
context.Response.Clear();
context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
await context.Response.WriteAsync("Unauthorized");
}
}
}