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.GetUserId
to 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 {
}