Saturday, 22 December 2018

Authenticating Users with Forms Authentication / Role Based Authentication / User Based Authentication

You can use [Authorize] attribute on Controller level or Action Method level to apply forms authentication. When it is applied on Controller level the entire Controller Class is restricted to anonymous users. When it is invoked it will prompt and ask you to validate by providing valid user and password.

When [Authorize] is applied at Action Method level, that method which is decorated with [Authorize] will be restricted to anonymous users and will prompt to enter valid user and password.

You can restrict the forms authentication user level and role level as well. Create some users and their roles.

Apply [Authorize(Users="AG Kumar")] attribute in Action Method. It will allow only the user “AG Kumar” to access that Action Method. Other users are not allowed to access this.

Apply [Authorize(Roles = "Administrators")] attribute in Action Method. It will allow those users who have “Administrators” role. Other roles are not allowed to access.

You can apply all the above on Controller Level or Action Method Level

Example:
namespace MyMvcApplication
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
 
        [Authorize]
        public ActionResult CompanySecrets()
        {
            return View();
        }
 
        [Authorize(Users="AG Kumar")]
        public ActionResult StephenSecrets()
        {
            return View();
        }
 
        [Authorize(Roles = "Administrators")]
        public ActionResult AdministratorSecrets()
        {
            return View();
        }
 
    }

}

No comments:

Post a Comment