Michel Andrade
Michel Andrade

Reputation: 4196

ASP.NET MVC 3 AuthorizeAttribute

I am developing a project using ASP.NET MVC 3, now use a MembershipProvider, RoleProvider AuthorizeAttribute and custom. So in certain parts of the code use this:

[Logon(Roles = "login, test1")]

This code works perfectly, for use in the MembershipProvider code:

public override string [] GetRolesForUser (string username)
{
    var = UsuarioRepository.GetListaPermissoesByUsuarioEmail permissions (username);

    if (permissions == null)
    {
        nullPermissao var = new string [0];
        nullPermissao return;
    }

    return permissions;
}

My question is. how can I use the following code, which method will need to customize? I want to check is determined whether a particular type of user who is logged in and if it has certain privileges.

[Logon(Roles = "login, test1," Users = "User1")]

Using override string [] GetRolesForUser (string username) method it checks the Roles, in wich method I can check the User?

Upvotes: 0

Views: 639

Answers (2)

marc.d
marc.d

Reputation: 3844

This should work out of the box with the AuthorizeAttribute. It checks if HttpContext.User.Identity.Name matches any of the terms you defined under AuthorizeAttribute.Users

As i see from the comments, you rolled your own LogonAttribute where your probably overwrote the OnAuthorize method. This is where the AuthorizeAtrribute does it`s magic.

Original ASP.NET MVC Source

protected virtual bool AuthorizeCore(HttpContextBase httpContext)
{
  if (httpContext == null)
    throw new ArgumentNullException("httpContext");
  IPrincipal user = httpContext.User;
  return user.Identity.IsAuthenticated && (this._usersSplit.Length <= 0 || Enumerable.Contains<string>((IEnumerable<string>) this._usersSplit, user.Identity.Name, (IEqualityComparer<string>) StringComparer.OrdinalIgnoreCase)) && (this._rolesSplit.Length <= 0 || Enumerable.Any<string>((IEnumerable<string>) this._rolesSplit, new Func<string, bool>(user.IsInRole)));
}

public virtual void OnAuthorization(AuthorizationContext filterContext)
{
  if (filterContext == null)
    throw new ArgumentNullException("filterContext");
  if (OutputCacheAttribute.IsChildActionCacheActive((ControllerContext) filterContext))
    throw new InvalidOperationException(MvcResources.AuthorizeAttribute_CannotUseWithinChildActionCache);
  if (this.AuthorizeCore(filterContext.HttpContext))
  {
    HttpCachePolicyBase cache = filterContext.HttpContext.Response.Cache;
    cache.SetProxyMaxAge(new TimeSpan(0L));
    cache.AddValidationCallback(new HttpCacheValidateHandler(this.CacheValidateHandler), (object) null);
  }
  else
    this.HandleUnauthorizedRequest(filterContext);
}

Upvotes: 1

Chris Snowden
Chris Snowden

Reputation: 5002

Did you mean to use the following?

[Authorize(Roles = "login, test1", Users = "User1")]

Upvotes: 0

Related Questions