0

I am trying to write a custom attribute that can validate if a user is authorized for certain controller or not. Found this link ASP.NET MVC 4 Custom Authorize Attribute with Permission Codes (without roles) here on Stackoverflow. My problem is I am not able to use User.Identity.GetUserIdto write any kind of query . It throw error that "Error 1 The name 'User' does not exist in the current context". Adding using Microsoft.AspNet.Identity; also did not helped. I basically want to do check if certain AccessLevel is valid for logged in user or not. For this later I was planning to go to database and query for logged in user. I am learning this so please advise if I am doing this totally wrong.

Below is the code I am starting with.

Thanks.

    public class UserAuthorizeAttributes : AuthorizeAttribute
    {
        public string AccessLevel { get; set; }

        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {         
            // Check if valid credentials  are there for selected User.Identity.GetUserId() in database
            { return true ; }
            else
            { return false; }

        }
        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
        filterContext.Result = new RedirectResult("/TimeShare/Account/LogOn");

        base.HandleUnauthorizedRequest(filterContext);
        }
    }

So I was planning to use in controllers as below

[UserAuthorizeAttributes(AccessLevel ="UserAdmin")] 
public class XXXXController : Controller {
 }
Community
  • 1
  • 1
ary
  • 829
  • 1
  • 11
  • 30
  • 3
    So just found out that `httpContext.User.Identity.GetUserId();` gives me ID. Not sure if this is the right way to go. – ary May 04 '15 at 20:39
  • 1
    There is a roles based attribute you can use for roles like UserAdmin. May be easier since there is no code you have to manage. – Jacob Roberts May 04 '15 at 21:33
  • I actually have to write custom that is on top of role based. This is the reason just role is based i not enough. Thanks. – ary May 05 '15 at 10:58
  • You are right with pulling the user ID from the httpContext. This is the way that your controllers are doing it behind the scenes. – Jacob Roberts May 05 '15 at 12:54
  • Thanks Jacob. But my question is why is `User.Identity.GetUserId` not working? – ary May 06 '15 at 14:56
  • Because there is no `User` in this context. You could create it yourself like `var User = httpContext.User;` but either way, it is one in the same, just accessed differently. – Jacob Roberts May 06 '15 at 15:22

0 Answers0