Tuesday, July 17, 2018

Authentication using External Providers(Hotmail)

In my previous article, I wrote about how to authenticate by creating new user accounts. Now what if, anyone doesn’t want to add another pair of user id password to his memory and want to use the existing ones which he/she is using very frequently in his/her day-to-day life. Well, here comes the external providers in the picture.
In this article, I won’t be covering the basics on how to create a website from scratch as it is already covered in an earlier article. So, let’s quickly jump on to the login screen and on right hand side, you will see the text as ‘Use another service to log in.’ as shown in below image:

Above screenshot also provides a hyperlink, which will guide us on how to setup the authentication using external providers.
What are external providers?
There is a huge list of authentication providers. The most common one’s are Twitter, Facebook, Google and Microsoft. This list is not restricted till here as it can be any other custom provider. Throughout this article, I’ll be driving you to setup the authentication with Hotmail account.
Steps to setup authentication with Hotmail account
Navigate to https://apps.dev.microsoft.com and do login using existing Hotmail Id as shown below:

On successful login, you will land upon below page:

Next is to click on ‘Add an app’ button, which is shown on top right corner. This will take you to:

In the above dialog, provide the application name and click on ‘Create’ button. Here you can also take a path of guidance by clicking on checkbox ‘Let us help you get started’. Once you click on Create button, an Application Id will be generated for you as shown below: 

Next, we have to work on adding application secrets.
Adding Application Secrets
Now click on ‘Generate New Password’ button. On click of this button, a password will be generated by you like shown below:

Copy this newly generated password and temporarily save it somewhere as you will need this password during the application configuration along with Application Id.
Adding Platform
Click on App platform on Registration screen. Here, for demo purpose I'm choosing Web. You can choose others too.
Next is to construct an URL, which is a combination of our application URL and signin host. This is what how it looks:

Click on the Save button and you are done with the configuration. Next, we have to associate this configuration with our application. So, let’s go ahead and quickly update our application using User Secrets as shown below: 

and place the following code in secrets.json:

  "Authentication:Microsoft:ApplicationId": "654e030a-a10b-40ee-82db-1bf0185aebc0",
  "Authentication:Microsoft:Password": "XXXXXXXXXXX"
Same lines of code you can write in Startup.cs also but we are maintaining the secrets in different file so that it can be changed easily while moving to production.
Next is to configure the identity in Startup.cs:

