Last active
June 10, 2016 09:28
-
-
Save Kashkovsky/4c370c08dc172afabf6db5efab088ef0 to your computer and use it in GitHub Desktop.
Custom authorize attribute
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 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