'How do I properly use OAuth via ASP.NET Core Identity?

I'm creating an ASP.NET Core Web API on .NET 6 + frontend in React (I don't want to use razor/blazor front technology) and I would like to add external OAuth2 authentication to my API server (only one method of logging in, via Twitch OAuth).

Here is my Program.cs

builder.Services.AddIdentity<IdentityUser, IdentityRole>()
    .AddEntityFrameworkStores<UserIdentityDbContext>();

builder.Services
    .AddAuthentication(options =>
    {
        options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        options.DefaultChallengeScheme = TwitchAuthenticationDefaults.AuthenticationScheme;
    })
    .AddCookie()
    .AddTwitch(options =>
{
    options.ClientId = builder.Configuration["TwitchOAuth:ClientId"];
    options.ClientSecret = builder.Configuration["TwitchOAuth:ClientSecret"];
    options.Scope.Add("bits:read");
    options.Scope.Add("channel:manage:redemptions");
    options.Scope.Add("channel:read:editors");
    options.Scope.Add("channel:read:subscriptions");
    options.Scope.Add("user:read:email");
    options.SaveTokens = true;
});    

As you can see I've set up Twitch authorization from AspNet.Security.OAuth.Twitch nuget package.

I know that on default my callback url will be localhost:7060/signin-twitch

I thought that all I need to do to make my OAuth registering work is to use Twitch token url with redirection to /signin-twitch

Example:

id.twitch.tv/oauth2/authorize?response_type=code&client_id=MyClientId&redirect_uri=https://localhost:7060/signin&scope=user:read:email+bits:read

Although whenever I use this link I got redirected to

https://localhost:7060/signin-twitch?code=MyCode&scope=user%3Aread%3Aemail+bits%3Aread

and I see this error (The oauth state was missing or invalid.):

Twitch oauth handler exception

What am I doing wrong?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source