Swiftorial Logo
Home
Swift Lessons
Tutorials
Learn More
Career
Resources

Using OpenID Connect in .NET Applications

Introduction

OpenID Connect (OIDC) is a simple identity layer on top of the OAuth 2.0 protocol, which allows clients to verify the identity of the end-user based on the authentication performed by an authorization server. This tutorial will guide you through implementing OpenID Connect authentication in a .NET application.

Step 1: Setting up Your .NET Project

First, create a new .NET project. You can do this using the .NET CLI or Visual Studio.

// Using .NET CLI
dotnet new mvc -n OpenIDConnectExample

Step 2: Adding Required Packages

To use OpenID Connect in your .NET project, you will need to add the appropriate packages. The most common library used for OpenID Connect authentication in .NET is Microsoft's own authentication library.

// Using .NET CLI to add packages
dotnet add package Microsoft.AspNetCore.Authentication
dotnet add package Microsoft.AspNetCore.Authentication.OpenIdConnect

Step 3: Configuring OpenID Connect in Startup.cs

Next, configure the OpenID Connect authentication in your Startup.cs file. This involves setting up the authentication services and configuring the OpenID Connect provider.

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllersWithViews();

    services.AddAuthentication(options =>
    {
        options.DefaultAuthenticateScheme = "Cookies";
        options.DefaultChallengeScheme = "oidc";
    })
    .AddCookie("Cookies")
    .AddOpenIdConnect("oidc", options =>
    {
        options.Authority = "https://your-identity-server";
        options.ClientId = "your-client-id";
        options.ClientSecret = "your-client-secret";
        options.ResponseType = "code";

        options.Scope.Add("profile");
        options.Scope.Add("email");

        options.SaveTokens = true;

        options.TokenValidationParameters = new TokenValidationParameters
        {
            NameClaimType = "name",
            RoleClaimType = "role"
        };
    });
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
        app.UseHsts();
    }

    app.UseHttpsRedirection();
    app.UseStaticFiles();

    app.UseRouting();

    app.UseAuthentication();
    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");
    });
}

Step 4: Creating the Login View and Controller

Create a view and controller for handling the login process.

// HomeController.cs
public class HomeController : Controller
{
    public IActionResult Index()
    {
        return View();
    }

    public IActionResult Login()
    {
        return Challenge(new AuthenticationProperties { RedirectUri = "/" }, "oidc");
    }

    public async Task Logout()
    {
        await HttpContext.SignOutAsync("Cookies");
        await HttpContext.SignOutAsync("oidc");
        return RedirectToAction("Index");
    }
}

// Index.cshtml
<h2>Welcome</h2>
<p><a href="/Home/Login">Log in with OpenID Connect</a></p>

Step 5: Testing the Authentication

Run your application and navigate to the login page. Clicking the login link should redirect you to the OpenID Connect provider's authorization page. After logging in, you should be redirected back to your application with the identity tokens saved for further use.

Conclusion

In this tutorial, we covered the basic setup for OpenID Connect authentication in a .NET application. We configured the necessary packages, set up the authentication service, and created a simple login flow. This should give you a solid foundation to further explore and implement OpenID Connect authentication in your .NET projects.