Showing posts with label ASP.Net Web API. Show all posts
Showing posts with label ASP.Net Web API. Show all posts

Saturday, October 17, 2015

Basic Authentication in Web-API at HOST level using Authentication Filters


In our previous discussions, we discussed about the basics about the security in asp.net web api. If you have not read that then i would recommend you to read that first here, as it will act as a base of where and how to apply the security in asp.net web api, as we discussed the basics of security. Also we discussed the concept of how we can Implement Basic Authentication in ASP.Net Web API at Host level (IIS). 

Continuing on same lines, we will implement basic authentication using the concept of Authentication filters. An authentication filter is nothing but creating an attribute and applying it on the class or method.
To start with, we will create an empty ASP.Net application. Next, we add an API controller called SampleController and derive it from ApiController to make it a web-api type controller. Also we add a method named GetList() to return list of string values. So our class will look like the following.

 public class SampleController : ApiController
 {
        public IEnumerable<String> GetList()
        {
          return new String[] { "value1", "value2" };
        }
 }


Let's browse the api method using the path: and see the results. We can easily view the results. No username/password required.

Anybody, who knows the url of your api, can make call to it and use the method and we would like to restrict this, so that only people who are authorized to access the system, should get access to the api method. So, in order to apply security on our method, we need to do the following:
  1. Create an authentication filter, which is nothing but a class derived from IAuthenticationFilter interface and Attribute class. It will implement the following IAuthenticate methods. These are:
    • AuthenticateAsync
    • ChallengeAsync
  2. Apply this filter as an attribute on the method or the controller, on which we would like to add the security.
  3. Apply the Authorize attribute along with this attribute. 
How the security process will work ? 

When the IAuthenticationFilter is applied, AuthenticateAsync is the method which will receive any request for the web-api methods and check for the credentials(if they are present), in the request header. There are 3 possible scenarios:

Case 1 - No credentials provided: Client request has not sent any credentials. In such a case, authentication filter will do nothing and pass it on to Authorize attribute to handle it. Since there were no credentials, and identity was NOT authenticated, the request is rejected with Code 401 unauthorized result.

Case 2 - Invalid credentials provided: In case the client has provided invalid credentials, the ErrorResult property of the current HttpAuthenticationContext instance is set with UnauthorizedResult. An authentication challenge is added to the Result property of the current HttpAuthenticationContext instance. This is done by the ChallengeAsync method of the IAuthenticationFilter interface.

Case 3 - Valid credentials provided: If the credentials provided in the request header are valid, then a valid ClaimPrincipal will be generated and will be assigned to the Principle property of the current HttpAuthenticationContext instance. Further the Authorize attribute will check if the Identity is established for the request, then allow the access to the method or controller. 

So one of the major role of Authorize attribute is checking whether an identity for the user has been established or not by the authentication filters, which were executed previously in the pipeline. If it is not established, then return 401 Unauthorized error, else request will be allowed to access the method.
So let's start by creating the authentication filter class. We will name it as BasicAuthenticationFilter. We will derive it from Attribute class and IAuthenticationFilter. So our code will look like the following:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Security.Claims;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using System.Web.Http.Filters;
using System.Web.Http.Results;
namespace AuthenticationFilter
{
    public class BasicAuthenticationFilter : Attribute, IAuthenticationFilter
    {
        private readonly String realm;
        public Boolean AllowMultiple { get { return false; } }
        public BasicAuthenticationFilter(string realm)
        {
             this.realm = "realm=" + realm;
        }
        public Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)
        {
             var currentRequest = context.Request;
             if (currentRequest.Headers.Authorization != null && currentRequest.Headers.Authorization.Scheme == "Basic")
            {
                 Encoding encoding = Encoding.GetEncoding("iso-8859-1");
                 var headerData = encoding.GetString(Convert.FromBase64String(currentRequest.Headers.Authorization.Parameter));
                 var credentials = headerData.Split(':');
                 var userId = credentials[0].Trim();
                 var pwd = credentials[1].Trim();
                 if (userId == "jasminder" && pwd == "jasminder")
                 {
                    var claims = new List<Claim>()
                    {
                                new Claim(ClaimTypes.Name, "auth")
                    };
                    var id = new ClaimsIdentity(claims, "Basic");
                    var principal = new ClaimsPrincipal(new[] { id });
                    context.Principal = principal;
                 }
                else
                {
                    context.ErrorResult = new UnauthorizedResult(new AuthenticationHeaderValue[0], context.Request);
                }
            }
              return Task.FromResult(0);
     }
    public async Task ChallengeAsync(HttpAuthenticationChallengeContext context, CancellationToken cancellationToken)
        {
            HttpResponseMessage result = await context.Result.ExecuteAsync(cancellationToken);
            if (result.StatusCode == HttpStatusCode.Unauthorized)
            {
                result.Headers.WwwAuthenticate.Add(new AuthenticationHeaderValue("Basic", "realm=" + this.realm));
            }
            context.Result = new ResponseMessageResult(result);
        }
    } 
}


