ASP.NET MVC Identity: How To Increase AspNetUserRoles Table

In ASP.NET MVC Identity, the relationship data for users and roles is stored in the AspNetUserRoles table, this table has two fields: UserId, RoleId, but I want to add other fields to this table like department field.

Therefore, if a user belongs to different departments, they will have different roles. Does anyone know how to do this? Thanks in advance!

+3


source to share


1 answer


I would suggest that you investigate the claims of ASPNet users. You can assign different claims to a user with an identity manager and based on the type of user claim that you allow him to access or not. Create your own claims attribute to be placed on top of another controller for user authentication. this should be implemented based on your needs. the custom attribute will run before the controller is executed, and if allowed, it will pass. else go back to the error page of your choice.

An example of using the attribute

[ClaimsAuthorize(ClaimsData.EditAddress)]
    public ActionResult CitiesPartial()

      



Attribute Authentication

 public class ClaimsAuthorizeAttribute : AuthorizeAttribute
{
    private readonly string _claimType;
    public ClaimsAuthorizeAttribute(string type)
    {
        _claimType = type;
    }
    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        var user = (ClaimsPrincipal)HttpContext.Current.User;

        if (user.HasClaim(_claimType, "True"))
        {
            base.OnAuthorization(filterContext);
        }
        else
        {
            HandleUnauthorizedRequest(filterContext, _claimType + " Not Allowed ");
        }
    }

    protected void HandleUnauthorizedRequest(AuthorizationContext filterContext, string message)
    {
        filterContext.Result = new RedirectToRouteResult(
                                   new RouteValueDictionary 
                               {
                                   { "action", "ClaimNotAuthorized" },
                                   { "controller", "Home" },
                                   {"errorMessage", message }
                               });
    }

    public static bool AuthorizedFor(string claimType)
    {
        var user = (ClaimsPrincipal)HttpContext.Current.User;
        return user.HasClaim(claimType, "True");
    }
}

      

hope this helps.

+2


source







All Articles