Open Visual Studio and select File >> New >> Project. After selecting the project, a “New Project” dialog will open.
Navigate to Tools >> Nuget Package Manager >> Package Manager Console.
It will open the Package Manager Console. Put in Update-Database command and hit enter. This will update the database using Entity Framework Code First Migrations.
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 My Applications page similar to the one shown below.
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.
If you use the URL format as www.demopage.com, you will get an error “Please enter a valid URL.” Always use URL format as http://demopage.com. Refer to the image below.
Do keep in mind that all the fields of this form are required so you need to provide appropriate value to all of them. Once you have furnished all the details click on 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 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 Press on Add button adjacent to it to add the value. Refer to the image below
We will be using a third party Nuget package AspNet.Security.OAuth.LinkedIn to implement LinkedIn authentication in our Web app. Open 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 Client ID and Client Secret field values in our application. We will use Secret Manager tool for this purpose. The Secret Manager tool is a project tool that can be used to store secrets such as password, API Key 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 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 Startup.cs file and put the following code into ConfigureServices method.
services.AddAuthentication().AddLinkedIn(options => { options.ClientId = Configuration["Authentication:LinkedIn:ClientId"]; options.ClientSecret = Configuration["Authentication:LinkedIn:ClientSecret"]; options.Events= new OAuthEvents() { OnRemoteFailure = loginFailureHandler => { var authProperties = options.StateDataFormat.Unprotect(loginFailureHandler.Request.Query["state"]); loginFailureHandler.Response.Redirect("/Account/login"); loginFailureHandler.HandleResponse(); return Task.FromResult(0); } }; });
In this code section, we are reading Client ID and Client Secret values from secrets.json file for the authentication purpose. We are also handling the event of “OnRemoteFailure” in this code section. Hence, if the user deny the access to his LinkedIn account, then he will be redirected back to Login page.
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; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Authentication.OAuth; 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"]; options.Events= new OAuthEvents() { OnRemoteFailure = loginFailureHandler => { var authProperties = options.StateDataFormat.Unprotect(loginFailureHandler.Request.Query["state"]); loginFailureHandler.Response.Redirect("/Account/login"); loginFailureHandler.HandleResponse(); return Task.FromResult(0); } }; }); // 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.
Launch the application and click Login in the top right corner of the homepage.
You will be redirected to http://localhost:52676/Account/Login page, where you can see the option to login using LinkedIn on the right side of page.
Clicking on LinkedIn button will take you to 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 Allow access button. The application will take 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.
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 secrets.json file contains dummy values. Hence replace the values with the keys of your LinkedIn app before executing it.
You can also find this article at C# Corner.
You can check my other articles on ASP .NET Core here
Introduction Blazor is a .NET web framework that allows us to create client-side applications using…
Introduction In this article, we are going to create a sudoku solver with the help…
Introduction In this article, we will learn how to implement Azure serverless with Blazor web…
Introduction Angular is an open-source framework that allows us to create applications for multiple platforms…
Introduction In this article, we will create an optical character recognition (OCR) application using Angular…
Introduction In this article, we will create an optical character recognition (OCR) application using Blazor…
View Comments
This does not work. Probably since LinkedIn changed their auth to 2.0 on May 1st 2019
Any way to merge previous email login with social media login. I tried the FB login and it won't let me login with an existing account with the same email.