Search code examples
.netasp.net-corejwtgoogle-signin

.NET Core 3.1 GoogleSignIn -The authentication handler registered for scheme 'Bearer' is 'JwtBearerHandler' which cannot be used for SignInAsync


I'm trying add Google login to my system which is already have JWT implementation.

I got clientId and secret. I call this method

        AuthenticationProperties properties = await _accountApiClient.GoogleLogin1();
        return new ChallengeResult("Google", properties);

But it throws this error: InvalidOperationException: The authentication handler registered for scheme 'Bearer' is 'JwtBearerHandler' which cannot be used for SignInAsync. The registered sign-in schemes are: Cookies.

My startup.cs is like below

    services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
        }).AddGoogle(options =>
        {
            options.ClientId = CLIENTID
            options.ClientSecret =SECRET
        })
        .AddJwtBearer("Bearer", options =>
        {
            options.SaveToken = true;
            options.RequireHttpsMetadata = false;
            options.TokenValidationParameters = new TokenValidationParameters()
            {
                ValidateIssuer = true,
                ValidateAudience = true,
                ValidAudience = Configuration["JWT:ValidAudience"],
                ValidIssuer = Configuration["JWT:ValidIssuer"],
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JWT:Secret"]))
            };
            options.Events = new JwtBearerEvents
            {
                OnMessageReceived = context =>
                {
                    context.Token = context.Request.Cookies[CommonNames.AuthCookieName];
                    return Task.CompletedTask;
                },
            };
        }).AddCookie("Cookies"); 
        services.AddLocalization(options =>
        {
            options.ResourcesPath = "Resources";
        });

I'm getting the error from https://localhost:XXXXX/signin-google?state=XXXX

Is there any idea why it throws error?


Solution

  • It is correct that you can ask the JwtBearer handler to sign-in the user. The purpose of AddJwtBearer is to authenticate requests with a JWT token.

    your problem is this line:

         options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    

    It should be

         options.DefaultChallengeScheme = GoogleDefaults.AuthenticationScheme;
    

    Because you want the Google handler to handle when the user is challenged.