Created
October 2, 2018 07:39
-
-
Save arruw/e8168d163d8ace8bf5251fda84283bed to your computer and use it in GitHub Desktop.
Check policy action filter that uses ModelState to bind values to it
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
using Microsoft.AspNetCore.Authorization; | |
using Microsoft.AspNetCore.Mvc; | |
using Microsoft.AspNetCore.Mvc.Filters; | |
using System; | |
using System.Threading.Tasks; | |
using Microsoft.Extensions.DependencyInjection; | |
namespace Performa365.Web.Utils.Filters | |
{ | |
public class CheckPolicyFilter : IAsyncActionFilter | |
{ | |
private readonly IAuthorizationService _authorizationService; | |
private readonly string _policyName; | |
public CheckPolicyFilter(IAuthorizationService authorizationService, string policyName) | |
{ | |
this._authorizationService = authorizationService; | |
this._policyName = policyName; | |
} | |
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) | |
{ | |
var ctrl = ((Controller)context.Controller); | |
var result = await this._authorizationService.AuthorizeAsync( | |
ctrl.User, | |
context.ModelState, | |
this._policyName); | |
if (result.Succeeded) | |
return; | |
context.Result = new ChallengeResult(); | |
} | |
} | |
public class CheckPolicyFilterFactoryAttribute : Attribute, IFilterFactory | |
{ | |
private readonly string _policyName; | |
public bool IsReusable => false; | |
public CheckPolicyFilterFactoryAttribute(string policyName) | |
{ | |
this._policyName = policyName; | |
} | |
public IFilterMetadata CreateInstance(IServiceProvider serviceProvider) | |
{ | |
var authorizationService = serviceProvider.GetService<IAuthorizationService>(); | |
return new CheckPolicyFilter(authorizationService, this._policyName); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment