Customizing .net Identity 2 - c#

I have an MVC5 application with .net 4.7.2 and I'm trying to have my customized version of .net Identity classes. I've followed the steps in this tutorial, with some changes here and there, because my project rely on a set of WCF services to communicate with the database, so I don't have direct connection to the database:
overview-of-custom-storage-providers-for-aspnet-identity
So mainly I've created my own MyUserStore which implements IUserStore and IUserRoleStore, and I've added this to Startup.cs:
public void ConfigureAuth(IAppBuilder app)
{
app.CreatePerOwinContext<MyUserManager>(MyUserManager.Create);
}
Now the problem that the IsInRole methods are not getting invoked, and also I had break point for methods like FindByIdAsync, FindByNameAsync and IsInRoleAsync and nothing got invoked, even though I've added
[Authorize(Roles ="TestRole")] attribute to couple actions and has tried to invoke this explicitly:
this.User.IsInRole("TestRole");
What I'm missing here to have it work in the proper way?
Edit #1 - adding the whole code:
Here under is the User Store related classes:
public class MyUserStore :
IUserStore<MyIdentityUser, int>,
IUserRoleStore<MyIdentityUser, int>,
IQueryableUserStore<MyIdentityUser, int>,
IDisposable
{
public Task CreateAsync(MyIdentityUser account)
{
// Add account to DB...
return Task.FromResult<object>(null);
}
public Task<MyIdentityUser> FindByIdAsync(int accountId)
{
// Get account from DB and return it
return Task.FromResult<MyIdentityUser>(account);
}
public Task<MyIdentityUser> FindByNameAsync(string userName)
{
// Get account from DB and return it
return Task.FromResult<MyIdentityUser>(account);
}
public Task UpdateAsync(MyIdentityUser account)
{
// Update account in DB
return Task.FromResult<object>(null);
}
public Task AddToRoleAsync(MyIdentityUser account, string roleName)
{
throw new NotImplementedException("UserStore.AddToRoleAsync");
return Task.FromResult<object>(null);
}
public Task<IList<string>> GetRolesAsync(MyIdentityUser account)
{
// TODO: Check if important to implement
throw new NotImplementedException("UserStore.GetRolesAsync");
}
public Task<bool> IsInRoleAsync(MyIdentityUser account, string task)
{
// Return true if has permission (not getting invoked)
return Task.FromResult<bool>(hasPermission);
}
public Task RemoveFromRoleAsync(MyIdentityUser account, string task)
{
throw new NotImplementedException("UserStore.RemoveFromRoleAsync");
}
public Task DeleteAsync(MyIdentityUser account)
{
// Delete user from DB
return Task.FromResult<Object>(null);
}
}
public class MyUserRole : IdentityUserRole<int> { }
public class MyUserClaim : IdentityUserClaim<int> { }
public class MyUserLogin : IdentityUserLogin<int> { }
public class MyIdentityUser : IdentityUser<int, MyUserLogin, MyUserRole, MyUserClaim>
{
public MyIdentityUser(int id)
{
Id = id;
}
// My extra account's properties
}
}
And here is the UserManager class:
public class MyUserManager : UserManager<MyIdentityUser, int>
{
public MyUserManager(IUserStore<MyIdentityUser, int> store)
: base(store) { }
public static MyUserManager Create(IdentityFactoryOptions<MyUserManager> options, IOwinContext context)
{
///Calling the non-default constructor of the UserStore class
var manager = new MyUserManager(new MyUserStore());
manager.UserValidator = new UserValidator<MyIdentityUser, int>(manager)
{
AllowOnlyAlphanumericUserNames = false,
RequireUniqueEmail = true
};
// Configure validation logic for passwords
manager.PasswordValidator = new PasswordValidator
{
RequiredLength = 6,
};
// Configure user lockout defaults
manager.UserLockoutEnabledByDefault = false;
manager.DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5);
manager.MaxFailedAccessAttemptsBeforeLockout = 3;
// You can write your own provider and plug it in here.
return manager;
}
}
And maybe this is the most important part, the login controller:
var manager = HttpContext.GetOwinContext().GetUserManager<MyUserManager>();
//check for credentials before sign in ..
var result = manager.CheckPasswordAsync(vm.userName, vm.password, ref state);
if(result.Result)
{
FormsAuthentication.SetAuthCookie(vm.userName, vm.rememberMe);
return Redirect("~/");
}
Regards,

Related

Role Based Authentication for web API not working

I'm facing an issue while working with Role-Based authentication for web APi.
I have a controller class where the controller has a custom authorize attribute called Myauthorize.
I have a method inside the controller which can be accessed only with Admin access.
But the same method has been calling with QA access as well.
Could anyone please help with the below?
Please find the code below.
Controller :
namespace Hosiptal.Controllers.office
{
[MyAuthorize(Constants.Roles.Admin)]
public class UserRolesController : ApiController
{
private readonly IRepository<EntityModels.Role> rolesRepository;
public UserRolesController(IRepository<EntityModels.Role> rolesRepository)
{
this.rolesRepository = rolesRepository;
}
// GET: Users
[HttpGet]
[Route("")]
public IEnumerable<Role> GetAll()
{
return this.rolesRepository.GetAll()
.ToArray()
.Select(r => Mapper.Current.Get<Role>(r));
}
}
}
MyAuthorize has followed.
namespace Hospital.Web.Filters.WebApi
{
public class MyAuthorize: AuthorizeAttribute
{
private readonly string[] allowedroles;
private static IUserProfileRepository UserProfileRepository
{
get { return IoC.Current.Resolve<IUserProfileRepository>(); }
}
public MyAuthorize(params string[] roles)
{
this.allowedroles = roles;
}
public override Task OnAuthorizationAsync(HttpActionContext actionContext, CancellationToken
cancellationToken)
{
var claimsIdentity = actionContext.RequestContext.Principal.Identity as ClaimsIdentity;
var alias = claimsIdentity.Name.Split('#')[0];
if (alias == null)
{
throw new ArgumentNullException(nameof(actionContext));
}
user(alias);
return base.OnAuthorizationAsync(actionContext, cancellationToken);
}
public static GenericPrincipal user(string userName)
{
userName = userName.ToUpper();
var userProfile = UserProfileRepository.Get(userName) ?? new UserProfile()
{
UserName = userName,
Roles = new List<Role>(),
FirstLoginDateUtc = DateTime.UtcNow
};
return CreatePrincipal(userProfile);
}
public static GenericPrincipal CreatePrincipal(UserProfile user)
{
var identity = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name,
user.UserName) }, "Custom");
return new GenericPrincipal(identity, user.Roles.Select(i =>
i.Name).ToArray());
}
}
}
How can restrict the user here based on access level?
If you review the source code for the AuthorizeAttribute class, you will see that it uses the controller context request's principal to perform authorization, so override the IsAuthorized method instead, move your code there and assign the principal you create to the context request's principal:
protected override bool IsAuthorized(HttpActionContext actionContext)
{
var claimsIdentity = actionContext.RequestContext.Principal.Identity as ClaimsIdentity;
var alias = claimsIdentity.Name.Split('#')[0];
if (alias == null)
{
throw new ArgumentNullException(nameof(actionContext));
}
//This sets the context's principal so the base class code can validate
actionContext.ControllerContext.RequestContext.Principal = user(alias);
//Call the base class and let it work its magic
return base.IsAuthorized(actionContext);
}
I will refrain from commenting on the design itself. This should fix your issue.
This is what's working for me
public class AdminAuthorizeAttributee : AuthorizeAttribute
{
public override void OnAuthorization(HttpActionContext actionContext)
{
if (AuthorizeRequest(actionContext))
{
return;
}
HandleUnauthorizedRequest(actionContext);
}
protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
{
base.HandleUnauthorizedRequest(actionContext);
}
private bool AuthorizeRequest(HttpActionContext actionContext)
{
try
{
var username = HttpContext.Current.User.Identity.Name;
var userManager = HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();
var user = userManager.Users.Where(a => a.UserName == username).FirstOrDefault();
var rolesForUser = userManager.GetRoles(user.Id);
var role = "Admin";
if (rolesForUser.Contains(role))
{
return true;
}
return false;
}
catch (Exception ex)
{
return false;
}
}
}
and in Controller
[AdminAuthorizeAttributee]
public class YOUR_Controller : ApiController
You don't need to create your own authorize filter for this.
Use the built-in [Authorize(Roles = "Admin")] - which will check if the user has a claim called "http://schemas.microsoft.com/ws/2008/06/identity/claims/role" and if that value matches to the one you put in that authorize attribute, the authorization will succeed.
So in your case just make sure, when you log in the user to set his claim with the role like this:
var claims = new List<Claim>()
{
new Claim(ClaimTypes.Role, "Admin"), //here set the users role
// ... other claims
};
(ClaimTypes class is from the namespace System.Security.Claims)
And then the [Authorize(Roles = "Admin")] should work just fine

