Last active
July 16, 2020 07:16
-
-
Save jonathascosta/7e27400d871af66133e87d2310abb7b2 to your computer and use it in GitHub Desktop.
Checks when is the resource owner or someone with admin role
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ResourceOwnerOrAdminAttribute : Attribute, IAuthorizationRule | |
{ | |
private readonly string idArgumentName; | |
public ResourceOwnerOrAdminAttribute(string idArgumentName = "id") | |
{ | |
this.idArgumentName = idArgumentName; | |
} | |
public async Task<bool> HasAccess(ActionExecutingContext context) | |
{ | |
var someService = context.HttpContext.RequestServices.GetService<ISomeService>(); | |
if (context.ActionArguments.TryGetValue(idArgumentName, out var argument) && argument is Guid id) | |
{ | |
var obj = await someService.GetByIdAsync(id); | |
return context.HttpContext.User.HasClaim(c => | |
(c.Type == ClaimTypes.Role && c.Value == "Admin") || | |
(c.Type == ClaimTypes.UserId && c.Value == obj?.UserId)); | |
} | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment