Reputation: 23
I have a separate database filled with employees, each with a unique email address. The website I am creating, employees can register an account and if they have a matching email address I would like them to see their contact information and edit it if possible.
Here is the following code I was able to use to achieve this.
[AllowAnonymous]
// GET: Contacts/Details/
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Contact contact = db.Contacts.Find(id);
if(User.IsInRole("Admin")||(User.Identity.GetUserName()==contact.Email))
{
return View(contact);
}
if (contact == null)
{
return HttpNotFound();
}
return RedirectToAction("AccessDenied","Error");
}
Ideally I would like to remove [AllowAnonymous]
and have something like
[Authorize(Roles="Admin",Users=User.Identity.GetUserName())]
but this pulls up an error:
"User.Identity.GetUserName() an object reference is required".
Any suggesions?
Upvotes: 1
Views: 151
Reputation: 4339
You can create a new attribute class, which should inherit from Authorise attribute class. You can pass your desired parameter in the new attribute class and play accordingly by overriding OnAuthorization method.
Upvotes: 1
Reputation: 106
Authorize Attribute constructor takes only Constant values, you cant use it dynamically for each user. if you want your specific type of users can only have access to this method, create a role for them and use it instead.
[Authorize(Roles="Admin,SpecialUsers")]
Upvotes: 0