Thursday, May 28, 2015

Facebook Authentication in ASP.NET5 Application

In today's blog post, I will be discussing how to set up Facebook authentication in ASP.NET 5 Web application.

Facebook Authentication in Web Application

To begin with, I created a new web application on Visual Studio 2015RC.
Then I navigated to and added a new app. Choose Website as the platform:

 I named the app as TestAuth and you can choose any category and click on Create App ID

 Now your App ID and and App Secret are created and you can view them like this:

In the Settings tab, I also added my project URL:

Then, in my TestAuth application, I went to Startup.cs file, Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerfactory) method and uncommented the following code:


This adds the Facebook Middleware by adding it to the HTTP Request pipeline.

Next, I added the AppId and AppSecret to my config.json file

  "Authentication": {

    "Facebook": {

      "AppId": "8xxxxxxxxxx",

      "AppSecret":  "2xxxxxxxxxxxxxxxxxxxxxx"



 Now when I run the application and navigate to Login page, I see Facebook login:

Clicking on Facebook button, redirects to the facebook login page. The customer can now use facebook credentials to login to our web application.


So we saw it's easy to set up Facebook authentication on our web application. This prevents the user from the hassle of creating new credentials on our site and for us as web developers, it prevents the hassle of managing the passwords. Similarly, we can use Twitter, Google, etc to set up authentication provider.
For future updates to my weekly blog, please subscribe to my blog via the "Subscribe By Email" feature at the right and follow me on Twitter. Until then Happy Coding :)

Thursday, May 21, 2015

Tag Helpers in ASP.NET5

In today's blog post, I will be discussing tag helpers in ASP.NET5. I recently downloaded the Visual Studio 2015 and started playing around with it. One of the new and exciting features in ASP.NET 5 (MVC6) is tag helpers.

Why Tag Helper

When we are working with MVC Views, currently we write C# like code in order to output the HTML elements. For example,

@Model.FirstName, new { style = "width: 100px;" })

When I am writing this code, I have no intellisense available to me when I am adding styles. All this is mentioned as simply HTML attributes. Even when I am adding any of the arguments, I don't get any intellisense to assist me. Also, if we look at the way any View page looks, overall it looks more like C# code rather than HTML code.

So here come the tag helpers to rescue us. The tag helpers help us write the view code in a cleaner way.

<input asp-for="FirstName" style="width:100px;"/>

This code looks more like HTML rather than C# code.

Secondly, now I have intellisense at every step while writing the code. Check out the screenshots:
i) Intellisense for Model Property Name

ii) Intellisense for style/ class, etc:

iii) Intellisense for choosing css class:

iv) Intellisense for choosing style:

Custom Tag Helper

Not only we can use the tag helpers provided to us, we can also create our own tag helpers. Let's see how to create our own custom tag helpers in MVC6 application. In order to create our own custom tag helper, we need to derive from TagHelper abstract class. Let's do this with an example:

 [TargetElement("entity", Attributes = "type")]

    public class EntityTagHelper : TagHelper


        public override void Process(TagHelperContext context,
         TagHelperOutput output)


            int type;

            output.TagName = "img";

             out type);

            string image = String.Empty;

            switch (type)


                case 0:

                    image = "/images/employee.png";


                case 1:

                    image = "/images/department.png";


                case 2:

                    image = "/images/group.png";



            output.Attributes["src"] = image;



Here, I created an EntityTagHelper and overrode the method called Process. There are 2 methods Process and ProcessAsync which can be overridden in TagHelper class. Async as the name suggests is for asynchronous processing.
The Process method has context and output parameters. We will be reading out input attributes from context and setting our output attributes in the output parameter. So here I am creating an img tag and setting the source of the image based on the value of attribute type provided with the entity tag, using simple switch case.

Next, I added this to _GlobalImport.cshtml

@addTagHelper "*, Abhi1"

So here I am adding my custom tag helpers from project named "Abhi1" to my views. This step is extremely important as without this the custom tags will not be working.

Next, I added this to my view:

<entity type="1"></entity>

Since type value of 1 was provided, which translates to department.png; I was able to get the image like this:

In this blog post, we saw how custom tag helpers are useful and how we can write our own custom tag helpers in MVC6.
For future updates to my weekly blog, please subscribe to my blog via the "Subscribe By Email" feature at the right and follow me on Twitter. Until then Happy Coding :)

Thursday, May 14, 2015

Custom Error And Stack Trace in MVC

