Whereas your project uses at least Membership
or ASP.NET Identity
, write down on top of each View the following attribute:
[Authorize(Roles = "Administrador, Professor, Coordenador")]
public ActionResult MinhaAction() { ... }
To authorize any user on Role
, use the following command somewhere in your code:
Roles.AddUserToRole("LoginDoUsuario", "Administrador");
To check in your code if the user belongs to any 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 verify the Roles
of the current user:
@Roles.GetRolesForUser()
Or a specific user:
@Roles.GetRolesForUser("LoginDoUsuario")
By the way, you can use the attribute without specifying Role
only to verify that the user is logged in:
[Authorize]
public ActionResult MinhaAction() { ... }
If no authentication scheme is specified, your application will use the SimpleMembership
if it is MVC4 or ASP.NET Identity
with Basic Authentication if it’s MVC5.
As stated, it is possible to customize the authentication scheme by reimplementing some classes. In any case, this part would already serve for another question.
Very good your answer. But I’m using Forms Authentication ! And that way, if a teacher tries to access an area that he can’t, the system rejects his identity and logs off. But what I really wanted is, for example, a Teacher, can not add or delete or even edit the student data, can only view and detail the data. So in this case, how do I hide the edit, add, and remove links in the Index view ?
– Érik Thiago
Using this answer line:
if (User.IsInRole("Administrador")) { ... }
.– Leonel Sanches da Silva
Directly in View ?
– Érik Thiago
Yes, it can be at View, including, with the
@
in front.– Leonel Sanches da Silva
Ahh understood. And in if I would leave blank like that ? Or have some check to do there ? Could put more than one profile on that line there ?
– Érik Thiago
It’s another function. I’ll put in the answer.
– Leonel Sanches da Silva
Gypsy, did not work, I put the if, and the option does not appear for any profile...
– Érik Thiago
I think it is again the case to open another question, this time detailing what was done in the solution. Then I can suggest what to do.
– Leonel Sanches da Silva