Considering that your project uses at least Membership
or ASP.NET Identity
, note the following attribute on top of each View:
[Authorize(Roles = "Administrador, Professor, Coordenador")]
public ActionResult MinhaAction() { ... }
To authorize some users in Role
, use the following command in some part of your code:
Roles.AddUserToRole("LoginDoUsuario", "Administrador");
To check your code if the user belongs to some Role
, use:
if (User.IsInRole("Administrador")) { ... }
To remove the user from a Role
, use:
Roles.RemoveUserFromRole("LoginDoUsuario", "Administrador");
For Views, the principle is the same:
@if (User.IsInRole("Administrador")) { ... }
To check the Roles
of the current user:
@Roles.GetRolesForUser()
Or from a specific user:
@Roles.GetRolesForUser("LoginDoUsuario")
Incidentally, you can use the attribute without specifying Role
only to check if the user is logged in:
[Authorize]
public ActionResult MinhaAction() { ... }
If no authentication scheme is specified, your application will use SimpleMembership
if it is MVC4 or ASP.NET Identity
with Basic Authentication if it is MVC5.
As stated, you can customize the authentication scheme by reimplementing some classes. In any case, this part would already serve another question.