I am developing ASP.Net MVC application. I have a login form for Admins. When an Admin logged in, it is redirected to home page.
Now when I click on Employee menu, it redirects to Employee/Index. In the Index method, I am checking whether Admin is logged in. I have to check in every method of Employee controller for admin login.
Is there any way to check for the admin login for all the admin area. Here admin can create, update, delete Employees, Store etc. So is there any way to check adminlogin just once instead all the method of Index, Create, Delete, Edit?
Anything like
// Controller of EmployeeController public EmployeeController() { if (Session["Admin"] == null) { // return to AdminLogin } } Because when I enter url in browser - localhost:9999/Admin/Employee/Create, it is redirected to Create page, without login. I don't want to check in all methods of a controller.
2 Answers
You need to apply Autorize attribute on the action methods or controller class you need and check for admin role like this:
[Authorize(Roles = "Admin")] There is detailed discussion on that question in asp.net mvc and check for if a user is logged in.
To avoid typos especially in case of using Authorize I will recommend having a static class for the Roles
public static class Roles { public const string Admin = "Admin"; } Then when decorating you can do this;
[Authorize(Roles = Roles.Admin)] Because you don't want retyping "Admin" everytime which could lead to a bug in your code when you make typo.