Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Authentication Using LinkedIn In ASP.NET Core 2.0

DZone's Guide to

Authentication Using LinkedIn In ASP.NET Core 2.0

Interested in learning how to empower your web application's users to use their LinkedIn credentials to login? Read on to learn how for an ASP.NET Core app!

· Security Zone ·
Free Resource

Discover how to provide active runtime protection for your web applications from known and unknown vulnerabilities including Remote Code Execution Attacks.

Introduction

Sometimes, we want users to log in using their existing credentials from third-party applications, such as Facebook, Twitter, Google, LinkedIn, etc. In this article, we are going to look into the authentication of an ASP.NET Core app using a LinkedIn account.

Prerequisites

  • Install .NET Core 2.0.0 or above SDK from here.
  • Install the latest version of Visual Studio 2017 Community Edition from here.

Create MVC Web Application

Open Visual Studio and select File >> New >> Project. After selecting the project, a “New Project” dialog will open.

Select .NET Core inside the Visual C# menu from the left-hand panel. Then, select “ASP.NET Core Web Application” from the available project types. Set the name of the project as LinkdinAuth and press OK.

After clicking on OK, a new dialog will open asking to select the project template. You will see two drop-down menus at the top left of the template window. Select “.NET Core” and “ASP.NET Core 2.0” from these dropdowns.

Then, select the “Web application (Model-View-Controller)” template. Click on Change Authentication button; a “Change Authentication” dialog box will open. Select “Individual User Account” and click OK. Now click OK again to create the web app. Before running the application, we need to apply migrations to our app.

Navigate to Tools >> Nuget Package Manager >> Package Manager Console.

It will open the Package Manager Console. Put in the Update-Database command and hit enter. This will update the database using Entity Framework Code First Migrations.

Press F5 to run the application. You will see a home page as shown below. Note the URL from the browser address bar. In this case, the URL is http://localhost:52676/. We need this URL to configure our LinkedIn app which we will be doing in our next section.

Create a LinkedIn App

Navigate to https://www.linkedin.com/developer/apps and sign in using your LinkedIn account. If you do not have a LinkedIn account, you need to create one. You cannot proceed without a LinkedIn account. Once you have logged in, you will be redirected to the My Applications page similar to the one shown below.

Click on the Create Application button to navigate to the Create a New Application page. Here you need to fill in the details to create a new LinkedIn application.

  • Company Name: Give an appropriate name. Here we are using the name DemoCompany.
  • Application Name: This is the name of your LinkedIn application.

Important Note

Do not use the word “LinkedIn” in your product name. You will be prompted with an error, “The application name cannot contain LinkedIn” and you won’t be allowed to create the app. This means “LinkedinAuthDemo” is an invalid name. Refer to the below image.

  • Application Description: Give a proper description of your application.
  • Application Logo: You need to upload a logo for your application. If you do not have a logo just upload any image. Please provide your application's logo image, in PNG or JPEG format. The image must be square and at least 80 x 80 pixels, and no larger than 5 MB in size.
  • Application Use: Select an appropriate value from the drop-down.
  • Website URL: Provide the URL for your public website. For this tutorial, we will use a dummy URL http://demopage.com.

Important Note

If you use the URL format, www.demopage.com, you will get an error "Please enter a valid URL." Always use the URL format, http://demopage.com. Refer to the image below.

  • Business Email: Give your email id. If you do not want to provide your personal email id then you can also use any dummy email id, such as xyz@gmail.com
  • Business Phone: Provide your contact number. For this tutorial, I am using a dummy phone number, 123456789.

Do keep in mind that all the fields of this form are required so you need to provide an appropriate value to all of them. Once you have furnished all the details click on the Submit button. If there is no error in the form, your LinkedIn app will be created successfully and you will be redirected to the application homepage.

Here you see the Client ID and Client Secret fields in the Authentication Keys section. Take a note of these values as we will need them to configure LinkedIn authentication in our web app. In the Authorized Redirect URLs fields provide the base URL of your application with /signin-linkedin appended to it. For this tutorial, the URL will be http://localhost:52676/signin-linkedin. After entering the URL, click on the Add button adjacent to it to add the value. Refer to the image below:

Configure Web App to Use LinkedIn Authentication

We will be using a third-party Nuget package, AspNet.Security.OAuth.LinkedIn, to implement LinkedIn authentication in our web app. Open the NuGet package manager (Tools >> NuGet Package Manager >> Package Manager Console) and put in the following command. Hit enter to install it.

Install-Package AspNet.Security.OAuth.LinkedIn -Version 2.0.0-rc2-final

