One
of the most important (and common) aspect of application security is
to allow access to certain sections of application only to specific
users (or groups). It can be achieved only after users are
authenticated. In the world of ASP.NET MVC these sections are
identified by action methods and controllers rather than actual URLs.
To
allow only authenticated users to access certain section of the
application we need to specify those sections with [Authorize]
attribute. We can make a single action method or a controller
accessible for only authenticated users. If we added the [Authorize]
attribute to controller then all action methods of the controller
will be accessible only to authenticated users. However, we can allow
certain action methods to not require authentication by decorating
them with the [AllowAnonymous] attribute. After the controllers and
the action methods are set to require users to be authenticated to
access them. The
framework
will redirect requests made by anonymous users (users who have not
yet entered authentication information) to the login page. After user
authentication, the MVC framework will redirect them back to the
original destination. It is done using a parameter in URL named
ReturnUrl which instructs the login page where to go after user
authentication.
To
achieve this functionality, we are going to create two controllers:
MembersController and AdminController. These controllers will be used
for the members section and the administration section of our web
site. It will be accessible only for authenticated users. We will use
steps to create a controller and we will decorate the controllers
with the [Authorize] attribute as shown in Figure 1 and 2.
Figure 1.
MembersController Class
Figure
2. AdminController
Class
We
need to add a view for action methods for each of the controllers. Do
not worry for content of the view,
just create the view. If we make a request to those controllers
(Members)
then ASP.NET MVC automatically redirects us to the login page as
shown in Figure 3.
Figure
3. A secured action method redirection
to login page
In
Figure 3, the
actual destination URL is defined in ReturnUrl
parameter in query string. If the user
enters a valid user name and password on login page then ASP.NET MVC
will automatically redirect the user to the intended URL (as
specified in ReturnUrl query
string parameter).
We
can allow certain action methods in a secured controller to make
accessible for all users, not just authenticated ones. For
this purpose, we use the [AllowAnonymous] attribute in action method.
For example, the Login() action method in the Account controller (in
Controllers/AccountController.cs file) it is defined this way, as
shown in Figure 4.
Figure 4.
Partial Listing of the Account Controller Class
No comments:
Post a Comment