In today's blog post, we will be discussing how harmful can a visible stack trace be and how we can avoid it.

Stack Trace

When the application throws an exception, we see the stack trace in the browser. This information is very valuable to someone who is trying to compromise your web application. The stack trace exposes the internal code structure and framework information. It also shows what caused the exception and it gives insight to the outsider how he can make the application fail.

Custom Error

In order to avoid leaking such information, we must set the customError mode in the config file. Inside system.web section of the web.config, we can set custom errors like this:

    <customErrors mode="On" defaultRedirect="/Error/Error">
      <error statusCode="403" redirect="/Error/UnAuthorized"/>

The mode can be set to On, Off or RemoteOnly - depending on the application needs. defaultRedirect is set to the path to which to redirect once an unhandled exception occurs. We can also set specific paths for different status codes. For example, for 403 Forbidden, we might want to show a separate view.

Here is how the ErrorController looks like:

public class ErrorController : Controller


        public ActionResult Error()


            return View();


        public ActionResult UnAuthorized()


            return View();



Now, if a generic exception occurs, the error page looks like this:

And if an unauthorized exception is thrown in the application, the page looks like this:


Proper Configuration for custom error is important for the safety of the web application. Custom Error setting in web config allows us to hide the sensitive information from being misused.
For future updates to my weekly blog, please subscribe to my blog via the "Subscribe By Email" feature at the right and follow me on Twitter. Until then Happy Coding :)

Thursday, May 7, 2015

Session Hijacking using Elmah in MVC

In today's blog post, we will be discussing how session can be hijacked using Elmah logs.


Elmah stands for Error Logging Modules and Handlers. It's used to log all kinds of errors across the application. One can view all the unhandled exceptions in the application in production environment.
In order to add Elmah to the application, we just need to add Elmah.Mvc (since it's MVC application, we should use Elmah.Mvc) via the Nuget Package Manager.

Once it's added to the project, we can navigate to /Elmah and see all the error logs. If we navigate to the exception details, we can see all kinds of information about the exception like call stack, timestamp, logged in user, request URL, etc. Other than these, there is another very important piece of information that is available i.e. Cookies (esp. AspNet.ApplicationCookie).

Session Hijacking

Session Hijacking attack comprises of stealing the session token used to identify a particular session, generally to gain unauthorized access to the web server.
So I have an application where Employee records are maintained and some users have access to the edit functionality and some are allowed to only view the records but not edit them.

So when logs in, he is able to edit the employee record. But when tries to access the Edit page, he gets unauthorized error. Now if the malicious user is able to access Elmah records, he can look at the Auth cookie value and copy it and paste it in his browser.
In order to accomplish this attack, I installed this Google Chrome extension called "EditThisCookie". This extension allows me to edit the cookie values. So the malicious user can copy the value from Elmah log and put it in the AspNet.ApplicationCookie like this:

And that's it, now the malicious user has hijacked the innocentuser's session and is logged in as the innocent user. He can access the Employee edit page (or other privileged information which he was not allowed to access).

How to Prevent

Since the information exposed by Elmah logs is so sensitive, we need to take care of who can see all the logs. So proper configuration of Elmah is extremely important.
By default, the Elmah logs are not available to be accessed remotely. In order to allow them to be accessible we need to add this to our config file:


    <security allowRemoteAccess="yes"/>


If we allow them to be remotely accessible, we need to configure who should have access to it. By setting requiresAuthentication to true, we make sure that the user has to be logged in in order to access the Elmah logs. We can also set specific roles or specific users who should have the access.


    <add key="elmah.mvc.disableHandler" value="false" />

    <add key="elmah.mvc.disableHandleErrorFilter" value="false" />

    <add key="elmah.mvc.requiresAuthentication" value="true" />

    <add key="elmah.mvc.IgnoreDefaultRoute" value="false" />

    <add key="elmah.mvc.allowedRoles" value="*" />

    <add key="elmah.mvc.allowedUsers" value="" />

    <add key="elmah.mvc.route" value="elmah" />

    <add key="elmah.mvc.UserAuthCaseSensitive" value="true" />


So according to the application needs, Elmah should be accessible to specific roles or users.


So we saw how we can login into somebody's account just by looking at the Elmah logs. Therefore, proper configuration of Elmah is extermely important for the security of our web application.
For future updates to my weekly blog, please subscribe to my blog via the "Subscribe By Email" feature at the right and follow me on Twitter. Until then Happy Coding :)