Help with sign-up with unsupported OAuth2.0 provider

iKingNinja 60 Reputation points
2024-04-09T17:04:08.6133333+00:00

Hello! I'm new to ASP.NET Core Identity and I'm having a hard time figuring out how to add support for an unsupported OAuth2.0 provider like Discord.

From my understanding I need to use the AddOAuth() method but I have some questions.

When I configure the OAuthOptions I can set a CallbackPath, do I have to create a controller action that matches that path to handle saving the user to the database?

I've seen people using OAuthOptions.Events.OnCreatingTicket to handle adding user claims, but I've also read that there's a SignInManager<TUser>.GetExternalLoginInfoAsync() method which should supposedly use the access token to obtain the user's info using OAuthOptions.UserInformationEndpoint.

This is what my code looks like right now:

// Program.cs

builder.Services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = "Example";
})
    .AddCookie()
    .AddOAuth("Example", options =>
    {
        options.ClientId = configuration["Credentials:Example:ClientId"];
        options.ClientSecret = configuration["Credentials:Example:ClientSecret"];
        options.AuthorizationEndpoint = "https://apis.example.com/oauth/v1/authorize";
        options.CallbackPath = new PathString("/api/v1/auth/redirect");
        options.TokenEndpoint = "https://apis.example.com/oauth/v1/token";
        options.UserInformationEndpoint = "https://apis.example.com/oauth/v1/userinfo";
        options.Scope.Add("openid");
        options.Scope.Add("profile");
        options.ClaimActions.MapJsonKey(ClaimTypes.NameIdentifier, "sub");
        options.ClaimActions.MapJsonKey(ClaimTypes.Name, "username");
    });

If someone could please show me the correct way of handling this kind of case with some example code it would be very appreciated as I've been stuck on this for 2 days.

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,179 questions
0 comments No comments
{count} votes