Checking ABP permissions from claims

I am using ABP version 3.9 for ASP.NET Core. We have an existing Identity Server 4 instance that provides role information in the form of claims (via OIDC). I would like to hook into ABP's permissions system for dynamic menu-ing, among other things. Since I'm not using a local Identity Server1 implementation, I don't see a way to convert the claims to permissions.
My thought is to use custom middleware to handle it like this:
public class ClaimsToAbpPermissionsMiddleware
{
private readonly RequestDelegate _next;
public ClaimsToAbpPermissionsMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
// Get user
ClaimsPrincipal user = context.User;
// foreach claim of type "role"
var roleClaims = user.Claims.Where(claim => claim.Type == "role");
foreach (Claim claim in roleClaims)
{
switch (claim.Value)
{
case "TestResults":
// Assign applicable permission
// ...
break;
default:
break;
}
}
// Call the next delegate/middleware in the pipeline
await _next(context);
}
}
The problem is that I don't know how to apply the permissions. User Management2 suggests using UserManager, which appears to have the necessary functionality.
First, Abp.ZeroCore doesn't have this class. Can I use Abp.Zero in an ASP.NET Core app?
Second, it looks like Abp.Authorization.Users.AbpUserManager has similar functionality. Can I use this? However, I'm not sure how to inject this into Startup, as it requires some types for injecting AbpUserManager<TRole, TUser> and I'm not clear on what types to use.
Any help would be appreciated.
Additionally, is what I'm trying feasible? Is there a better approach?
The issue is that I'm not using Module Zero's User Management2. All of our users are in a separate ASP.NET Identity (Identity Server) implementation, and I'm using the template from ABP that doesn't include the models/pages for user/tenant/role, so I don't have the types to inject AbpUserManager<TRole, TUser>.
1https://aspnetboilerplate.com/Pages/Documents/Zero/Identity-Server
2https://aspnetboilerplate.com/Pages/Documents/Zero/User-Management
Update: So I implemented IPermissionChecker as per the answer below:
PermissionChecker (not in love with the switch, but am going to refactor once it's working):
public class PermissionChecker : IPermissionChecker, ITransientDependency
{
private readonly IHttpContextAccessor _httpContextAccessor;
public PermissionChecker(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
public Task<bool> IsGrantedAsync(string permissionName)
{
bool isGranted = false;
// Get user
var user = _httpContextAccessor.HttpContext.User;
// Get claims of type "role"
var roleClaims = user.Claims.Where(claim => claim.Type == "role");
// Check for applicable permission based on role permissions
foreach (Claim claim in roleClaims)
{
switch (claim.Value)
{
case "TestResults":
// Assign applicable permission
// ...
if(permissionName.ToLowerInvariant() == "TestResults".ToLowerInvariant())
{
isGranted = true;
}
break;
case "About":
// Assign applicable permission
// ...
if (permissionName.ToLowerInvariant() == "AboutView".ToLowerInvariant())
{
isGranted = true;
}
break;
case "Account":
// Assign applicable permission
// ...
if (permissionName.ToLowerInvariant() == "AccountView".ToLowerInvariant())
{
isGranted = true;
}
break;
default:
break;
}
if (isGranted)
{
break;
}
}
//return new Task<bool>
return Task.FromResult(isGranted);
}
public Task<bool> IsGrantedAsync(UserIdentifier user, string permissionName)
{
return IsGrantedAsync(permissionName);
}
}
AuthorizationProvider:
public class MyAuthProvider : AuthorizationProvider
{
public override void SetPermissions(IPermissionDefinitionContext context)
{
var about = context.CreatePermission("AboutView");
var account = context.CreatePermission("AccountView");
var testResults = context.CreatePermission("TestResults");
}
}
Module Initialization:
public class CentralPortalCoreModule : AbpModule
{
public override void PreInitialize()
{
Configuration.Auditing.IsEnabledForAnonymousUsers = true;
CentralPortalLocalizationConfigurer.Configure(Configuration.Localization);
IocManager.Register<IPermissionChecker, PermissionChecker>(DependencyLifeStyle.Transient);
Configuration.Authorization.Providers.Add<MyAuthProvider>();
}
public override void Initialize()
{
IocManager.RegisterAssemblyByConvention(typeof(CentralPortalCoreModule).GetAssembly());
}
}
Navigation Provider:
public override void SetNavigation(INavigationProviderContext context)
{
context.Manager.MainMenu
.AddItem(
new MenuItemDefinition(
PageNames.Home,
L("HomePage"),
url: "",
icon: "fa fa-home"
)
).AddItem(
new MenuItemDefinition(
PageNames.About,
L("About"),
url: "Home/About",
icon: "fa fa-info",
requiredPermissionName: "AboutView",
requiresAuthentication: true
)
).AddItem(
new MenuItemDefinition(
"Results",
L("Results"),
url: "Results",
icon: "fa fa-tasks",
requiredPermissionName: "TestResults"
)
)
.AddItem(
new MenuItemDefinition(
PageNames.Account,
L("Account"),
url: "Account",
icon: "fa fa-info",
requiredPermissionName:"AccountView",
requiresAuthentication: true
)
)
.AddItem(
new MenuItemDefinition(
PageNames.Contact,
L("Contact"),
url: "Contact",
icon: "fa fa-info"
)
);
}
Adding breakpoints shows that the PermissionChecker is initialized as is the AuthProvider. Unfortunately, the navigation doesn't show the protected items even though I am authenticated and have valid role claims. The IsGrantedAsync method is never called. I tried setting the nav items with requiresAuthentication = true and false and neither changed anything.
Am I missing something?
Well, you're referring to Module Zero documentation but not using Module Zero.
If you don't store users, then it may not make sense to store user permissions.
You can implement IPermissionChecker to check permissions from claims.
public class PermissionChecker : IPermissionChecker, ITransientDependency
{
private readonly IHttpContextAccessor _httpContextAccessor;
public PermissionChecker(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
public async Task<bool> IsGrantedAsync(string permissionName)
{
// Get user
var user = _httpContextAccessor.HttpContext.User;
// Get claims of type "role"
var roleClaims = user.Claims.Where(claim => claim.Type == "role");
// Check for applicable permission based on role permissions
// ...
}
public Task<bool> IsGrantedAsync(UserIdentifier user, string permissionName)
{
return IsGrantedAsync(permissionName);
}
}
Since AuthorizationHelper checks AbpSession.UserId, you'll have to override its method.
public class NonUserAuthorizationHelper : AuthorizationHelper
{
private readonly IAuthorizationConfiguration _authConfiguration
public NonUserAuthorizationHelper(IFeatureChecker featureChecker, IAuthorizationConfiguration authConfiguration)
: base(featureChecker, authConfiguration)
{
_authConfiguration = authConfiguration;
}
public override async Task AuthorizeAsync(IEnumerable<IAbpAuthorizeAttribute> authorizeAttributes)
{
if (!_authConfiguration.IsEnabled)
{
return;
}
// if (!AbpSession.UserId.HasValue)
// {
// throw new AbpAuthorizationException(
// LocalizationManager.GetString(AbpConsts.LocalizationSourceName, "CurrentUserDidNotLoginToTheApplication")
// );
// }
foreach (var authorizeAttribute in authorizeAttributes)
{
await PermissionChecker.AuthorizeAsync(authorizeAttribute.RequireAllPermissions, authorizeAttribute.Permissions);
}
}
}
And then replace it in the PreInitialize method of your *.Core module.
// using Abp.Configuration.Startup;
public override void PreInitialize()
{
Configuration.ReplaceService<IAuthorizationHelper, NonUserAuthorizationHelper>();
}

Custom authorization attribute implementation [duplicate]

I'm trying to make a custom authorization attribute in ASP.NET Core. In previous versions it was possible to override bool AuthorizeCore(HttpContextBase httpContext). But this no longer exists in AuthorizeAttribute.
What is the current approach to make a custom AuthorizeAttribute?
What I am trying to accomplish: I am receiving a session ID in the Header Authorization. From that ID I'll know whether a particular action is valid.
The approach recommended by the ASP.Net Core team is to use the new policy design which is fully documented here. The basic idea behind the new approach is to use the new [Authorize] attribute to designate a "policy" (e.g. [Authorize( Policy = "YouNeedToBe18ToDoThis")] where the policy is registered in the application's Startup.cs to execute some block of code (i.e. ensure the user has an age claim where the age is 18 or older).
The policy design is a great addition to the framework and the ASP.Net Security Core team should be commended for its introduction. That said, it isn't well-suited for all cases. The shortcoming of this approach is that it fails to provide a convenient solution for the most common need of simply asserting that a given controller or action requires a given claim type. In the case where an application may have hundreds of discrete permissions governing CRUD operations on individual REST resources ("CanCreateOrder", "CanReadOrder", "CanUpdateOrder", "CanDeleteOrder", etc.), the new approach either requires repetitive one-to-one mappings between a policy name and a claim name (e.g. options.AddPolicy("CanUpdateOrder", policy => policy.RequireClaim(MyClaimTypes.Permission, "CanUpdateOrder));), or writing some code to perform these registrations at run time (e.g. read all claim types from a database and perform the aforementioned call in a loop). The problem with this approach for the majority of cases is that it's unnecessary overhead.
While the ASP.Net Core Security team recommends never creating your own solution, in some cases this may be the most prudent option with which to start.
The following is an implementation which uses the IAuthorizationFilter to provide a simple way to express a claim requirement for a given controller or action:
public class ClaimRequirementAttribute : TypeFilterAttribute
{
public ClaimRequirementAttribute(string claimType, string claimValue) : base(typeof(ClaimRequirementFilter))
{
Arguments = new object[] {new Claim(claimType, claimValue) };
}
}
public class ClaimRequirementFilter : IAuthorizationFilter
{
readonly Claim _claim;
public ClaimRequirementFilter(Claim claim)
{
_claim = claim;
}
public void OnAuthorization(AuthorizationFilterContext context)
{
var hasClaim = context.HttpContext.User.Claims.Any(c => c.Type == _claim.Type && c.Value == _claim.Value);
if (!hasClaim)
{
context.Result = new ForbidResult();
}
}
}
[Route("api/resource")]
public class MyController : Controller
{
[ClaimRequirement(MyClaimTypes.Permission, "CanReadResource")]
[HttpGet]
public IActionResult GetResource()
{
return Ok();
}
}
I'm the asp.net security person. Firstly let me apologize that none of this is documented yet outside of the music store sample or unit tests, and it's all still being refined in terms of exposed APIs. Detailed documentation is here.
We don't want you writing custom authorize attributes. If you need to do that we've done something wrong. Instead, you should be writing authorization requirements.
Authorization acts upon Identities. Identities are created by authentication.
You say in comments you want to check a session ID in a header. Your session ID would be the basis for identity. If you wanted to use the Authorize attribute you'd write an authentication middleware to take that header and turn it into an authenticated ClaimsPrincipal. You would then check that inside an authorization requirement. Authorization requirements can be as complicated as you like, for example here's one that takes a date of birth claim on the current identity and will authorize if the user is over 18;
public class Over18Requirement : AuthorizationHandler<Over18Requirement>, IAuthorizationRequirement
{
public override void Handle(AuthorizationHandlerContext context, Over18Requirement requirement)
{
if (!context.User.HasClaim(c => c.Type == ClaimTypes.DateOfBirth))
{
context.Fail();
return;
}
var dobVal = context.User.FindFirst(c => c.Type == ClaimTypes.DateOfBirth).Value;
var dateOfBirth = Convert.ToDateTime(dobVal);
int age = DateTime.Today.Year - dateOfBirth.Year;
if (dateOfBirth > DateTime.Today.AddYears(-age))
{
age--;
}
if (age >= 18)
{
context.Succeed(requirement);
}
else
{
context.Fail();
}
}
}
Then in your ConfigureServices() function you'd wire it up
services.AddAuthorization(options =>
{
options.AddPolicy("Over18",
policy => policy.Requirements.Add(new Authorization.Over18Requirement()));
});
And finally, apply it to a controller or action method with
[Authorize(Policy = "Over18")]
It seems that with ASP.NET Core 2, you can again inherit AuthorizeAttribute, you just need to also implement IAuthorizationFilter (or IAsyncAuthorizationFilter):
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
public class CustomAuthorizeAttribute : AuthorizeAttribute, IAuthorizationFilter
{
private readonly string _someFilterParameter;
public CustomAuthorizeAttribute(string someFilterParameter)
{
_someFilterParameter = someFilterParameter;
}
public void OnAuthorization(AuthorizationFilterContext context)
{
var user = context.HttpContext.User;
if (!user.Identity.IsAuthenticated)
{
// it isn't needed to set unauthorized result
// as the base class already requires the user to be authenticated
// this also makes redirect to a login page work properly
// context.Result = new UnauthorizedResult();
return;
}
// you can also use registered services
var someService = context.HttpContext.RequestServices.GetService<ISomeService>();
var isAuthorized = someService.IsUserAuthorized(user.Identity.Name, _someFilterParameter);
if (!isAuthorized)
{
context.Result = new StatusCodeResult((int)System.Net.HttpStatusCode.Forbidden);
return;
}
}
}
Based on Derek Greer GREAT answer, i did it with enums.
Here is an example of my code:
public enum PermissionItem
{
User,
Product,
Contact,
Review,
Client
}
public enum PermissionAction
{
Read,
Create,
}
public class AuthorizeAttribute : TypeFilterAttribute
{
public AuthorizeAttribute(PermissionItem item, PermissionAction action)
: base(typeof(AuthorizeActionFilter))
{
Arguments = new object[] { item, action };
}
}
public class AuthorizeActionFilter : IAuthorizationFilter
{
private readonly PermissionItem _item;
private readonly PermissionAction _action;
public AuthorizeActionFilter(PermissionItem item, PermissionAction action)
{
_item = item;
_action = action;
}
public void OnAuthorization(AuthorizationFilterContext context)
{
bool isAuthorized = MumboJumboFunction(context.HttpContext.User, _item, _action); // :)
if (!isAuthorized)
{
context.Result = new ForbidResult();
}
}
}
public class UserController : BaseController
{
private readonly DbContext _context;
public UserController( DbContext context) :
base()
{
_logger = logger;
}
[Authorize(PermissionItem.User, PermissionAction.Read)]
public async Task<IActionResult> Index()
{
return View(await _context.User.ToListAsync());
}
}
You can create your own AuthorizationHandler that will find custom attributes on your Controllers and Actions, and pass them to the HandleRequirementAsync method.
public abstract class AttributeAuthorizationHandler<TRequirement, TAttribute> : AuthorizationHandler<TRequirement> where TRequirement : IAuthorizationRequirement where TAttribute : Attribute
{
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, TRequirement requirement)
{
var attributes = new List<TAttribute>();
var action = (context.Resource as AuthorizationFilterContext)?.ActionDescriptor as ControllerActionDescriptor;
if (action != null)
{
attributes.AddRange(GetAttributes(action.ControllerTypeInfo.UnderlyingSystemType));
attributes.AddRange(GetAttributes(action.MethodInfo));
}
return HandleRequirementAsync(context, requirement, attributes);
}
protected abstract Task HandleRequirementAsync(AuthorizationHandlerContext context, TRequirement requirement, IEnumerable<TAttribute> attributes);
private static IEnumerable<TAttribute> GetAttributes(MemberInfo memberInfo)
{
return memberInfo.GetCustomAttributes(typeof(TAttribute), false).Cast<TAttribute>();
}
}
Then you can use it for any custom attributes you need on your controllers or actions. For example to add permission requirements. Just create your custom attribute.
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
public class PermissionAttribute : AuthorizeAttribute
{
public string Name { get; }
public PermissionAttribute(string name) : base("Permission")
{
Name = name;
}
}
Then create a Requirement to add to your Policy
public class PermissionAuthorizationRequirement : IAuthorizationRequirement
{
//Add any custom requirement properties if you have them
}
Then create the AuthorizationHandler for your custom attribute, inheriting the AttributeAuthorizationHandler that we created earlier. It will be passed an IEnumerable for all your custom attributes in the HandleRequirementsAsync method, accumulated from your Controller and Action.
public class PermissionAuthorizationHandler : AttributeAuthorizationHandler<PermissionAuthorizationRequirement, PermissionAttribute>
{
protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, PermissionAuthorizationRequirement requirement, IEnumerable<PermissionAttribute> attributes)
{
foreach (var permissionAttribute in attributes)
{
if (!await AuthorizeAsync(context.User, permissionAttribute.Name))
{
return;
}
}
context.Succeed(requirement);
}
private Task<bool> AuthorizeAsync(ClaimsPrincipal user, string permission)
{
//Implement your custom user permission logic here
}
}
And finally, in your Startup.cs ConfigureServices method, add your custom AuthorizationHandler to the services, and add your Policy.
services.AddSingleton<IAuthorizationHandler, PermissionAuthorizationHandler>();
services.AddAuthorization(options =>
{
options.AddPolicy("Permission", policyBuilder =>
{
policyBuilder.Requirements.Add(new PermissionAuthorizationRequirement());
});
});
Now you can simply decorate your Controllers and Actions with your custom attribute.
[Permission("AccessCustomers")]
public class CustomersController
{
[Permission("AddCustomer")]
IActionResult AddCustomer([FromBody] Customer customer)
{
//Add customer
}
}
What is the current approach to make a custom AuthorizeAttribute
For pure authorization scenarios (like restricting access to specific users only), the recommended approach is to use the new authorization block: https://github.com/aspnet/MusicStore/blob/1c0aeb08bb1ebd846726232226279bbe001782e1/samples/MusicStore/Startup.cs#L84-L92
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.Configure<AuthorizationOptions>(options =>
{
options.AddPolicy("ManageStore", policy => policy.RequireClaim("Action", "ManageStore"));
});
}
}
public class StoreController : Controller
{
[Authorize(Policy = "ManageStore"), HttpGet]
public async Task<IActionResult> Manage() { ... }
}
For authentication, it's best handled at the middleware level.
What are you trying to achieve exactly?
What?!
I decided to add another simple answer. B/c I find most of these answers a little overengineered. And also because I needed a way to GRANT authorization, not just DENY it. Most of the answers here offer a way to "tighten" security, but I wanted to "loosen" it. For example: "if some application setting is configured, then allow access to anonymous users".
public class MyAuthAttribute : Attribute, IAuthorizationFilter
{
public void OnAuthorization(AuthorizationFilterContext context)
{
//check access
if (CheckPermissions())
{
//all good, add optional code if you want. Or don't
}
else
{
//DENIED!
//return "ChallengeResult" to redirect to login page (for example)
context.Result = new ChallengeResult(CookieAuthenticationDefaults.AuthenticationScheme);
}
}
}
That's it. No need to mess with "policies", "claims", "handlers" and other [beep]
Usage:
// GET api/Get/5
[MyAuth]
public ActionResult<string> Get(int id)
{
return "blahblah";
}
The modern way is AuthenticationHandlers
in startup.cs add
services.AddAuthentication("BasicAuthentication").AddScheme<AuthenticationSchemeOptions, BasicAuthenticationHandler>("BasicAuthentication", null);
public class BasicAuthenticationHandler : AuthenticationHandler<AuthenticationSchemeOptions>
{
private readonly IUserService _userService;
public BasicAuthenticationHandler(
IOptionsMonitor<AuthenticationSchemeOptions> options,
ILoggerFactory logger,
UrlEncoder encoder,
ISystemClock clock,
IUserService userService)
: base(options, logger, encoder, clock)
{
_userService = userService;
}
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
{
if (!Request.Headers.ContainsKey("Authorization"))
return AuthenticateResult.Fail("Missing Authorization Header");
User user = null;
try
{
var authHeader = AuthenticationHeaderValue.Parse(Request.Headers["Authorization"]);
var credentialBytes = Convert.FromBase64String(authHeader.Parameter);
var credentials = Encoding.UTF8.GetString(credentialBytes).Split(new[] { ':' }, 2);
var username = credentials[0];
var password = credentials[1];
user = await _userService.Authenticate(username, password);
}
catch
{
return AuthenticateResult.Fail("Invalid Authorization Header");
}
if (user == null)
return AuthenticateResult.Fail("Invalid User-name or Password");
var claims = new[] {
new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
new Claim(ClaimTypes.Name, user.Username),
};
var identity = new ClaimsIdentity(claims, Scheme.Name);
var principal = new ClaimsPrincipal(identity);
var ticket = new AuthenticationTicket(principal, Scheme.Name);
return AuthenticateResult.Success(ticket);
}
}
IUserService is a service that you make where you have user name and password.
basically it returns a user class that you use to map your claims on.
var claims = new[] {
new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
new Claim(ClaimTypes.Name, user.Username),
};
Then you can query these claims and her any data you mapped, ther are quite a few, have a look at ClaimTypes class
you can use this in an extension method an get any of the mappings
public int? GetUserId()
{
if (context.User.Identity.IsAuthenticated)
{
var id=context.User.FindFirst(ClaimTypes.NameIdentifier);
if (!(id is null) && int.TryParse(id.Value, out var userId))
return userId;
}
return new Nullable<int>();
}
This new way, i think is better than the old way as shown here, both work
public class BasicAuthenticationAttribute : AuthorizationFilterAttribute
{
public override void OnAuthorization(HttpActionContext actionContext)
{
if (actionContext.Request.Headers.Authorization != null)
{
var authToken = actionContext.Request.Headers.Authorization.Parameter;
// decoding authToken we get decode value in 'Username:Password' format
var decodeauthToken = System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(authToken));
// spliting decodeauthToken using ':'
var arrUserNameandPassword = decodeauthToken.Split(':');
// at 0th postion of array we get username and at 1st we get password
if (IsAuthorizedUser(arrUserNameandPassword[0], arrUserNameandPassword[1]))
{
// setting current principle
Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity(arrUserNameandPassword[0]), null);
}
else
{
actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
}
}
else
{
actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
}
}
public static bool IsAuthorizedUser(string Username, string Password)
{
// In this method we can handle our database logic here...
return Username.Equals("test") && Password == "test";
}
}
If anyone just wants to validate a bearer token in the authorize phase using the current security practices you can,
add this to your Startup/ConfigureServices
services.AddSingleton<IAuthorizationHandler, BearerAuthorizationHandler>();
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer();
services.AddAuthorization(options => options.AddPolicy("Bearer",
policy => policy.AddRequirements(new BearerRequirement())
)
);
and this in your codebase,
public class BearerRequirement : IAuthorizationRequirement
{
public async Task<bool> IsTokenValid(SomeValidationContext context, string token)
{
// here you can check if the token received is valid
return true;
}
}
public class BearerAuthorizationHandler : AuthorizationHandler<BearerRequirement>
{
public BearerAuthorizationHandler(SomeValidationContext thatYouCanInject)
{
...
}
protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, BearerRequirement requirement)
{
var authFilterCtx = (Microsoft.AspNetCore.Mvc.Filters.AuthorizationFilterContext)context.Resource;
string authHeader = authFilterCtx.HttpContext.Request.Headers["Authorization"];
if (authHeader != null && authHeader.Contains("Bearer"))
{
var token = authHeader.Replace("Bearer ", string.Empty);
if (await requirement.IsTokenValid(thatYouCanInject, token))
{
context.Succeed(requirement);
}
}
}
}
If the code doesn't reach context.Succeed(...) it will Fail anyway (401).
And then in your controllers you can use
[Authorize(Policy = "Bearer", AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
The below code worked for me in .Net Core 5
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class AccessAuthorizationAttribute : AuthorizeAttribute, IAuthorizationFilter
{
public string Module { get; set; } //Permission string to get from controller
public AccessAuthorizationAttribute(string module)
{
Module = module;
}
public void OnAuthorization(AuthorizationFilterContext context)
{
//Validate if any permissions are passed when using attribute at controller or action level
if (string.IsNullOrEmpty(Module))
{
//Validation cannot take place without any permissions so returning unauthorized
context.Result = new UnauthorizedResult();
return;
}
if (hasAccess)
{
return;
}
context.Result = new UnauthorizedResult();
return;
}
}
The accepted answer (https://stackoverflow.com/a/41348219/4974715) is not realistically maintainable or suitable because "CanReadResource" is being used as a claim (but should essentially be a policy in reality, IMO). The approach at the answer is not OK in the way it was used, because if an action method requires many different claims setups, then with that answer you would have to repeatedly write something like...
[ClaimRequirement(MyClaimTypes.Permission, "CanReadResource")]
[ClaimRequirement(MyClaimTypes.AnotherPermision, "AnotherClaimVaue")]
//and etc. on a single action.
So, imagine how much coding that would take. Ideally, "CanReadResource" is supposed to be a policy that uses many claims to determine if a user can read a resource.
What I do is I create my policies as an enumeration and then loop through and set up the requirements like thus...
services.AddAuthorization(authorizationOptions =>
{
foreach (var policyString in Enum.GetNames(typeof(Enumerations.Security.Policy)))
{
authorizationOptions.AddPolicy(
policyString,
authorizationPolicyBuilder => authorizationPolicyBuilder.Requirements.Add(new DefaultAuthorizationRequirement((Enumerations.Security.Policy)Enum.Parse(typeof(Enumerations.Security.Policy), policyWrtString), DateTime.UtcNow)));
/* Note that thisn does not stop you from
configuring policies directly against a username, claims, roles, etc. You can do the usual.
*/
}
});
The DefaultAuthorizationRequirement class looks like...
public class DefaultAuthorizationRequirement : IAuthorizationRequirement
{
public Enumerations.Security.Policy Policy {get; set;} //This is a mere enumeration whose code is not shown.
public DateTime DateTimeOfSetup {get; set;} //Just in case you have to know when the app started up. And you may want to log out a user if their profile was modified after this date-time, etc.
}
public class DefaultAuthorizationHandler : AuthorizationHandler<DefaultAuthorizationRequirement>
{
private IAServiceToUse _aServiceToUse;
public DefaultAuthorizationHandler(
IAServiceToUse aServiceToUse
)
{
_aServiceToUse = aServiceToUse;
}
protected async override Task HandleRequirementAsync(AuthorizationHandlerContext context, DefaultAuthorizationRequirement requirement)
{
/*Here, you can quickly check a data source or Web API or etc.
to know the latest date-time of the user's profile modification...
*/
if (_aServiceToUse.GetDateTimeOfLatestUserProfileModication > requirement.DateTimeOfSetup)
{
context.Fail(); /*Because any modifications to user information,
e.g. if the user used another browser or if by Admin modification,
the claims of the user in this session cannot be guaranteed to be reliable.
*/
return;
}
bool shouldSucceed = false; //This should first be false, because context.Succeed(...) has to only be called if the requirement specifically succeeds.
bool shouldFail = false; /*This should first be false, because context.Fail()
doesn't have to be called if there's no security breach.
*/
// You can do anything.
await doAnythingAsync();
/*You can get the user's claims...
ALSO, note that if you have a way to priorly map users or users with certain claims
to particular policies, add those policies as claims of the user for the sake of ease.
BUT policies that require dynamic code (e.g. checking for age range) would have to be
coded in the switch-case below to determine stuff.
*/
var claims = context.User.Claims;
// You can, of course, get the policy that was hit...
var policy = requirement.Policy
//You can use a switch case to determine what policy to deal with here...
switch (policy)
{
case Enumerations.Security.Policy.CanReadResource:
/*Do stuff with the claims and change the
value of shouldSucceed and/or shouldFail.
*/
break;
case Enumerations.Security.Policy.AnotherPolicy:
/*Do stuff with the claims and change the
value of shouldSucceed and/or shouldFail.
*/
break;
// Other policies too.
default:
throw new NotImplementedException();
}
/* Note that the following conditions are
so because failure and success in a requirement handler
are not mutually exclusive. They demand certainty.
*/
if (shouldFail)
{
context.Fail(); /*Check the docs on this method to
see its implications.
*/
}
if (shouldSucceed)
{
context.Succeed(requirement);
}
}
}
Note that the code above can also enable pre-mapping of a user to a policy in your data store. So, when composing claims for the user, you basically retrieve the policies that had been pre-mapped to the user directly or indirectly (e.g. because the user has a certain claim value and that claim value had been identified and mapped to a policy, such that it provides automatic mapping for users who have that claim value too), and enlist the policies as claims, such that in the authorization handler, you can simply check if the user's claims contain requirement.Policy as a Value of a Claim item in their claims. That is for a static way of satisfying a policy requirement, e.g. "First name" requirement is quite static in nature. So, for the example above (which I had forgotten to give example on Authorize attribute in my earlier updates to this answer), using the policy with Authorize attribute is like as follows, where ViewRecord is an enum member:
[Authorize(Policy = nameof(Enumerations.Security.Policy.ViewRecord))]
A dynamic requirement can be about checking age range, etc. and policies that use such requirements cannot be pre-mapped to users.
An example of dynamic policy claims checking (e.g. to check if a user is above 18 years old) is already at the answer given by #blowdart (https://stackoverflow.com/a/31465227/4974715).
PS: I typed this on my phone. Pardon any typos and lack of formatting.
As of this writing I believe this can be accomplished with the IClaimsTransformation interface in asp.net core 2 and above. I just implemented a proof of concept which is sharable enough to post here.
public class PrivilegesToClaimsTransformer : IClaimsTransformation
{
private readonly IPrivilegeProvider privilegeProvider;
public const string DidItClaim = "http://foo.bar/privileges/resolved";
public PrivilegesToClaimsTransformer(IPrivilegeProvider privilegeProvider)
{
this.privilegeProvider = privilegeProvider;
}
public async Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
{
if (principal.Identity is ClaimsIdentity claimer)
{
if (claimer.HasClaim(DidItClaim, bool.TrueString))
{
return principal;
}
var privileges = await this.privilegeProvider.GetPrivileges( ... );
claimer.AddClaim(new Claim(DidItClaim, bool.TrueString));
foreach (var privilegeAsRole in privileges)
{
claimer.AddClaim(new Claim(ClaimTypes.Role /*"http://schemas.microsoft.com/ws/2008/06/identity/claims/role" */, privilegeAsRole));
}
}
return principal;
}
}
To use this in your Controller just add an appropriate [Authorize(Roles="whatever")] to your methods.
[HttpGet]
[Route("poc")]
[Authorize(Roles = "plugh,blast")]
public JsonResult PocAuthorization()
{
var result = Json(new
{
when = DateTime.UtcNow,
});
result.StatusCode = (int)HttpStatusCode.OK;
return result;
}
In our case every request includes an Authorization header that is a JWT. This is the prototype and I believe we will do something super close to this in our production system next week.
Future voters, consider the date of writing when you vote. As of today, this works on my machine.™ You will probably want more error handling and logging on your implementation.
Just adding to the great answer from #Shawn. If you are using dotnet 5 you need to update the class to be:
public abstract class AttributeAuthorizationHandler<TRequirement, TAttribute> : AuthorizationHandler<TRequirement> where TRequirement : IAuthorizationRequirement where TAttribute : Attribute
{
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, TRequirement requirement)
{
var attributes = new List<TAttribute>();
if (context.Resource is HttpContext httpContext)
{
var endPoint = httpContext.GetEndpoint();
var action = endPoint?.Metadata.GetMetadata<ControllerActionDescriptor>();
if(action != null)
{
attributes.AddRange(GetAttributes(action.ControllerTypeInfo.UnderlyingSystemType));
attributes.AddRange(GetAttributes(action.MethodInfo));
}
}
return HandleRequirementAsync(context, requirement, attributes);
}
protected abstract Task HandleRequirementAsync(AuthorizationHandlerContext context, TRequirement requirement, IEnumerable<TAttribute> attributes);
private static IEnumerable<TAttribute> GetAttributes(MemberInfo memberInfo) => memberInfo.GetCustomAttributes(typeof(TAttribute), false).Cast<TAttribute>();
}
Noting the way getting the ControllerActionDescriptor has changed.
I have bearer token and I can read claims.
I use that attribute on controllers and actions
public class CustomAuthorizationAttribute : ActionFilterAttribute
{
public string[] Claims;
public override void OnActionExecuting(ActionExecutingContext context)
{
// check user
var contextUser = context?.HttpContext?.User;
if (contextUser == null)
{
throw new BusinessException("Forbidden");
}
// check roles
var roles = contextUser.FindAll("http://schemas.microsoft.com/ws/2008/06/identity/claims/role").Select(c => c.Value).ToList();
if (!roles.Any(s => Claims.Contains(s)))
{
throw new BusinessException("Forbidden");
}
base.OnActionExecuting(context);
}
}
example
[CustomAuthorization(Claims = new string[]
{
nameof(AuthorizationRole.HR_ADMIN),
nameof(AuthorizationRole.HR_SETTING)
})]
[Route("api/[controller]")]
[ApiController]
public class SomeAdminController : ControllerBase
{
private readonly IMediator _mediator;
public SomeAdminController(IMediator mediator)
{
_mediator = mediator;
}
[HttpGet("list/SomeList")]
public async Task<IActionResult> SomeList()
=> Ok(await _mediator.Send(new SomeListQuery()));
}
That is Roles
public struct AuthorizationRole
{
public static string HR_ADMIN;
public static string HR_SETTING;
}
Here's a simple 5-step guide for how to implement custom role authorization using policies for all you copy and pasters out there :) . I used these docs.
Create a requirement:
public class RoleRequirement : IAuthorizationRequirement
{
public string Role { get; set; }
}
Create a handler:
public class RoleHandler : AuthorizationHandler<RoleRequirement>
{
protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, RoleRequirement requirement)
{
var requiredRole = requirement.Role;
//custom auth logic
// you can use context to access authenticated user,
// you can use dependecy injection to call custom services
var hasRole = true;
if (hasRole)
{
context.Succeed(requirement);
}
else
{
context.Fail(new AuthorizationFailureReason(this, $"Role {requirement.Role} missing"));
}
}
}
Add the handler in Program.cs:
builder.Services.AddSingleton<IAuthorizationHandler, RoleHandler>();
Add a policy with your role requirement in program.cs:
builder.Services.AddAuthorization(options =>
{
options.AddPolicy("Read", policy => policy.Requirements.Add(new RoleRequirement{Role = "ReadAccess_Custom_System"}));
});
Use your policy:
[Authorize("Read")]
public class ExampleController : ControllerBase
{
}
A lot of people here already told this, but with Policy handlers you can come really far in terms of what you could achieve with the old way in .NET Framework.
I followed a quick writeup from this answer on SO: https://stackoverflow.com/a/61963465/7081176
For me it works flawlessly after making some classes:
The EditUserRequirement:
public class EditUserRequirement : IAuthorizationRequirement
{
public EditUserRequirement()
{
}
}
An abstract handler to make my life easier:
public abstract class AbstractRequirementHandler<T> : IAuthorizationHandler
where T : IAuthorizationRequirement
{
public async Task HandleAsync(AuthorizationHandlerContext context)
{
var pendingRequirements = context.PendingRequirements.ToList();
foreach (var requirement in pendingRequirements)
{
if (requirement is T typedRequirement)
{
await HandleRequirementAsync(context, typedRequirement);
}
}
}
protected abstract Task HandleRequirementAsync(AuthorizationHandlerContext context, T requirement);
}
An implementation of the abstract handler:
public class EditUserRequirementHandler : AbstractRequirementHandler<EditUserRequirement>
{
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, EditUserRequirement requirement)
{
// If the user is owner of the resource, allow it.
if (IsOwner(context.User, g))
{
context.Succeed(requirement);
}
return Task.CompletedTask;
}
private static bool IsOwner(ClaimsPrincipal user, Guid userIdentifier)
{
return user.GetUserIdentifier() == userIdentifier;
}
}
Registering my handler and requirement:
services.AddSingleton<IAuthorizationHandler, EditUserRequirementHandler>();
services.AddAuthorization(options =>
{
options.AddPolicy(Policies.Policies.EditUser, policy =>
{
policy.Requirements.Add(new EditUserRequirement());
});
});
And then using my Policy in Blazor:
<AuthorizeView Policy="#Policies.EditUser" Resource="#id">
<NotAuthorized>
<Unauthorized />
</NotAuthorized>
<Authorized Context="Auth">
...
</Authorized>
</AuthorizeView>
I hope this is useful for anyone facing this issue.
I have been looking into solving a very similar issue, and settled on creating a custom ActionFilterAttribute (I'm going to call it AuthorizationFilterAttribute) instead of an AuthorizeAttribute to implement the guidance here: https://learn.microsoft.com/en-us/aspnet/core/security/authorization/resourcebased?view=aspnetcore-6.0#challenge-and-forbid-with-an-operational-resource-handler.
For authorization in our app. We had to call a service based on the parameters passed in authorization attribute.
For example, if we want to check if logged in doctor can view patient appointments we will pass "View_Appointment" to custom authorize attribute and check that right in DB service and based on results we will athorize. Here is the code for this scenario:
public class PatientAuthorizeAttribute : TypeFilterAttribute
{
public PatientAuthorizeAttribute(params PatientAccessRights[] right) : base(typeof(AuthFilter)) //PatientAccessRights is an enum
{
Arguments = new object[] { right };
}
private class AuthFilter : IActionFilter
{
PatientAccessRights[] right;
IAuthService authService;
public AuthFilter(IAuthService authService, PatientAccessRights[] right)
{
this.right = right;
this.authService = authService;
}
public void OnActionExecuted(ActionExecutedContext context)
{
}
public void OnActionExecuting(ActionExecutingContext context)
{
var allparameters = context.ActionArguments.Values;
if (allparameters.Count() == 1)
{
var param = allparameters.First();
if (typeof(IPatientRequest).IsAssignableFrom(param.GetType()))
{
IPatientRequest patientRequestInfo = (IPatientRequest)param;
PatientAccessRequest userAccessRequest = new PatientAccessRequest();
userAccessRequest.Rights = right;
userAccessRequest.MemberID = patientRequestInfo.PatientID;
var result = authService.CheckUserPatientAccess(userAccessRequest).Result; //this calls DB service to check from DB
if (result.Status == ReturnType.Failure)
{
//TODO: return apirepsonse
context.Result = new StatusCodeResult((int)System.Net.HttpStatusCode.Forbidden);
}
}
else
{
throw new AppSystemException("PatientAuthorizeAttribute not supported");
}
}
else
{
throw new AppSystemException("PatientAuthorizeAttribute not supported");
}
}
}
}
And on API action we use it like this:
[PatientAuthorize(PatientAccessRights.PATIENT_VIEW_APPOINTMENTS)] //this is enum, we can pass multiple
[HttpPost]
public SomeReturnType ViewAppointments()
{
}

Get the UserManager instance outside of ASP.NET web application?

I have an ASP.NET MVC 5 web app with ASP.NET Identity (Individual Accounts). But I need to be able to register new users from a console app.
So I'm moving some of the ASP.NET Identity classes from the web app into a class library to be shared between the web app and the CLI.
I have successfully moved the following:
public class PortalDbContext : IdentityDbContext<PortalUser>
{
public PortalDbContext(string connectionString)
: base(connectionString, throwIfV1Schema: false)
{
}
public static PortalDbContext Create(string connectionString)
{
return new PortalDbContext(connectionString);
}
}
public class PortalUser : IdentityUser
{
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<PortalUser> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
}
public class PortalUserManager : UserManager<PortalUser>
{
public PortalUserManager(IUserStore<PortalUser> store) : base(store)
{
}
public async Task<IdentityResult> RegisterUser(string email, string password)
{
PortalUser user = new PortalUser { UserName = email, Email = email };
return await this.CreateAsync(user, password);
}
}
But I have no idea where to get the IUserStore<PortalUser> the PortalUserManager needs from.
In the web app, this manager is retrieved from HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>() which I clearly can't use in a class library.
Take a look at the OwinRequestScopeContext nuget package. It allows you to make use of a context without a dependency on System.Web. I'll add the example from the current readme for the sake of not having a link-only answer:
# Usage
// using Owin; you can use UseRequestScopeContext extension method.
// enabled timing is according to Pipeline.
// so I recommend enable as far in advance as possible.
app.UseRequestScopeContext();
app.UseErrorPage();
app.Run(async _ =>
{
// get global context like HttpContext.Current.
var context = OwinRequestScopeContext.Current;
// Environment is raw Owin Environment as IDictionary<string, object>.
var __ = context.Environment;
// optional:If you want to change Microsoft.Owin.OwinContext, you can wrap.
new Microsoft.Owin.OwinContext(context.Environment);
// Timestamp is request started(correctly called RequestScopeContextMiddleware timing).
var ___ = context.Timestamp;
// Items is IDictionary<string, object> like HttpContext.Items.
// Items is threadsafe(as ConcurrentDictionary) by default.
var ____ = context.Items;
// DisposeOnPipelineCompleted can register dispose when request completed(correctly RequestScopeContextMiddleware underling Middlewares finished)
// return value is cancelToken. If call token.Dispose() then canceled register.
var cancelToken = context.DisposeOnPipelineCompleted(new TraceDisposable());
// OwinRequestScopeContext over async/await also ConfigureAwait(false)
context.Items["test"] = "foo";
await Task.Delay(TimeSpan.FromSeconds(1)).ConfigureAwait(false);
var _____ = OwinRequestScopeContext.Current.Items["test"]; // foo
await Task.Run(() =>
{
// OwinRequestScopeContext over new thread/threadpool.
var ______ = OwinRequestScopeContext.Current.Items["test"]; // foo
});
_.Response.ContentType = "text/plain";
await _.Response.WriteAsync("Hello OwinRequestScopeContext! => ");
await _.Response.WriteAsync(OwinRequestScopeContext.Current.Items["test"] as string); // render foo
});
I've ended up adding a static method Create(string connectionString) to PortalUserManager that will create the UserStore and DbContext and return a new instance of the manager.
public class PortalDbContext : IdentityDbContext<PortalUser>
{
public PortalDbContext(string connectionString)
: base(connectionString, throwIfV1Schema: false)
{
}
public static PortalDbContext Create(string connectionString)
{
return new PortalDbContext(connectionString);
}
}
public class PortalUser : IdentityUser
{
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<PortalUser> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
}
public class PortalUserManager : UserManager<PortalUser>
{
public PortalUserManager(IUserStore<PortalUser> store) : base(store)
{
}
public static PortalUserManager Create(string connectionString)
{
UserStore<PortalUser> userStore = new UserStore<PortalUser>(PortalDbContext.Create(connectionString));
PortalUserManager manager = new PortalUserManager(userStore);
// Configure validation logic for usernames
manager.UserValidator = new UserValidator<PortalUser>(manager)
{
AllowOnlyAlphanumericUserNames = true,
RequireUniqueEmail = true
};
// Configure validation logic for passwords
manager.PasswordValidator = new PasswordValidator
{
RequiredLength = 6,
RequireNonLetterOrDigit = true,
RequireDigit = true,
RequireLowercase = true,
RequireUppercase = true,
};
return manager;
}
public async Task<IdentityResult> RegisterUser(string email, string password)
{
PortalUser user = new PortalUser { UserName = email, Email = email };
return await this.CreateAsync(user, password);
}
}

How do I access role objects from HttpContext, or more specifically from a custom authorize attribute?

Background
I would like to authorize an ApplicationUser based on their ApplicationRoles' RoleClaims. I would like to implement this like so:
public class RoleClaimAuthorizeAttribute : AuthorizeAttribute
{
public RoleClaim RoleClaim { get; set; }
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
foreach (ApplicationRole role in Roles)
{
if ((RoleClaim & role.Claims) > 0)
{
return true;
}
}
return false;
}
}
Then I could decorate controller actions like so:
[RoleClaimAuthorize(RoleClaim =
RoleClaim.CanCreateRoles |
RoleClaim.CanReadRoles |
RoleClaim.CanDeleteRoles |
RoleClaim.CanUpdateRoles
)]
//
// GET: /Roles/
public ActionResult Index()
{
return View(_roleManager.Roles);
}
Question
The problem I'm encountering is any method I can find of reaching an ApplicationUser's ApplicationRoles from my custom authorize attribute returns a string array of ApplicationRole.Name not an array of ApplicationRole so I can't get to ApplicationRole.Claims. I'm also using Unity instead of Owin to handle ApplicationRoleManager so I can't request ApplicationRoleManager via HttpContext.Current.GetOwinContext().Get<ApplicationRoleManager>().
So how can I get to a collection of ApplicationRole objects for the current user and thus ApplicationRole.Claims?
Or if it's a more appropriate solution, how can I store a string array of the current ApplicationUser's ApplicationRoles' RoleClaims in HttpContext much like how roles are stored? I'm aware my authorization attribute couldn't work as described in this situation but it's a situation I can work with nonetheless.
Relevant Classes
ApplicationUser
// You can add profile data for the user by adding more properties to your ApplicationUser class, please visit http://go.microsoft.com/fwlink/?LinkID=317594 to learn more.
public class ApplicationUser : IdentityUser<Guid, ApplicationUserLogin, ApplicationUserRole, ApplicationUserClaim>
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public override Guid Id { get; set; }
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser, Guid> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser, Guid> manager, string authenticationType)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, authenticationType);
// Add custom user claims here
return userIdentity;
}
}
ApplicationRole
public class ApplicationRole : IdentityRole<Guid, ApplicationUserRole>
{
public ApplicationRole() : base()
{
this.Id = Guid.NewGuid();
}
public ApplicationRole(string name)
: this()
{
this.Name = name;
}
public ApplicationRole(string name, params string[] claims)
: this(name)
{
Claims = (RoleClaim)Enum.Parse(typeof(RoleClaim), String.Join(",", claims));
}
public RoleClaim Claims { get; set; }
}
RoleClaim
[Flags]
public enum RoleClaim : int
{
CanCreateUsers = 1,
CanReadUsers = 2,
CanUpdateUsers = 4,
CanDeleteUsers = 8,
CanCreateRoles = 16,
CanReadRoles = 32,
CanUpdateRoles = 64,
CanDeleteRoles = 128,
CanCreateTests = 256,
CanReadTests = 512,
CanUpdateTests = 1024,
CanDeleteTests = 2048
}
ApplicationRoleManager
public class ApplicationRoleManager : RoleManager<ApplicationRole, Guid>
{
public ApplicationRoleManager(IRoleStore<ApplicationRole, Guid> store) : base(store)
{
}
}
If you registered the role manager in Unity you could retrieve everywhere, including your custom attribute, simply by calling following method:
var roleManager = DependencyResolver.Current.GetService<ApplicationRoleManager>();
Or if you don't want to use the resolver directly you could use Unity's property injection feature so Unity automatically injects the role manager in the custom attribute which in explained here. Then call roleManager.FindByNameAsync() method to retrieve the role object.
But this approach is not recommended because in each call your code hits the database to retrieve claims. It is much better to store user's claims in ClaimsIdentity when user signs in then retrieve them within the attribute like this:
public class ApplicationSignInManager : SignInManager<ApplicationUser, string>
{
private readonly ApplicationRoleManager _roleManager;
public ApplicationSignInManager(ApplicationUserManager userManager,
IAuthenticationManager authenticationManager,
ApplicationRoleManager rolemanager)
: base(userManager, authenticationManager)
{
//inject the role manager to the sign in manager
_roleManager=rolemanager;
}
public override async Task<ClaimsIdentity> CreateUserIdentityAsync(ApplicationUser user)
{
var ident= await user.GenerateUserIdentityAsync((ApplicationUserManager)UserManager);
// add your custom claims here
var userRoles=user.Roles.Select(r=>r.RoleId);
ident.AddClaims(_roleManager.Roles.Where(r => userRoles.Any(ur => ur == r.Id))
.Select(r=>r.Claims).ToList()
.Select(c => new Claim("RoleClaims", c.ToString())));
return ident;
}
}
Now RoleClaims are added as claims when user signs in. You could retrieve them in the attribute like this:
public class RoleClaimAuthorizeAttribute : AuthorizeAttribute
{
public RoleClaim RoleClaim { get; set; }
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
foreach (var claims in GetClaims(httpContext.User.Identity as ClaimsIdentity))
{
if ((RoleClaim & claims) > 0)
{
return true;
}
}
return false;
}
private IEnumerable<RoleClaim> GetClaims(ClaimsIdentity ident)
{
return ident==null
? Enumerable.Empty<RoleClaim>()
: ident.Claims.Where(c=>c.Type=="RoleClaims")
.Select(c=>(RoleClaim)Enum.Parse(typeof(RoleClaim), c.Value));
}
}

Categories

Resources