Attribute class will make it possible to apply it as an attribute on the method or controller. AuthenticateAsync will be used for authenticating the request credentials, if present, and ChallengeAsync will be used to prepare the final HttpResponse, based on the result of ExecuteAsync method of the current HttpAuthenticationChallengeContexts' context.

Now simply apply this filter and the authorize attribute on our method, like any other attribute:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace AuthenticationFilter
{
    public class SampleController : ApiController
    {
        [BasicAuthenticationFilter("testRealm")]
        [Authorize]
        public IEnumerable<String> GetList()
        {
            return new String[] { "value1", "value2" };
        }
    }
}

Now let's test the 3 cases that we discussed above.

Case 1:  Run the application and you will be prompted for a username/password.


Click Cancel and see that you get the message Authorization has been denied for this request.


This was because, when the authentication filter received the request, no credentials were provided. So it passed on the request to the Authorize attribute. Due to absence of an authenticated principle, it rejected the request and this message was received.

Case 2:  Run the api again and this time enter invalid credentials. This time, the authenticate method will check for the credentials. Since the credentials were not valid, it will set the ErrorResult property of the current HttpAuthenticationContext instance.




Case 3:  Since the credentials were invalid, it will again ask for the credentials. This time, we will provide the valid credentials and see the code get's executed:



This time the credentials were valid. So an Identity is established for the current request (as above) and method result is returned.

Now a point that I have mentioned above, about the ExecuteAsync is very important. This means that when ever the ChallengeAsync method get's executed, it will get the HttpResponse generated for the request, from the ExecuteAsync method. So if the ExecuteAsync method says that the request is UnAuthorized request, we will check the response and set the basic authentication challenge in the response. Read a very important point here, from the official asp.net web-api. It says:

It's important to understand that ChallengeAsync is called before the HTTP response is created, and possibly even before the controller action runs. When ChallengeAsync is called, context.Result contains an IHttpActionResult, which is used later to create the HTTP response. So when ChallengeAsync is called, you don't know anything about the HTTP response yet. The ChallengeAsync method should replace the original value of context.Result with a new IHttpActionResult. This IHttpActionResult must wrap the original context.Result.

The best way to test this point is to remove the Authorize attribute and add a debugger to the ChallengeAsync and the api method we need to access. When we run the request, we can see that the ExecuteAsync will be able to execute the api method (in our case it is GetList) and HttpStatusCode as OK will be returned. This means the HttpResponse was successfully generated for the request, by the ExecuteAsync method. Had we applied the Authorize attribute, it would have returned UnAuthorized status and based on the results it returned, we can then add our authentication challenge on the response from the ExecuteAsync.

So this was how we can implement the basic authentication filter using web-api Authentication filters. Hope you enjoyed reading it. Happy coding...!!!

Thursday, September 10, 2015

Security in ASP.Net Web API

While exploring security options in asp.net web api, found many options on the web including the official ASP.Net Web API website. So explored it further and things became more clear. Finally decided to compile the understanding about this concept and hope it will help you also:

To start with we have to basic things/aspects about the security implementation. These are:


  • Authentication: Authentication is whether a user has proved his authenticity to access the web-api.The client request proves authenticity usually in the form of some kind of username and password. 
        For ex. an office may only allow people to enter, who is having any access card, to               enter office premises. If he is not, the system will not allow him to enter the office.
  • Authorization: Authorization on the other hand means, although being authenticated to access the web-api, should a user be allowed access a particular method of the web-api. 
         For ex. although a person may be allowed to enter the office he may still not have                  access to certain areas of the office, due to different department.This is the concept of          authorization. If you are not authorized, you will not be allowed to access the                          resource. 

Further, in order to implement the security we have two different points/level where we can implement the security. These are :

  1. Host Level:  Host is basically which is used to host the web-api. Host level options include the to use the Http Modules and OWIN middle-ware components. Http modules restrict to use IIS as the host option i.e. you can use the Http modules to implement security only if you are using IIS for hosting the web- api. On the other hand, to use OWIN middle-ware components we must use OWIN based hosting of the web api.

  2. ASP.Net Web API pipeline: This allows implementation within the asp.net web-api pipeline, rather then dependency on the hosting option used for it.This means they are host agnostic i.e. there implementation does not rely on the underlying hosting option. We may have IIS or OWIN based hosting and use any of the options available in this category. Some of the options available in this category include:
    • Use of Message Handlers
    • Use of Action Filters
    • Use of Authorization Filters
    • Use of Authentication Filters