This NuGet package is maintained by aspnet-contrib. You can read more about this package here.

We need to store the Client ID and Client Secret field values in our application. We will use the Secret Manager tool for this purpose. The Secret Manager tool is a project tool that can be used to store secrets such as passwords, API keys, etc. for a .NET Core project during the development process. With the Secret Manager tool, we can associate app secrets with a specific project and can share them across multiple projects.

Open our web application once again and right-click the project in the Solution Explorer and select "Manage User Secrets" from the context menu.

A secrets.json file will open. Put the following code in it.

{  
  "Authentication:LinkedIn:ClientId": "Your ClientId here",  
  "Authentication:LinkedIn:ClientSecret": "Your ClientSecret here"  
} 

Now, open the Startup.cs file and put the following code into the ConfigureServices method.

services.AddAuthentication().AddLinkedIn(options =>  
{  
    options.ClientId = Configuration["Authentication:LinkedIn:ClientId"];  
    options.ClientSecret = Configuration["Authentication:LinkedIn:ClientSecret"];  
}); 

In this code section, we are reading the Client ID and Client Secret values from the secrets.json file for authentication purposes.

So, finally, Startup.cs will look like this.

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Threading.Tasks;  
using Microsoft.AspNetCore.Builder;  
using Microsoft.AspNetCore.Identity;  
using Microsoft.EntityFrameworkCore;  
using Microsoft.AspNetCore.Hosting;  
using Microsoft.Extensions.Configuration;  
using Microsoft.Extensions.DependencyInjection;  
using LinkdinAuth.Data;  
using LinkdinAuth.Models;  
using LinkdinAuth.Services;  

namespace LinkdinAuth  
{  
    public class Startup  
    {  
        public Startup(IConfiguration configuration)  
        {  
            Configuration = configuration;  
        }  

        public IConfiguration Configuration { get; }  

        // This method gets called by the runtime. Use this method to add services to the container.  
        public void ConfigureServices(IServiceCollection services)  
        {  
            services.AddDbContext<ApplicationDbContext>(options =>  
                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));  

            services.AddIdentity<ApplicationUser, IdentityRole>()  
                .AddEntityFrameworkStores<ApplicationDbContext>()  
                .AddDefaultTokenProviders();  

            services.AddAuthentication().AddLinkedIn(options =>  
            {  
                options.ClientId = Configuration["Authentication:LinkedIn:ClientId"];  
                options.ClientSecret = Configuration["Authentication:LinkedIn:ClientSecret"];  
            });  

            // Add application services.  
            services.AddTransient<IEmailSender, EmailSender>();  

            services.AddMvc();  
        }  

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.  
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)  
        {  
            if (env.IsDevelopment())  
            {  
                app.UseBrowserLink();  
                app.UseDeveloperExceptionPage();  
                app.UseDatabaseErrorPage();  
            }  
            else  
            {  
                app.UseExceptionHandler("/Home/Error");  
            }  

            app.UseStaticFiles();  

            app.UseAuthentication();  

            app.UseMvc(routes =>  
            {  
                routes.MapRoute(  
                    name: "default",  
                    template: "{controller=Home}/{action=Index}/{id?}");  
            });  
        }  
    }  
}  

And, with this, our application is ready.

Execution Demo

Launch the application and click login in the top right corner of the homepage.

You will be redirected to the http://localhost:52676/Account/Login page, where you can see the option to login using LinkedIn on the right side of the page.

Clicking on the LinkedIn button will take you to the LinkedIn authorization page where you will be asked to fill in your LinkedIn credentials and authorize the LinkedIn app to use your LinkedIn account.

Put in your LinkedIn credentials and click on the Allow access button. The application will take a few moments to authenticate your LinkedIn account and, upon successful authentication with LinkedIn, you will be redirected to a registration page inside our application where you need to fill in an email id to tag with your account.

Give an email id and click register. You will be redirected to the homepage again but this time you can also see your registered email id at the top right corner. Hence, we have successfully logged in to our ASP .NET Core application using LinkedIn.

Conclusion

We have successfully created a LinkedIn app and used it to authenticate our ASP.NET Core application.

You can get the source code from GitHub.

Please note that the secrets.json file contains dummy values. Hence, replace the values with the keys of your Google app before executing it.

You can check my other articles on ASP .NET Core here.

Find out how Waratek’s award-winning application security platform can improve the security of your new and legacy applications and platforms with no false positives, code changes or slowing your application.

Topics:
security ,authentication ,web application security

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}