ASP.NET MVC 4 : Authentication and Authorization:Intranet Application - c#

I'm new to ASP.NET MVC world. I'm building an intranet web application. Authentication and authorization is defined in my case as below:
Authentication: If HttpRequest contains an Header with "USER_ID", user is authenticated.
Authorization: There is one in-house WCF Service, which returns list of roles user is entitled to taking USER_ID as input. I keep the roles required by my application in xml file. If user's required role is in svc response then, she is allowed to use the application.
I'm thinking of implementing it like below:
In Global.asax - > Application_AuthenticateRequest, I'll put code to check http Header. If its non_blank, I'll let user to go through this stage.
In OnAuthorization method of AuthorizeAttribute class, I'll put code to fetch role list and match it against required roles from xml file.
Is there any way that I can use existing authentication,authorization infrastructure?
I see code like this
[Authorize(Roles = "admin")]
public string Index() {
return "only admins!";
}
How can I link Roles property like above to some Xml or Table instead of hard coding?
Please help me to implement this logic in asp.net mvc application.

You should check Windows Identity Foundation (WIF), in particular ClaimsAuthorizationManager and ClaimsPrincipalPermissionAttribute. The later allow you to specify what operation and resource need to be secured, while in ClaimsAuthorizationManager you can check whether the current user can perform the operation on the resource, and that can be read from any source you desire.

For Authorization, I would either:
Create a GenericPrincipal in the global.asax AuthorizeRequest event handler with the appropriate roles, and assign it to both HttpContext.User and Thread.CurrentPrincipal.
Or (better), write a custom RoleProvider that gets the users roles from the xml file. If you configure such a RoleProvider, ASP.NET will assign a suitable RolePrincipal to both HttpContext.User and Thread.CurrentPrincipal.
You can then use the standard AuthorizeAttribute.

Related

Custom role based authorization from an existing database

Currently, I am developing an web application in ASP.net and till now i have done authenticating the user after successful login using Identity in ASP.Net. Now i want to authorize the user based on the different roles available in the database. I have a database with 3 tables namely Users, Roles and UserRoles. A user can have more than 1 role.
In this case, how can i implement role based authorization in my project.I have done custom authentication using Identity and removed Entity from my project.
public void ConfigureAuth(IAppBuilder app)
{
// Configure the custom user manager and custom signin manager to use a single instance per
request
app.CreatePerOwinContext<CustomUserManager>(CustomUserManager.Create);
app.CreatePerOwinContext<CustomSignInManager>(CustomSignInManager.Create);
}
With this, simple[Authorize] attribute is working fine for me. How can i create something like [Authorize(Roles="Customer")]? Should i use something like IRole for this or just overriding Authorize Attribute method is enough? Is both same or different? Can anyone help me to solve this problem?

How in ASP.NET MVC do I maintain info about whether a user is "logged in" throughout pages?

