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?
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.