Section 5 of 6

OAuth 2.0 & OpenID Connect

🎯 What You'll Learn

  • What is OAuth 2.0
  • What is OpenID Connect
  • OAuth vs OpenID Connect
  • OAuth flows
  • Using OpenID Connect

What is OAuth 2.0?

OAuth 2.0 is an authorization framework that allows third-party applications to access user resources without sharing passwords.

💡 Key Concept

OAuth 2.0 = Authorization (what you can access)
OpenID Connect = Authentication (who you are) built on OAuth 2.0

What is OpenID Connect?

OpenID Connect (OIDC) is an identity layer built on top of OAuth 2.0. It adds authentication to OAuth's authorization.

Aspect OAuth 2.0 OpenID Connect
Purpose Authorization Authentication + Authorization
Question What can I access? Who am I?
Token Access Token ID Token + Access Token
Use Case API access Single Sign-On (SSO)

OAuth 2.0 Flows

1. Authorization Code Flow

Most secure flow for web applications.

  1. User clicks "Login with Google"
  2. Redirected to Google login
  3. User authenticates
  4. Google redirects back with authorization code
  5. App exchanges code for access token

2. Client Credentials Flow

For server-to-server authentication (no user involved).

3. Implicit Flow

Legacy flow for SPAs (not recommended, use Authorization Code + PKCE instead).

Using OpenID Connect

1. Install Package

Install NuGet Package Bash
dotnet add package Microsoft.AspNetCore.Authentication.OpenIdConnect

2. Configure OpenID Connect

Program.cs C#
builder.Services.AddAuthentication(options =>
{
    options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddCookie()
.AddOpenIdConnect(options =>
{
    options.Authority = "https://accounts.google.com";
    options.ClientId = builder.Configuration["Google:ClientId"];
    options.ClientSecret = builder.Configuration["Google:ClientSecret"];
    options.ResponseType = "code";
    options.SaveTokens = true;
    options.Scope.Add("openid");
    options.Scope.Add("profile");
    options.Scope.Add("email");
});

Key Takeaways

  • OAuth 2.0: Authorization framework
  • OpenID Connect: Authentication layer on OAuth 2.0
  • Authorization Code Flow: Most secure for web apps
  • ID Token: Contains user identity information
  • Access Token: Used to access protected resources
  • Use cases: SSO, social login, API access