After they type in their password, should I keep a variable in server session storage like Session["loggedIn"] = true that I check when requests are made to pages that require a login, or is there a better/safer way this is traditionally done in ASP.NET?
No, do not keep this in a session variable. In fact, I would argue you should try not to use session for anything. Try to keep the HTTP communication as stateless as possible.
For authentication in ASP.NET MVC, you have 2 alternatives, but ultimately, the both end up working the same way: by writing an encrypted authentication cookie to the browser after you successfully log a user in.
The newer alternative was mentioned in a comment to the OP: Microsoft.AspNet.Identity. To use this, you should be using a newer version of ASP.NET MVC with the OWIN pipeline (though I am not sure if you have to). The older alternative is called Forms Authentication, and can be used with any version of MVC except version 6 (the new vNext / core 1.0 stuff) I believe.
When you have successfully integrated one of these 2 tools into your MVC application, after a user logs on, your Controllers will have a non-null User property of type IPrincipal. You can use this property to determine whether or not a user is authenticated:
// in a controller
bool isThereAUserLoggedIn = this.User != null && this.User.Identity.IsAuthenticated;
If you are using the newer Microsoft.AspNet.Identity, then this IPrincipal User property will be implemented as a ClaimsPrincipal with one or more ClaimsIdentitys. Forms Authentication does not do claims like this, so if you want claims, or social login, etc, use Microsoft.AspNet.Identity.
The way that this is traditionally done in ASP.NET and by my opinion also better and safer is by making use of the ASP.NET Identity package.
ASP.NET Identity handles all aspects around user accounts in a web application:
database for users, including roles and more
user registration and management, like register, email verification, log in, remember me option, forgot my password action and more.
user authentication & authorization
Just to make things more clear, authentication means that the user making the request is actually a valid application user and authorization means that the user has the authority to perform the requested action.
Practically, when a user logs in, Identity automatically keeps that information and makes it available in all controllers and views under User property. So you know at any time which user made the request. Identity also supplies each request with a cookie used for user authentication and authorization.
To check for user authentication you use the User.Identity.IsAuthenticated in a view and the Authorize attribute in a controller:
[Authorize]
public ActionResult Create( ... ){ ... }
The above use of the Authorize attribute will allow only to registered users to request this page.
It is also very common to extend the functionality of your application to include roles for the users and user authorization. Identity creates a "Users" table, a "Roles" table and a many to many relationship between them. After assigning roles to your users you can authorize their requests by using User.Identity.IsInRole("YourRoleName") in a view and in a controller:
[Authorize("YourRoleName")]
public ActionResult Create( ... ){ ... }
The above use of the Authorize attribute will allow only to registered users having the "YourRoleName" role to request this page. In any case if Identity fails to authenticate or authorize the request will prompt to the log in page.
ASP.NET Identity is simple to use, it works and it is easy to extend the membership functionality of your application both by making use the many tools supplied with it and overriding its classes to give them a more specific or complex behaviour.
You will find infinite help on the web on how to use it or a step by step guide.

extend HttpContext.User.Identity in asp.net mvc

in my application i want to use the current logged in user details,
in HttpContext.User.Identity there are 'AuthenticationType', 'IsAuthenticated' and 'Name', I want some more details from database when user logged in to the system. Is there any way to extend this identity class?
As Daniel noted in his comment you're going to need to create your own implementation of IPrincipal. I'm going to assume that you're using MVC5. If so, then you're going to need to implement an authentication filter which will allow you to set the principal for the request. This authentication filter would go to the database, retrieve the fields you have added, and populate your IPrincipal implementation. Finally, you would need to globally register that filter in your FilterConfig.cs file in App_Start so that it will be applied to every controller action in the application without you having to type it over and over again.

Authentication filters in MVC 5

Authentication filters from Release Notes page
Authentication filters are a new kind of filter in ASP.NET MVC that
run prior to authorization filters in the ASP.NET MVC pipeline and
allow you to specify authentication logic per-action, per-controller,
or globally for all controllers. Authentication filters process
credentials in the request and provide a corresponding principal.
Authentication filters can also add authentication challenges in
response to unauthorized requests.
Can some one provide the practical use of this? Where I can use this AuthenticationFilters exactly?
Earlier I use to manage Access Control List for a action/controller by writing own CustomAttribute: FilterAttribute, IAuthorizationFilter and implement public void OnAuthorization(AuthorizationContext filterContext) . Is it possible to use this AuthenticationFilter here?
As the docs says, the custom authentication filter provides an authentication per-action, per-controller or globally.
An example use is changing the authentication for just few selected controllers. Suppose for example that your whole site uses Forms Authentication where principals are taken from forms cookies.
However, you have a selected controller that acts as OAuth2 Resource Server where requests come from Service Providers (servers) and there are no forms cookies, rather, an OAuth2 access token is provided by the service provider server.
This is where a custom authentication filter comes into play - its task is to translate the token to a principal for the lifetime of current request only, just for the only controller that acts as the resource server endpoint. You don't want the whole site to accept OAuth2 tokens, rather the one particular controller.
The reason to introduce authentication filters is to separate authentication from authorization, where:
authentication is for estabilishing a principal for current request
authorization is to verify whether or not the current principal is permitted to execute current request
This was not clearly separated before authentication filters were introduced. Personally, I used to use authorization filters for this, however having two separate layers of filters in this particular order (authentication first, then authorization) is just cleaner.
Custom authentication can be created by implementing IAuthenticationFilter. It can be used where current user principal is necessary to change for executing certain portion of action of a controller by overriding OnAuthentication method. One can put extra task on request by overriding OnAuthenticationChallenge method.

