Creado apartir del commit b888de6c92056de294456f581a56e25e734d4ab7 de develop
This commit is contained in:
@@ -0,0 +1,28 @@
|
||||
using System.Security.Claims;
|
||||
using adas_core.Domain.Enums;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc.Filters;
|
||||
|
||||
namespace adas_core.Authentication.Attributes;
|
||||
|
||||
[AttributeUsage(AttributeTargets.Method)]
|
||||
public class AuthorizeRolesAttribute(PermissionEnum.RolesType type) : Attribute, IAuthorizationFilter
|
||||
{
|
||||
public void OnAuthorization(AuthorizationFilterContext context)
|
||||
{
|
||||
var user = context.HttpContext.User;
|
||||
|
||||
if (user.Identity?.IsAuthenticated != true)
|
||||
{
|
||||
context.Result = new UnauthorizedResult();
|
||||
return;
|
||||
}
|
||||
|
||||
var roles = user.Claims.Where(c => c.Type == ClaimTypes.Role);
|
||||
|
||||
if (type == PermissionEnum.RolesType.AuthSome) return;
|
||||
|
||||
var hasRequiredRole = roles.Any(r => r.Value.StartsWith(type.ToString()));
|
||||
if (!hasRequiredRole) context.Result = new ForbidResult();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user