Skip to main content

Lesson 4 of 8

Roles, Claims & External OAuth2 Providers

Roles group users by permission level (Admin, User, Manager). Claims are key-value facts about a user (subscription_tier: pro, tenant_id: xyz) that enable fine-grained authorization without extra DB lookups. OAuth2 enables 'Sign in with Google/GitHub' - Google handles the password.

25 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Role Management & OAuth2 External Login

Role Management & OAuth2 External Login
// ━━ Seed roles at startup ━━
public static class RoleSeeder
{
    public static async Task SeedAsync(IServiceProvider services)
    {
        using var scope = services.CreateScope();
        var roleManager = scope.ServiceProvider.GetRequiredService<RoleManager<IdentityRole>>();

        var roles = new[] { "Admin", "Manager", "User", "ReadOnly" };
        foreach (var role in roles)
        {
            if (!await roleManager.RoleExistsAsync(role))
                await roleManager.CreateAsync(new IdentityRole(role));
        }
    }
}

// Call after app.Build():
await RoleSeeder.SeedAsync(app.Services);

// ━━ Assign/remove roles ━━
await userManager.AddToRoleAsync(user, "Admin");
await userManager.RemoveFromRoleAsync(user, "User");
var userRoles = await userManager.GetRolesAsync(user); // ["Admin"]

// ━━ Custom claims on user ━━
await userManager.AddClaimAsync(user, new Claim("subscription_tier", "pro"));
await userManager.AddClaimAsync(user, new Claim("tenant_id", "acme-corp"));
// Claims are included in JWT via GenerateAccessToken claims list

// ━━ OAuth2 / Social Login - Google ━━
// dotnet add package Microsoft.AspNetCore.Authentication.Google
builder.Services
    .AddAuthentication()
    .AddGoogle(options =>
    {
        options.ClientId = builder.Configuration["Google:ClientId"]!;
        options.ClientSecret = builder.Configuration["Google:ClientSecret"]!;
        options.CallbackPath = "/api/auth/google-callback";
        options.Scope.Add("email");
        options.Scope.Add("profile");
    })
    .AddGitHub(options =>  // dotnet add package AspNet.Security.OAuth.GitHub
    {
        options.ClientId = builder.Configuration["GitHub:ClientId"]!;
        options.ClientSecret = builder.Configuration["GitHub:ClientSecret"]!;
        options.CallbackPath = "/api/auth/github-callback";
        options.Scope.Add("user:email");
    });

// ━━ OAuth2 callback controller ━━
[HttpGet("google-callback")]
public async Task<IActionResult> GoogleCallback()
{
    var result = await HttpContext.AuthenticateAsync("Google");
    if (!result.Succeeded) return Unauthorized();

    var googleId = result.Principal!.FindFirstValue(ClaimTypes.NameIdentifier)!;
    var email = result.Principal.FindFirstValue(ClaimTypes.Email)!;
    var name = result.Principal.FindFirstValue(ClaimTypes.Name)!;

    // Find or create user
    var user = await userManager.FindByEmailAsync(email);
    if (user is null)
    {
        user = new ApplicationUser { UserName = email, Email = email, EmailConfirmed = true, FirstName = name.Split(' ')[0], LastName = name.Split(' ').Skip(1).FirstOrDefault() ?? "" };
        await userManager.CreateAsync(user);
        await userManager.AddToRoleAsync(user, "User");
        await userManager.AddLoginAsync(user, new UserLoginInfo("Google", googleId, "Google"));
    }

    var roles = await userManager.GetRolesAsync(user);
    var accessToken = _tokenService.GenerateAccessToken(user, roles);
    // Redirect to frontend with token in secure cookie
    return Redirect($"https://myapp.com/auth/callback?token={accessToken}");
}

TokenService _tokenService = null!;
UserManager<ApplicationUser> userManager = null!;

Tip

Tip

Practice Roles Claims External OAuth2 Providers in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

.NET provides a unified platform for building various application types

Practice Task

Note

Practice Task - (1) Write a working example of Roles Claims External OAuth2 Providers from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with Roles Claims External OAuth2 Providers is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready dotnet code.

Topics in This Module

0/8 done