OAuth2 Authentication in C#: A Simple Guide

OAuth2 (Open Authorization 2.0) is a protocol that lets apps access user data without needing to
handle passwords directly. Think of it as a way to let users sign in to your app using their existing
Google, Facebook, or Microsoft accounts—without giving you their password.

In this post, we’ll break down what OAuth2 is and how you can set it up in a C# ASP.NET Core
application using Google OAuth as an example. Ready? Let’s dive in!

What is OAuth2?

At a high level, OAuth2 is a framework that allows a user to authorize an app to access their data
(like emails or profile information) without exposing their login credentials. Instead of handing over
a password, the app gets a token that allows it to make requests to access the user’s info.

OAuth2 has several types of “grants” (ways to get that token), but the most common one for web
apps is the Authorization Code Grant. This is where users log in, give permission, and the app gets
a token to access their data.

Setting Up OAuth2 in a C# ASP.NET Core App

Now that we know what OAuth2 is, let’s walk through how to set it up in an ASP.NET Core app.
We’ll use Google OAuth for this example, but the steps will work for other providers like Microsoft
or Facebook too!

1. Register Your App

Before we start coding, you’ll need to register your app with the OAuth2 provider (Google, in this case):

  • Go to the Google Developer Console: https://console.developers.google.com/
  • Create a new project.
  • Enable the Google+ API or any other API you want to access.
  • Create OAuth 2.0 credentials to get your Client ID and Client Secret. Keep these safe—they’ll be used in the code to authenticate your app.

2. Install the Required Packages

Next, let’s install the necessary packages to handle OAuth2 in your project. You can do this via the Package Manager Console:

1
2
Install-Package Microsoft.AspNetCore.Authentication.OAuth
Install-Package Microsoft.AspNetCore.Authentication.Google

These packages let ASP.NET Core talk to Google (or another OAuth2 provider) for authentication.

3. Configure OAuth2 in Startup.cs

In your Startup.cs file, we need to set up Google OAuth2 authentication. Here’s how:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public void ConfigureServices(IServiceCollection services)
{
// Add authentication services
services.AddAuthentication(options =>
{
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = GoogleDefaults.AuthenticationScheme;
})
.AddCookie() // Cookie-based authentication
.AddGoogle(options =>
{
options.ClientId = Configuration["Google:ClientId"]; // Use your Client ID
options.ClientSecret = Configuration["Google:ClientSecret"]; // Use your Client Secret
options.Scope.Add("email"); // Request email access
options.SaveTokens = true; // Save the access token for later
});

services.AddMvc();
}

Here’s what’s happening:

  • AddAuthentication: We tell the app how to handle authentication. In this case, we use cookies to store the login session and Google for OAuth.
  • AddGoogle: We set up Google OAuth using the credentials we got earlier.
  • Scope: We ask for permission to access the user’s email (you can add more scopes if you need other data).

4. Set Up the Authentication Flow

Now we’ll create some actions in our controller to handle logging in and logging out:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}

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

public async Task<IActionResult> Logout()
{
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
return RedirectToAction(nameof(Index));
}

public IActionResult Privacy()
{
return View();
}
}

Here’s the breakdown:

  • Login: When the user clicks “Login,” they’ll be redirected to Google’s login page. Once they log in and grant permissions, they’ll be sent back to your app.
  • Logout: Logs the user out of the app and redirects them to the homepage.

5. Get User Info with Access Tokens

After the user logs in, we get an access token. This token lets your app make requests to Google’s APIs on the user’s behalf. Here’s how to fetch the token and get the user’s profile info:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public async Task<IActionResult> Profile()
{
var accessToken = await HttpContext.GetTokenAsync("access_token");
var userInfo = await GetGoogleUserInfo(accessToken); // Use the token to get user data

return View(userInfo);
}

private async Task<UserInfo> GetGoogleUserInfo(string accessToken)
{
var client = new HttpClient();
var response = await client.GetAsync($"https://www.googleapis.com/oauth2/v2/userinfo?access_token={accessToken}");
response.EnsureSuccessStatusCode();
var content = await response.Content.ReadAsStringAsync();
var userInfo = JsonConvert.DeserializeObject<UserInfo>(content);
return userInfo;
}
  • GetTokenAsync: We retrieve the access token.
  • GetGoogleUserInfo: We call Google’s userinfo API to fetch the user’s profile info (like name and email).

6. Handling Token Expiry

OAuth2 tokens aren’t forever. They expire after a while, but the good news is that ASP.NET Core will automatically handle refreshing tokens for you if you set SaveTokens = true when configuring Google authentication.

However, if you need to manually refresh the token, you can use the refresh token you receive along with the access token. That’s a bit more involved, but it’s something to keep in mind as your app grows.

Conclusion

OAuth2 is a great way to handle authentication without needing to deal with sensitive user passwords. Instead of storing passwords, you get a token that lets you access data securely. In this post, we’ve gone through how to integrate Google OAuth2 authentication into your C# ASP.NET Core app, but the steps are similar for other OAuth2 providers like Microsoft, Facebook, or any custom provider.

A few key takeaways:

  • OAuth2 lets users log in securely using accounts they already have (like Google or Facebook).
  • After logging in, the app gets an access token to make API calls on behalf of the user.
  • Don’t forget about token expiry—refresh tokens are your friend!

That’s it! You’re now ready to start implementing OAuth2 in your own apps. 🚀


Let me know if you need any more examples or explanations. Happy coding!