what is the best way to restrict services for certain users

EDIT: reworded and simplified question to be consise...
In my service layer I have something like
GetAllMessages(string userid);
I could have various types of users on my system like Clients / Supplier etc...
This service is only available to all types of users, however what is the best way to implement services only available to selected users e.g.
DeleteAllMessages(string userid); //client only
NewSupplierMessages(string userid); //supplier
Typically these methods will be in one class called MessagesService
NOTE: just to clarify, the user is loggedon and authenticated, however I am wondering if I should write my methods as such:
DeleteAllMessages(ClientUser user); //client only
NewSupplierMessages(SupplierUser userid); //supplier
Basically get the details of the user for every action and call methods in a more strongly typed manner...
EDIT 2:
Note my domain layer is in a seperate class library from my web app, a "client user" will be part of a "client", similarly a "supplier user" will be part of "supplier" - so if I wanted to query my service layer and call the correct code (i.e. retrieve the correct details) - I MUST pass in the user id or a strongly typed class of the user, I cannot see how having a contraint on a DTO object that represents who can access the service as incorrect/ brittle?
Other wise I will have something like this:
GetClientDetails();
The user is handled by asp.net so we know this action can be accessed by the user, however what if there are multiple clients? Surely then we must pass in some some of client id/ if I was to pass in user id I could get the client id from it...
Rather I would say my domain layer is incorrect seeing something like the above signature...
EDIT 3:
The only other alternative I could think off is, when the user authenticates, store the use in a class called UserSession inside the asp.net mvc application as a global state, then inject this using DI (ninject) into my domain service layer, therefore when my signatures can be
GetClientDetails();
The domain service class implementing this interface could be:
public class ClientService : IClientWorkerService
{
private ISession _session;
private IGenericRepo = _repo;
public ClientService(IUserSession _session, IGenericRepo _repo)
{
this._session = _session;
this._repo = _repo;
}
public ClientDetails GetClientDetails()
{
var loggedonuser = _session.GetUser();
if(!loggedonuser.isClient())
throw new NoAccessException()
return _repo.Single<Client>(x=> x.ClientID == loggedonuser.ClientID);
}
}
See MSDN: ASP.NET Authorization
Authorization determines whether an
identity should be granted access to a
specific resource. In ASP.NET, there
are two ways to authorize access to a
given resource:
File authorization
File
authorization is performed by the
FileAuthorizationModule. It checks the
access control list (ACL) of the .aspx
or .asmx handler file to determine
whether a user should have access to
the file. ACL permissions are verified
for the user's Windows identity (if
Windows authentication is enabled) or
for the Windows identity of the
ASP.NET process. For more information,
see ASP.NET Impersonation.
URL authorization
URL authorization
is performed by the
UrlAuthorizationModule, which maps
users and roles to URLs in ASP.NET
applications. This module can be used
to selectively allow or deny access to
arbitrary parts of an application
(typically directories) for specific
users or roles.
An Overview of Authentication and Authorization Options in ASP.NET
Building Secure ASP.NET Applications: Authentication, Authorization, and Secure Communication
Role-based access control
Custom role based Web Service access

Categories

Resources