Skip to content

Instantly share code, notes, and snippets.

@vanillajonathan
Created January 24, 2018 14:26
Show Gist options
  • Save vanillajonathan/5565f1003ffb8ff1e5bdba6706bef93d to your computer and use it in GitHub Desktop.
Save vanillajonathan/5565f1003ffb8ff1e5bdba6706bef93d to your computer and use it in GitHub Desktop.
Authorizes requests if the route parameter name equals a claim.
using System;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
namespace WebApplication
{
/// <summary>
/// Specifies that the class or method that this attribute is applied to requires
/// a route template with a route parameter name which value matches the claim
/// associated with the authenticated user.
/// </summary>
/// <seealso cref="RouteAttribute"/>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class RouteAuthorization : Attribute, IAuthorizationFilter
{
private readonly string _claimType;
private readonly string _routeParameter;
/// <summary>
/// Initializes a new instance of the <see cref="RouteAuthorization"/> class
/// with the specified claim type and router parameter name.
/// </summary>
/// <param name="claimType">The claim type.</param>
/// <param name="routeParameter">The route parameter name.</param>
public RouteAuthorization(string claimType, string routeParameter)
{
_claimType = claimType;
_routeParameter = routeParameter;
}
public void OnAuthorization(AuthorizationFilterContext context)
{
var routeParameter = context.RouteData.Values.SingleOrDefault(x => x.Key == _routeParameter);
var claim = context.HttpContext.User.FindFirst(_claimType);
var claimValue = (string)routeParameter.Value;
if (claim != null && claimValue != claim.Value)
{
context.Result = new UnauthorizedResult();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment