first time include all file
This commit is contained in:
@@ -0,0 +1,39 @@
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc.Filters;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using CarParkValidationAPI.Entities;
|
||||
using CarParkValidationAPI.Models;
|
||||
|
||||
namespace CarParkValidationAPI.Authorization
|
||||
{
|
||||
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
|
||||
public class AuthorizeAttribute : Attribute, IAuthorizationFilter
|
||||
{
|
||||
private readonly IList<AdminRole> _roles;
|
||||
|
||||
public AuthorizeAttribute(params AdminRole[] roles)
|
||||
{
|
||||
_roles = roles ?? new AdminRole[] { };
|
||||
}
|
||||
|
||||
public void OnAuthorization(AuthorizationFilterContext context)
|
||||
{
|
||||
// skip authorization if action is decorated with [AllowAnonymous] attribute
|
||||
var allowAnonymous = context.ActionDescriptor.EndpointMetadata.OfType<AllowAnonymousAttribute>().Any();
|
||||
if (allowAnonymous)
|
||||
return;
|
||||
|
||||
// authorization
|
||||
var user = (User)context.HttpContext.Items["User"];
|
||||
|
||||
if (user == null || (_roles.Any() && !_roles.Contains((AdminRole)user.Role)))
|
||||
{
|
||||
// not logged in or role not authorized
|
||||
context.Result = new JsonResult(new { message = "Unauthorized" }) { StatusCode = StatusCodes.Status401Unauthorized };
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user