Skip to content

Instantly share code, notes, and snippets.

@arruw
Created October 2, 2018 07:39
Show Gist options
  • Save arruw/e8168d163d8ace8bf5251fda84283bed to your computer and use it in GitHub Desktop.
Save arruw/e8168d163d8ace8bf5251fda84283bed to your computer and use it in GitHub Desktop.
Check policy action filter that uses ModelState to bind values to it
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