Skip to content

Instantly share code, notes, and snippets.

@Kashkovsky
Last active June 10, 2016 09:28
Show Gist options
  • Save Kashkovsky/4c370c08dc172afabf6db5efab088ef0 to your computer and use it in GitHub Desktop.
Save Kashkovsky/4c370c08dc172afabf6db5efab088ef0 to your computer and use it in GitHub Desktop.
Custom authorize attribute
using System;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
namespace Common
{
public class CustomAuthAttribute : AuthorizeAttribute
{
private ApplicationUserManager _userManager;
public ApplicationUserManager UserManager
{
get
{
return _userManager ?? HttpContext.Current.GetOwinContext()
.GetUserManager<ApplicationUserManager>();
}
private set
{
_userManager = value;
}
}
private readonly string[] _allowedRoles;
public CustomAuthAttribute(params string[] roles)
{
_allowedRoles = roles;
}
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
var userId = httpContext.User.Identity.GetUserId();
if (userId == null)
{
return false;
}
var userRoles = UserManager.GetRolesAsync(userId).Result;
var canAccess = _allowedRoles.Any(x => userRoles.Contains(x));
if (canAccess) return true;
return false;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment