Skip to main content
Login Register
Code2night
  • Home
  • Blog Archive
  • Learn
    • Tutorials
    • Videos
  • Interview Q&A
  • Resources
    • Cheatsheets
    • Tech Comparisons
  • Languages
    • Angular Angular js ASP.NET Asp.net Core ASP.NET Core, C# ASP.NET MVC ASP.NET Web Forms C C# C#, ASP.NET Core, Dapper
      C#, ASP.NET Core, Dapper, Entity Framework DotNet General Web Development HTML, CSS HTML/CSS Java JavaScript JavaScript, HTML, CSS JavaScript, Node.js Node.js
      Python Python 3.11, Pandas, SQL Python 3.11, SQL Python 3.11, SQLAlchemy Python 3.11, SQLAlchemy, SQL Python 3.11, SQLite React Security SQL Server TypeScript
  • Post Blog
  • Tools
    • Beautifiers
      JSON Beautifier HTML Beautifier XML Beautifier CSS Beautifier JS Beautifier SQL Formatter
      Dev Utilities
      JWT Decoder Regex Tester Diff Checker Cron Explainer String Escape Hash Generator Password Generator
      Converters
      Base64 Encode/Decode URL Encoder/Decoder JSON to CSV CSV to JSON JSON to TypeScript Markdown to HTML Number Base Converter Timestamp Converter Case Converter
      Generators
      UUID / GUID Generator Lorem Ipsum QR Code Generator Meta Tag Generator
      Image Tools
      Image Converter Image Resizer Image Compressor Image to Base64 PNG to ICO Background Remover Color Picker
      Text & Content
      Word Counter PDF Editor
      SEO & Web
      SEO Analyzer URL Checker World Clock
  1. Home
  2. Blog
  3. ASP.NET Core
  4. Integrating LinkedIn OAuth in ASP.NET Core for Professional Login

Integrating LinkedIn OAuth in ASP.NET Core for Professional Login

Date- May 01,2026 86
linkedin oauth

Overview

OAuth is an open standard for access delegation commonly used as a way to grant websites or applications limited access to users' information without exposing passwords. The integration of LinkedIn OAuth allows developers to authenticate users via their LinkedIn accounts, validating their identity while providing a seamless login experience. This is particularly advantageous in professional contexts where users may prefer logging in with their existing LinkedIn profiles rather than creating new accounts.

Real-world use cases of LinkedIn OAuth integration include job portals, professional networking platforms, and applications that require professional credentials for access. For example, a recruitment platform may utilize LinkedIn OAuth to allow recruiters to log in and fetch candidate profiles directly from LinkedIn, enhancing user experience and reducing friction in the onboarding process.

Prerequisites

  • ASP.NET Core SDK: Ensure you have the latest version of the ASP.NET Core SDK installed on your machine.
  • LinkedIn Developer Account: Create a LinkedIn developer account to set up your application and obtain API keys.
  • Basic Knowledge of C#: Familiarity with C# programming and ASP.NET Core framework is essential.
  • NuGet Package Manager: You will need to manage dependencies using NuGet for OAuth packages.

Setting Up LinkedIn Application

Before integrating LinkedIn OAuth into your ASP.NET Core application, you need to create a LinkedIn application. This process involves registering your application on the LinkedIn Developer Portal, which provides you with the necessary credentials such as the Client ID and Client Secret.

To create a LinkedIn application:

  1. Visit the LinkedIn Developer Portal.
  2. Click on 'Create App' and fill in the required details such as the app name, company, and description.
  3. Once created, navigate to the 'Auth' tab to configure your application's authentication settings.
  4. Set the Redirect URLs to point to your ASP.NET Core application endpoint that will handle OAuth callbacks, e.g., `https://localhost:5001/signin-linkedin`.

Configuring ASP.NET Core for LinkedIn OAuth

In your ASP.NET Core application, you need to configure the authentication services to use LinkedIn as an external login provider. This is achieved by adding the necessary packages and setting up the authentication middleware.

public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthentication(options =>
    {
        options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        options.DefaultChallengeScheme = "LinkedIn";
    })
    .AddCookie()
    .AddOAuth("LinkedIn", options =>
    {
        options.ClientId = "YOUR_CLIENT_ID";
        options.ClientSecret = "YOUR_CLIENT_SECRET";
        options.CallbackPath = new PathString("/signin-linkedin");

        options.AuthorizationEndpoint = "https://www.linkedin.com/oauth/v2/authorization";
        options.TokenEndpoint = "https://www.linkedin.com/oauth/v2/accessToken";
        options.UserInformationEndpoint = "https://api.linkedin.com/v2/me";

        options.ClaimActions.MapJsonKey(ClaimTypes.NameIdentifier, "id");
        options.ClaimActions.MapJsonKey(ClaimTypes.Name, "localizedFirstName");
        options.ClaimActions.MapJsonKey("family_name", "localizedLastName");
        options.ClaimActions.MapJsonKey(ClaimTypes.Email, "elements[0].handle~.emailAddress");

        options.Events = new OAuthEvents
        {
            OnCreatingTicket = async context =>
            {
                var request = new HttpRequestMessage(HttpMethod.Get, context.UserInformationEndpoint);
                request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", context.AccessToken);

                var response = await context.Backchannel.SendAsync(request, context.HttpContext.RequestAborted);
                if (response.IsSuccessStatusCode)
                {
                    var user = JObject.Parse(await response.Content.ReadAsStringAsync());
                    context.Identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user["id"]?.ToString()));
                    context.Identity.AddClaim(new Claim(ClaimTypes.Name, user["localizedFirstName"]?.ToString()));
                    context.Identity.AddClaim(new Claim(ClaimTypes.Surname, user["localizedLastName"]?.ToString()));
                    context.Identity.AddClaim(new Claim(ClaimTypes.Email, user["elements"]?[0]?["handle~"]?["emailAddress"]?.ToString()));
                }
            }
        };
    });
}

This code snippet configures the ASP.NET Core authentication middleware:

  • Default Scheme: Sets the default authentication scheme to cookies and the challenge scheme to LinkedIn.
  • AddOAuth: Configures LinkedIn OAuth with the necessary credentials and endpoints.
  • ClaimActions: Maps JSON keys from LinkedIn's response to claims in the user's identity.
  • OnCreatingTicket: An event that is triggered after receiving the authentication token and before creating the ticket. It makes a request to LinkedIn's User Information Endpoint to fetch user details.

Redirecting Users to LinkedIn for Authentication

To initiate the LinkedIn OAuth flow, you need to redirect users to LinkedIn's authorization endpoint. This is typically done in a controller action.

[HttpGet]
[Route("/login/linkedin")]
public IActionResult LoginLinkedIn() 
{
    var redirectUrl = Url.Action("LinkedInResponse", "Account", null, Request.Scheme);
    var properties = new AuthenticationProperties { RedirectUri = redirectUrl };
    return Challenge(properties, "LinkedIn");
}

The `LoginLinkedIn` action does the following:

  • RedirectUri: Constructs the redirect URL that LinkedIn will send users back to after authentication.
  • Challenge: Triggers the OAuth challenge, sending users to LinkedIn for authentication.

Handling the Callback from LinkedIn

Once users authenticate, LinkedIn redirects them back to your application. You'll need to handle this callback to finalize the login process.

[HttpGet]
[Route("/signin-linkedin")]
public async Task LinkedInResponse() 
{
    var result = await HttpContext.AuthenticateAsync("LinkedIn");
    if (!result.Succeeded)
    {
        return RedirectToAction("Login");
    }

    // Sign in the user with the claims
    var claims = result.Principal.Claims.ToList();
    var claimsIdentity = new ClaimsIdentity(claims, "LinkedIn");
    await HttpContext.SignInAsync(new ClaimsPrincipal(claimsIdentity));

    return RedirectToAction("Index", "Home");
}

This code handles the callback:

  • AuthenticateAsync: Attempts to authenticate the user using the LinkedIn scheme.
  • ClaimsIdentity: Creates a new identity from the claims returned by LinkedIn.
  • SignInAsync: Signs in the user to the application with the created claims principal.

Edge Cases & Gotchas

When integrating LinkedIn OAuth, developers may encounter specific pitfalls that can cause unexpected behaviors. Below are some common issues and their resolutions.

Incorrect Redirect URI

One of the most common issues is setting an incorrect redirect URI in the LinkedIn app settings. Ensure that the redirect URI specified in your LinkedIn application matches the one used in your ASP.NET Core application. Any mismatch will result in authentication failure.

Scope Permissions

LinkedIn has specific permissions (scopes) that need to be requested for accessing user data. If your application does not request the necessary scopes, you may not receive the required information. Always verify that your application requests the right scopes according to your needs.

Performance & Best Practices

When implementing OAuth integrations, there are several best practices to enhance performance and security:

  • Use HTTPS: Always use HTTPS for your application to protect sensitive data transmitted over the network.
  • Limit Scopes: Request only the necessary permissions to minimize the exposure of user data.
  • Handle Token Expiry: Implement logic to handle token expiry and refresh tokens when necessary.
  • Logging and Monitoring: Log OAuth events and monitor for unusual activities to detect potential security breaches.

Real-World Scenario: A Professional Networking Application

To illustrate the concepts discussed, let’s create a simple professional networking application that allows users to log in via LinkedIn and view their profile information.

Step 1: Create a New ASP.NET Core Application

dotnet new mvc -n LinkedInAuthExample
cd LinkedInAuthExample

Step 2: Add Required NuGet Packages

dotnet add package Microsoft.AspNetCore.Authentication.OAuth
dotnet add package Microsoft.AspNetCore.Authentication.Cookies

Step 3: Update Startup.cs

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        // Add authentication configuration here
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        // Configure the HTTP request pipeline here
    }
}

Step 4: Create Views and Controllers

public class AccountController : Controller
{
    // Add LoginLinkedIn and LinkedInResponse actions here
}

This simple application structure will allow users to log in using LinkedIn and retrieve their profile data. Complete the application by creating views that display user information fetched from LinkedIn, enhancing the user experience.

Conclusion

  • OAuth Integration: LinkedIn OAuth integration enables seamless user authentication while protecting user credentials.
  • Configuration: Proper configuration of the authentication middleware is crucial for successful integration.
  • Edge Cases: Be aware of common pitfalls like redirect URI mismatches and scope permissions to avoid integration issues.
  • Best Practices: Implement best practices in security and performance to enhance user experience and application reliability.

S
Shubham Saini
Programming author at Code2Night — sharing tutorials on ASP.NET, C#, and more.
View all posts →

Related Articles

Implementing GitHub OAuth Integration in ASP.NET Core for Seamless User Login
Apr 30, 2026
Implementing Custom Middleware in ASP.NET Core: A Comprehensive Guide
Mar 24, 2026
SignalR Integration in ASP.NET Core: Building a Real-Time WebSocket Chat Application
May 17, 2026
Integrating Azure OpenAI Service with ASP.NET Core: A Comprehensive Guide
May 04, 2026
Previous in ASP.NET Core
Comprehensive Guide to Okta SSO Integration in ASP.NET Core Using…
Next in ASP.NET Core
Cloudinary Image Upload and Transformation in ASP.NET Core
Buy me a pizza

Comments

🔥 Trending This Month

  • 1
    Complete Guide to C++ Classes: Explained with Examples 4,212 views
  • 2
    Implementing an End-to-End CI/CD Pipeline for ASP.NET Core… 367 views
  • 3
    Create Database and CRUD operation 3,388 views
  • 4
    Mastering TypeScript Utility Types: Partial, Required, Rea… 675 views
  • 5
    Responsive Slick Slider 23,373 views
  • 6
    Integrating Azure Cognitive Search into ASP.NET Core Appli… 156 views
  • 7
    Integrating Anthropic Claude API in ASP.NET Core for AI Ch… 141 views
  • 8
    How to get fcm server key 4,849 views

On this page

🎯

Interview Prep

Ace your ASP.NET Core interview with curated Q&As for all levels.

View ASP.NET Core Interview Q&As

More in ASP.NET Core

  • How to Encrypt and Decrypt Password in Asp.Net 26191 views
  • Exception Handling Asp.Net Core 20938 views
  • HTTP Error 500.31 Failed to load ASP NET Core runtime 20391 views
  • How to implement Paypal in Asp.Net Core 19753 views
  • Task Scheduler in Asp.Net core 17705 views
View all ASP.NET Core posts →

Tags

AspNet C# programming AspNet MVC c programming AspNet Core C software development tutorial MVC memory management Paypal coding coding best practices data structures programming tutorial tutorials object oriented programming Slick Slider StripeNet
Free Download for Youtube Subscribers!

First click on Subscribe Now and then subscribe the channel and come back here.
Then Click on "Verify and Download" button for download link

Subscribe Now | 1770
Download
Support Us....!

Please Subscribe to support us

Thank you for Downloading....!

Please Subscribe to support us

Continue with Downloading
Be a Member
Join Us On Whatsapp
Code2Night

A community platform for sharing programming knowledge, tutorials, and blogs. Learn, write, and grow with developers worldwide.

Panipat, Haryana, India
info@code2night.com
Quick Links
  • Home
  • Blog Archive
  • Tutorials
  • About Us
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Guest Posts
  • SEO Analyzer
Dev Tools
  • JSON Beautifier
  • HTML Beautifier
  • CSS Beautifier
  • JS Beautifier
  • SQL Formatter
  • Diff Checker
  • Regex Tester
  • Markdown to HTML
  • Word Counter
More Tools
  • Password Generator
  • QR Code Generator
  • Hash Generator
  • Base64 Encoder
  • JWT Decoder
  • UUID Generator
  • Image Converter
  • PNG to ICO
  • SEO Analyzer
By Language
  • Angular
  • Angular js
  • ASP.NET
  • Asp.net Core
  • ASP.NET Core, C#
  • ASP.NET MVC
  • ASP.NET Web Forms
  • C
  • C#
  • C#, ASP.NET Core, Dapper
  • C#, ASP.NET Core, Dapper, Entity Framework
  • DotNet
  • General Web Development
  • HTML, CSS
  • HTML/CSS
  • Java
  • JavaScript
  • JavaScript, HTML, CSS
  • JavaScript, Node.js
  • Node.js
  • Python
  • Python 3.11, Pandas, SQL
  • Python 3.11, SQL
  • Python 3.11, SQLAlchemy
  • Python 3.11, SQLAlchemy, SQL
  • Python 3.11, SQLite
  • React
  • Security
  • SQL Server
  • TypeScript
© 2026 Code2Night. All Rights Reserved.
Made with for developers  |  Privacy  ·  Terms
Translate Page
We use cookies to improve your experience and analyze site traffic. By clicking Accept, you consent to our use of cookies. Privacy Policy
Accessibility
Text size
High contrast
Grayscale
Dyslexia font
Highlight links
Pause animations
Large cursor