You are on page 1of 8

ASP.

NET MVC 6 Security and Role management

The following diagram gives an idea of Authentication when the end-user makes a call to
an MVC 6 application.

When the end-user makes a call to an MVC 6 application requesting a View, a response
in the form of a View is returned when the action is executed. However if the Controller or
the Action is applied with the [Authorize] filter , then the request processing on the
server sends the Login Page response to the client. Once the end-user sends the
request with credentials, the Authentication Filter is executed which is responsible for
validating Credentials against the Database server where the application users are
stored. If the credentials are validated, then the Users will be Logged In and response of
the View will be sent back to the user.
• Filters in mvc
What are the filters:

Sometimes we would like to perform certain action before or after a particular operation,
or sometimes we need a pre or post action behaviors from action, for achieving this
functionality ASP.NET MVC provides a feature called Filters.

Types of filters:

ASP.NET MVC supports following types of filters:

1. Action Filters
2. Authorization Filters
3. authentication Filters
4. Result Filters
5. Exception Filters

Action filters are used to implement the logic that get executed before or after a
controller action executes.

Authorization Filters:

It is used to implement authorization and authentication for action filters

Result Filters:

Result filters contains logic that gets executed before or after a view result gets
executed. E.g. if you want to change view before its get render to browser.

Exception Filters:

Exception filters are used to handle error, caused by either controller action or
controller action results, we can also use it for logging the exceptions.

Let's gives some Action Filter in ASP.NET MVC:

Action Filters can be applied to either controller action or controller itself, with the
help of action filter we can change the way, the action or controller gets executed.

MVC provides following action filters:


• Output Cache:

This filter caches the output of action for certain duration. E.g. below code
snippet, we are decorating login action with output cache keyword, that will
cache the output of login action for 20 seconds( we have given 20 seconds
duration).

• Handle Error:

It handles the error caused by action or controller, if any exception occurs it


redirects the action to custom error page. e.g: here in the below code snippet
handle error attribute is decorated to login action method, it will redirect to a
view called "error.cshtml" when any exception will occur by this action
method.

Authorize:
It is used for filtering the authorized user to access the resource. E.g. in below
code snippet we have decorated an action method with Authorize attribute.

• If we will try to access this action then it will give following error:

The new Authorize attribute can do role checks like this:

[Authorize(Roles = "Sales")]
public IActionResult DoSalesyStuff()
{ /* .. */ }

Following lesson focus on how to use ASP.NET Identity in MVC Application for
creating user roles and displaying the menu depending on user roles.

Authentication and Authorization

Authentication

Check for the Valid User. Here the question is how to check whether a user is
valid or not. When a user comes to a website for the first time he will register
for that website. All his information, like user name, password, email, and so
on will be stored in the website database. When a user enters his userID and
password, the information will be checked with the database. If the user has
entered the same userID and Password as in the database then he or she is a
valid user and will be redirected to the website home page. If the user enters
a UserID and/or Password that does not match the database then the login
page will give error message, something like “Enter valid Name or
Password”.
The entire process of checking whether the user is valid or not for
accessing the website is called Authentication.

You need to add <system.web> to the web.config and put the authentication
section within it:
<system.web>
<authentication mode="Forms">
<forms loginurl="~/Comfirm/Login" timeout="2880"></forms>
</authentication>
</system.web>

This mean there is a controller Comfirm and an action Login.cshtml view


and Login action any one who not authenticated redirected to this page
Timout specify how long the user is authenticated after login in .

Authorization

Once the user is authenticated he needs to be redirected to the appropriate page by his
role. For example, when an Admin is logged in, then he is to be redirected to the Admin
Page. If an Accountant is logged in, then he is to be redirected to his Accounts page. If
an End User is logged in, then he is to be redirected to his page.
Web.config role provider

Store roles in web.config. Convenient for smaller web applications,


role management on development setups or other scenarios
where it's not possible/practical to use the SQL Server Role
Provider.

Features

• Roles stored in web.config. Fast to set up, easy to deploy.


• Supports external configuration files.

Configuration

<configuration>
...
<system.web>
<roleManager enabled="true"
defaultProvider="WebConfigRoleProvider">
<providers>
<add name="customRoleProvider"
type="WebConfigRoleProvider. myRoleProvider"/>
</providers>
</roleManager>
</system.web>
Role-based authorization in ASP.NET mvc
When an identity is created it may belong to one or more roles. For example, Tracy
may belong to the Administrator and User roles whilst Scott may only belong to the
User role. How these roles are created and managed depends on the backing store
of the authorization process
Adding role checks
Role-based authorization checks are declarative—the developer embeds them
within their code, against a controller or an action within a controller, specifying
roles which the current user must be a member of to access the requested resource.
For example, the following code limits access to any actions on
the AdministrationController to users who are a member of
the Administrator role:

[Authorize(Roles = "Administrator")]
public class AdministrationController : Controller
{
}

You can specify multiple roles as a comma separated list:


[Authorize(Roles = "HRManager,Finance")]
public class SalaryController : Controller
{
}

This controller would be only accessible by users who are members of


the HRManager role or the Finance role.

If you apply multiple attributes then an accessing user must be a member of all the
roles specified; the following sample requires that a user must be a member of both
the PowerUser and ControlPanelUser role.

[Authorize(Roles = "PowerUser")]
[Authorize(Roles = "ControlPanelUser")]
public class ControlPanelController : Controller
{
}

You can further limit access by applying additional role authorization attributes at
the action level:

[Authorize(Roles = "Administrator, PowerUser")]


public class ControlPanelController : Controller
{
public ActionResult SetTime()
{
}
[Authorize(Roles = "Administrator")]
public ActionResult ShutDown()
}
}

In the previous code snippet members of the Administrator role or


the PowerUser role can access the controller and the SetTime action, but only
members of the Administrator role can access the ShutDown action.

You can also lock down a controller but allow anonymous, unauthenticated access to
individual actions.

[Authorize]
public class ControlPanelController : Controller
{
public ActionResult SetTime()
{
}

[AllowAnonymous]
public ActionResult Login()
{
}
}

You might also like