public void ConfigureServices(IServiceCollection services)
       services.AddDbContext<ApplicationDbContext>(options =>

       services.AddIdentity<ApplicationUser, IdentityRole>()

       services.AddAuthentication().AddMicrosoftAccount(options => 
                options.ClientId = Configuration["Authentication:Microsoft:ApplicationId"];
                options.ClientSecret = Configuration["Authentication:Microsoft:Password"];

                .AddRazorPagesOptions(options =>
         services.AddSingleton<IEmailSender, EmailSender>();
If you want to know more about setting up authentication, the official Microsoft article can also be referred.  
We are almost there. Save your application and click on Login button. You will notice that the Microsoft button is appearing on the right side. Click on that, provide your Hotmail credentials and on successful login you will land upon below screen:

On click of yes, below screen will be shown:

Quickly click on register and see the magic. You will notice that you are now logged in with your Hotmail id as shown below:

Whatever we did can also be done through a guided process which we came across during our configuration process in the form of a hyperlink. Additionally, you can also follow this link.
Hope you enjoyed learning.

Sunday, July 15, 2018

Received C# Corner MVP award

Today I’m so happy and excited to share with you all that I’ve received the Most valuable Professional (MVP) award from C# Corner for the second time. Last week, I received an email that I’ve been awarded this esteemed award for my community contributions.

Wednesday, July 4, 2018

Authentication in layman terms

Recently I met one of my readers and he asked me what is authentication and why is it required in very simple terms. So, here is the post.

What is Authentication?
To understand the fundamentals of authentication, let's begin by taking an easy example. You are working on some file and now you want to share that file to a person named XYZ over OneDrive. So, the purpose of authentication in this case is to make sure that only XYZ can access that document.

How to achieve it?
It can be achieved by setting up the authentication system and this system will tell who all can access this file based on some predefined rules. In our case, the rule is simple - none except XYZ should be able to access the file.

How verification happens?
Entire verification activity solely depends on our authentication system. When I'm saying authentication system, it means it is nothing but a piece of software written by someone. Now how will this piece of software validate the incoming user whether it is XYZ, ABC or someone else?

The most popular way to accomplish this is by using the login form wherein user will enter its identity in the form of login details.

Let's go in a bit formal way. 
Authentication is a process of identifying an entity using challenge response pattern.

Are Authentication and Identification same?
Not really. Authentication deals with only offering the challenge to the user, which is a login form in our case, whereas Identification deals with matching user claims, which can be name, DoB, etc.

Hope you got a fleeting idea on what is an authentication system. Happy learning!

Tuesday, May 15, 2018

Setting up Two-Factor Authentication in ASP.NET Core 2.0

In this article, I’m going to write bit about security aspects in ASP.Net Core 2.0.

Whenever you create a new ASP.NET Core application, you must notice that there is an option on dialog with a button captioned as Change Authentication and once you click on that, you will land upon a dialog having below 4 options as shown below:


I’ll discuss about each of these options in detail but as of now, to get started, let’s take a high-level idea about these
  • No Authentication – which means application is completely anonymous and open for everyone to access it.
  • Individual User Accounts – it uses local database for storing the information related to user.
  • Work or School Accounts – it means application will work with Office365, Active Directory, support for cloud, etc..
  • Windows Authentication – For internet application and uses IIS capabilities to know who has logged in.
Here I’ll be choosing my option as ‘Individual User Accounts’ which is very easy, simplest as well as common too, with sub option chosen as ‘Store user accounts in-app’.  
Once you clicked OK, you will notice that ASP.NET Core has added the required middleware in ConfigureServices method with a default token provider, as shown below:
  public void ConfigureServices(IServiceCollection services)

            services.AddDbContext<ApplicationDbContext>(options =>


            services.AddIdentity<ApplicationUser, IdentityRole>()




                .AddRazorPagesOptions(options =>





            services.AddSingleton<IEmailSender, EmailSender>();

And in Configure method, same is added to the HTTP request pipeline by calling UseAuthentication method as shown below:
   public void Configure(IApplicationBuilder app, IHostingEnvironment env)

         if (env.IsDevelopment())








Is middleware configuration sequencing matters?

One important thing to notice in above code snippet is the sequence in which middleware are configured. app.UserAuthentication is called after app.StaticFiles, which means we don’t want any of our static contents to be authenticated before rendering them on to the browser.

Are you thinking, why so? Well, let’s understand this with a most common example of Login page.
Login page, which usually has static contents like css, image, etc. If we will shuffle the sequence of both the statements, then Login page will never ever come until user is authenticated. Now if user is already authenticated, then why do we need Login page. Isn’t it an interesting analogy?

What happen on click of Register?

 Now quickly run the application and click on Register and register yourself as shown below:

Once you populated the details and click on Register, you will land upon below page: 

Nothing to worry.

This is the expected behaviour because our identity data is not stored anywhere. So, we have to create the required tables and for that we can use local SQL Express database. This can be done quickly by pressing a button Apply Migrations as shown in above screenshot. Once button is pressed, just refresh your page and you would be happy to see the web page with your email id and Log out option in top right corner as shown below:



Configuring the registered data

Let’s say now if we want to modify our existing authentication details. So, to do that, one can click on mail id shown on top right corner of the web page and that will land upon below screen:







So, in above screen, we can change the registered email id, password and can also configure two-factor authentication.

Setting up two-factor authentication

Once you selected Two-factor authentication in above screen, you will be asked to add authenticator app as shown below:


Once the button is clicked, we will be taken to a page which will tell us that use the given key davi e4jo yiyt kmkz gtn5 jdek jmmb jpl5 as a password. Please note, this is the key generated for me. For you, it would be different one.
But typing this key manually in a phone could be very tedious process. Isn’t it?

So, other way to get the same information on phone is by using the QR code. You can also see a hyperlink which will take you to a very nice documentation explaining about the steps on how to proceed. 

Here we have to use JavaScript library for QR code generation. So, let’s quickly add that to our application under folder wwwroot/lib/qrCode.

Next is to call the method which will generate the QR code for us. Go to EnableAuthenticator.cshtml and update @section Scripts with below code:
    @section Scripts {

    @await Html.PartialAsync("_ValidationScriptsPartial")

    <script type="text/javascript" src="~/lib/qrCode/qrcode.js"></script>

    <script type="text/javascript">

     new QRCode(document.getElementById("qrCode"),

                text: "@Html.Raw(Model.AuthenticatorUri)",

                width: 150,

                height: 150



Make sure that path of qrcode.js is mentioned correctly. We are almost done. Now quickly launch the application and navigate back to Two-factor authentication tab. You will notice that nice QR code is ready for your scan as shown below:

Using Test Online Authenticator App

Now we have setup the two-factor authentication. In order to verify if it’s working correctly or not, we can use online authenticator app from URL: https://gauth.apps.gbraad.nl/.

Steps to use this application are: 
Give some account name and give your key as a secret key and press Add. As soon as you will click on Add, some 6-digit number will be generated as shown below:

This 6-digit number we will use to verify our authentication as shown below:


Quickly click on Verify button and we are done with setting up our 2FA as shown below:


Using Recovery Codes

In previous screenshot, you must have seen that some numbers are displayed in red color. Those numbers are called recovery code which are very useful in case if you lose your phone or say you got a new phone. One should keep these keys in some secure place. Let’s have a look on how to use these recovery codes.
Launch your application and supply user name password. On supplying correct details, you will be asked for Authentication Key as shown below:

Now click on the given hyperlink ‘log in with recovery code.’ which will further ask you to enter your recovery code. Pick any one of the recovery keys which were generated for you and enter in the given text box as shown below:

As soon as you will click on Login button, you will see that you are logged in. Aren’t you happy, even after losing your phone 😉.
Now 2FA is perfectly set up, you can go and reset your recovery code anytime.

Please note, any recovery code which were generated can be use only once but one can generate recovery code any number of times.

Hope you enjoyed learning!