2

I'm working on a MVC project. I want to use custom authorization attribute. First of all I used an example in this blog post.

public class CustomAuthorizeAttribute : AuthorizeAttribute
{
    public string RolesConfigKey { get; set; }

    protected virtual CustomPrincipal CurrentUser => HttpContext.Current.User as CustomPrincipal;

    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        if (!filterContext.HttpContext.Request.IsAuthenticated) return;
        var authorizedRoles = ConfigurationManager.AppSettings["RolesConfigKey"];

        Roles = string.IsNullOrEmpty(Roles) ? authorizedRoles : Roles;

        if (string.IsNullOrEmpty(Roles)) return;
        if (CurrentUser == null) return;
        if (!CurrentUser.IsInRole(Roles)) base.OnAuthorization(filterContext);
    }

    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        if (!filterContext.HttpContext.Request.IsAuthenticated) return;
    }
}

I use this custom principal in my base controller.

public class CustomPrincipal : IPrincipal
{
    public CustomPrincipal(string userName) { this.Identity = new GenericIdentity(userName); }

    public bool IsInRole(string userRoles)
    {
        var result = true;
        var userRolesArr = userRoles.Split(',');
        foreach (var r in Roles)
        {
            if (userRolesArr.Contains(r)) continue;
            result = false;
            break;
        }
        return result;
    }

    public IIdentity Identity { get; }
    public string UserId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string[] Roles { get; set; }
} 

In my routeconfig my default route is /Account/Index where users login operations in. And this is account controllers Index action.

    [HttpPost, ValidateAntiForgeryToken]
    public ActionResult Index(AccountViewModel accountModel)
    {
        var returnUrl = string.Empty;

        if (!ModelState.IsValid) { return UnsuccessfulLoginResult(accountModel.UserName, ErrorMessages.WrongAccountInfo); }

        var account = _accountService.CheckUser(accountModel.UserName, accountModel.Password);
        if (account == null) return UnsuccessfulLoginResult(accountModel.UserName, ErrorMessages.WrongAccountInfo);

        var roles = account.Roles.Select(r => r.RoleName).ToArray();
        var principalModel = new CustomPrincipalModel
        {
            UserId = account.UserId,
            FirstName = "FirstName",
            LastName = "LastName",
            Roles = roles
        };

        var userData = JsonConvert.SerializeObject(principalModel);
        var ticket = new FormsAuthenticationTicket(1, account.UserId, DateTime.Now, DateTime.Now.AddMinutes(30), false, userData);
        var encryptedTicket = FormsAuthentication.Encrypt(ticket);
        var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
        Response.Cookies.Add(cookie);

        SetCulture(account.DefaultCulture);

        if (!Array.Exists(roles, role => role == "admin" || role == "user")) return UnsuccessfulLoginResult(accountModel.UserName, ErrorMessages.WrongAccountInfo);

        if (roles.Contains("admin")) { returnUrl = Url.Action("Index", "Admin"); }
        if (roles.Contains("user")) { returnUrl = Url.Action("Index", "Upload"); }

        return SuccessfulLoginResult(accountModel.UserName, returnUrl);
    } 

As you can see when user is in admin role this action redirects user /Admin/Index otherwise /Upload/Index. But after I logged in a user has user role and typed /Admin/Index , authorization filters not working and user can access admin page.

Although I have added to UploadController and AdminController this attribute this error is occuring. How can I fix this ?

[CustomAuthorize(Roles = "user")]
public class UploadController : BaseController

[CustomAuthorize(Roles = "admin")]
public class AdminController : BaseController

2 Answers2

1

You need to add claims for your user, add this part to your method:

. . .    

var roles = account.Roles.Select(r => r.RoleName).ToArray();

ClaimsIdentity identity = new ClaimsIdentity(DefaultAuthenticationTypes.ApplicationCookie);

identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, accountModel.UserName));

roles.ToList().ForEach((role) => identity.AddClaim(new Claim(ClaimTypes.Role, role)));

identity.AddClaim(new Claim(ClaimTypes.Name, userCode.ToString()));

. . . 
SᴇM
  • 7,024
  • 3
  • 24
  • 41
0

Problem solved with these changes.

In my CustomAuthorizeAttribute changed this line

if (!filterContext.HttpContext.Request.IsAuthenticated) return;

to

if (!filterContext.HttpContext.Request.IsAuthenticated) base.OnAuthorization(filterContext);

And removed lines that I read allowed roles from web config. So my attributes final version like below

public class CustomAuthorizeAttribute : AuthorizeAttribute
{
    protected virtual CustomPrincipal CurrentUser => HttpContext.Current.User as CustomPrincipal;

    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        if (!filterContext.HttpContext.Request.IsAuthenticated) base.OnAuthorization(filterContext);

        if (string.IsNullOrEmpty(Roles)) return;
        if (CurrentUser == null) return;
        if (!CurrentUser.IsInRole(Roles)) filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "Error", action = "AccessDenied" })); 
    }
}

Then I added a controller named ErrorController and redirected to this page when user not in role.

With these changes I realized that I was unable to access my /Account/Index and added [AllowAnonymous] attribute to actions below.

    [AllowAnonymous]
    public ActionResult Index() { return View(); }

    [HttpPost, ValidateAntiForgeryToken, AllowAnonymous]
    public ActionResult Index(AccountViewModel accountModel)