So if we talk about what we discussed above, we can represent the different options in hierarchy as :



Host level options are executed before the request reaches the web-api. So when implemented, they get called earlier in the request cycle and may get called, even if the request is not aimed at the web-api resource. On the other hand, web-api level options are executed after the host and are more specific to the requests which are intended for the api.

For ex. when Http modules are used as an option to implement the authentication, it will be called for any type of incoming request to the web-server, even if it's not related to the web-api. On the other hand, option like Message handler (at web-api level), executes only for the requests which are aimed at the web-api.

Host level options are less preferable as they restrict the type of host used. Options at the web-api level provide more granular level of permissions which means they can be applied at the Controller level or the Method level in api. 

For ex. Authentication filters are a new feature in ASP.Net Web-API 2. This option is available at the web-api level and provides more granular control over the security, as it allows the filters to be applied at the controller and the individual method levels as well.

So this is about the basic concepts about security implementation in asp.net web-api. I hope you enjoyed reading it. Any feedback is welcome. Happy coding...!!!

Sunday, March 1, 2015

WebAPI self hosting using OWIN

In one of my previous articles, we discussed `. Continuing on the same paths, we will now discuss how we can self host the web api, using OWIN custom host. So let's start with it.
Add a new Console application and let's call it WebAPIOWINHosting.

Next, in order to create a webapi and use OWIN custom host, we add references to Microsoft.AspNet.WebApi.OwinSelfHost, using nuget package manager. This will not only add the references for the webapi but also the OWIN components, along with the other required dependencies.


Add a new webapi controller class. We remove all the methods and add a simple GET method to get sum of two random numbers.




Add a new class named Startup.cs. This is as per the OWIN specifications. Use the HttpConfiguration class to create the webapi routing template and add it to the request pipeline using the appBuilder.UseWebApi method, where appBuilder is of type IAppBuilder.

Open the Program.cs file and start the server using the WebApp.Start method, spcifying StartUp class as the entry point for the settings required. This is the OWIN specification of starting the server in the custom host.

Now simply run the application and the server is started. 



To test the webapi, we will use the Chrome browser Postman extension. So enter the url of the webapi, which we specified in the Program.cs and Send the request. See the results are received.

Easy to host, isn't it. If you learnt it than do share it. Source code of the example is also attached here. Happy coding...!!!

Friday, December 26, 2014

ASP.Net Web api self hosting using windows service

In my previous article, we discussed about web api self hosting using console application. This time, we will use the windows service to perform the self hosting of the web api. So let's start by creating a new windows service project type. We call it as WindowsService_HostAPI. 
In order to perform the self hosting of web api, we need to add references to the self hosting libraries. For this, we use the nuget package manager and install the references.
 


Next, we select the project in which we need to add the references and the following libraries get added to the project.
Next, we add a new item of the type web api controller class and name it as ValuesController, which inherits from ApiController. Make sure that the suffix of the class is  'Controller'.  This is required for the routing process to handle the incoming request. We remove all the default methods and add a simple method named GetString which returns a string value.

Now we need to configure a hosting server which would host the api. The point here is that this server must get configured in an event, which gets fired when the service is started. So we will use the OnStart event of our service class (which inherits from ServiceBase class). When the service is hosted, this OnStart event will be fired and the hosting configuration will be registered. So our code becomes:

Build the solution. Now the api is ready to be hosted and for this, we only need to install the service and than start it by navigating to the list of installed services.
To host this windows service, go to the service design view, right click and select 
Add Installer. 

1. Go to the properties of serviceInstaller1 and change the ServiceName property to WebAPISelfHosting. This will be name with which the service will get installed.
2. Go to the properties of serviceProcessInstaller1 and change Account property to LocalSystem.
To install the service, we need to use the installutil.exe from the location:
C:\Windows\Microsoft.NET\Framework\v4.0.30319
or you can start the visual studio command prompt (as an administrator) and use the following command to refer to the above location of installutil.exe.
cd  C:\Windows\Microsoft.NET\Framework\v4.0.30319
Execute the following command in the command prompt to install the service.
installutil ...\WindowsService_HostAPI\WindowsService_HostAPI\bin\Debug\WindowsService_HostAPI.exe
I have used only relative path here for the example. Make sure that you use the complete path, from the root. This will install the service on the system.

Go to the list of installed windows services, select the service named WebAPISelfHosting, right click and start the service.

Web api is now hosted and we can create a client to generate request to the api. For this we create an html page which will make an ajax call to the api.

Run the client page and also start the network capture using F12. See the results, web api returns the results.

So this is how we can host the web api using a windows service. Hope you enjoyed reading it. Happy coding...!!!