Swiftorial Logo
Home
Swift Lessons
Tutorials
Learn More
Career
Resources

Using OAuth for Authentication in .NET

Introduction

OAuth is an open standard for access delegation commonly used as a way to grant websites or applications limited access to a user's information without exposing passwords. This tutorial will guide you through implementing OAuth 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 OAuthExample

Step 2: Adding Required Packages

To use OAuth in your .NET project, you will need to add the appropriate packages. The most common library used for OAuth 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.OAuth

Step 3: Configuring OAuth in Startup.cs

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

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

    services.AddAuthentication(options =>
    {
        options.DefaultAuthenticateScheme = "Cookies";
        options.DefaultChallengeScheme = "OAuthProvider";
    })
    .AddCookie("Cookies")
    .AddOAuth("OAuthProvider", options =>
    {
        options.ClientId = "your-client-id";
        options.ClientSecret = "your-client-secret";
        options.CallbackPath = new PathString("/signin-oauth");
        
        options.AuthorizationEndpoint = "https://provider.com/oauth/authorize";
        options.TokenEndpoint = "https://provider.com/oauth/token";
        options.UserInformationEndpoint = "https://provider.com/oauth/userinfo";
        
        options.SaveTokens = true;
        
        options.ClaimActions.MapJsonKey(ClaimTypes.NameIdentifier, "id");
        options.ClaimActions.MapJsonKey(ClaimTypes.Name, "name");
        options.ClaimActions.MapJsonKey(ClaimTypes.Email, "email");
        
        options.Events = new OAuthEvents
        {
            OnCreatingTicket = async context =>
            {
                var request = new HttpRequestMessage(HttpMethod.Get, context.Options.UserInformationEndpoint);
                request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", context.AccessToken);
                
                var response = await context.Backchannel.SendAsync(request, HttpCompletionOption.ResponseHeadersRead,
				context.HttpContext.RequestAborted);
                response.EnsureSuccessStatusCode();
                
                var user = JsonDocument.Parse(await response.Content.ReadAsStringAsync());
                context.RunClaimActions(user.RootElement);
            }
        };
    });
}

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 = "/" }, "OAuthProvider");
    }

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

// Index.cshtml
<h2>Welcome</h2>
<p><a href="/Home/Login">Log in with OAuth</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 OAuth provider's authorization page. After logging in, you should be redirected back to your application with access tokens saved for further use.

Conclusion

In this tutorial, we covered the basic setup for OAuth 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 OAuth authentication in your .NET projects.