简体   繁体   中英

ASP.NET Core 'The oauth state was missing or invalid' while redirecting from GoogleAPI

I have a ASP.NET Core (v2.1) that should get all the user's for every authenticated user.

My FE is Vue.js and I'm using this package to allow the user to authenticate via Google (This works somehow fine) I've followed step by step in https://docs.microsoft.com/en-us/aspnet/core/security/authentication/social/google-logins?view=aspnetcore-2.1&tabs=aspnetcore2x#create-the-app-in-google-api-console and something doesn't work..

When I'm using 'postmessage' as my redirect_uri in my Vue component I can the googleUser object but the redirect_uri is incorrect so I can't exchange the code for tokens in my Backend server (ASP.NET Core).

But if I'm using the real redirect_uri I've configured in my Google API Console I'm getting "The oauth state was missing or invalid" and the Url is as instructed in the documentation here .

It seems like the Authentication Middleware isn't being initialized or something but I couldn't find any soulution..

My Startup.cs:

public Startup(IConfiguration configuration)
{
  var builder = new ConfigurationBuilder()        
    .AddJsonFile("appSettings.json",
      optional: false,
      reloadOnChange: true)
    .AddEnvironmentVariables();
    builder.AddUserSecrets<Startup>();     
  Configuration = configuration;
}

public IConfiguration Configuration { get; }

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
  services.AddIdentity<ApplicationUser, IdentityRole>()
    .AddEntityFrameworkStores<ApplicationDbContext>()
    .AddDefaultTokenProviders();

  services.AddAuthentication().AddGoogle(googleOptions =>
  {
    googleOptions.ClientId = Configuration["Authentication:Google:ClientId"];
    googleOptions.ClientSecret = Configuration["Authentication:Google:ClientSecret"];        
  });
  services.AddCors(options =>
  {
    options.AddPolicy("AllowAll", p =>
    {
      p.AllowAnyOrigin()
      .AllowAnyHeader()
      .AllowAnyMethod()
      .AllowCredentials();
    });
  });
  services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
  if (env.IsDevelopment())
  {
    app.UseDeveloperExceptionPage();
  }
  else
  {
    app.UseHsts();
  }
  app.UseCors("AllowAll");      
  app.UseHttpsRedirection();
  app.UseAuthentication();
  app.UseMvc();
}

My Vue.js component that enables users to login:

  <script> import Vue from 'vue' import { mapMutations, mapState } from 'vuex' export default { data(router) { return { section: 'Login', loading: '', response: '' } }, methods: { ...mapMutations(['syncUser']), signIn: function () { // This lets me get the googleUser object rather than the auth code Vue.googleAuth().directAccess() Vue.googleAuth().signIn(this.onSignInSuccess, this.onSignInError) }, onSignInSuccess: function (googleUser) { this.syncUser({ token: googleUser, provider: 'Google' }) // This line is redirecting me to this url with the auth code and other things from Google googleUser.grantOfflineAccess({ 'redirect_uri': 'http://localhost:1906/signin-google' }).then(function (response) { syncUser({ token: response.code, provider: 'Google' }) //this.toggleLoading() //this.resetResponse() }, function (error) { console.log(error) }) // this.syncUser({ token: authorizationCode, provider: 'Google' }) }, onSignInError: function (error) { this.response = 'Failed to sign-in' console.log('GOOGLE SERVER - SIGN-IN ERROR', error) }, toggleLoading: function () { this.loading = (this.loading === '') ? 'loading' : '' }, resetResponse: function () { this.response = '' } } } </script> 

Thank you :)

It seems an issue related with Google+ shut down..

To ASP.NET Core 2.x try the workaround explained in https://github.com/aspnet/AspNetCore/issues/6486

   services.AddAuthentication().AddGoogle(o => {
            o.ClientId = _configuration["CLIENT_ID"];
            o.ClientSecret = _configuration["CLIENT_SECRET"];
            o.UserInformationEndpoint = "https://www.googleapis.com/oauth2/v2/userinfo";
            o.ClaimActions.Clear();
            o.ClaimActions.MapJsonKey(ClaimTypes.NameIdentifier, "id");
            o.ClaimActions.MapJsonKey(ClaimTypes.Name, "name");
            o.ClaimActions.MapJsonKey(ClaimTypes.GivenName, "given_name");
            o.ClaimActions.MapJsonKey(ClaimTypes.Surname, "family_name");
            o.ClaimActions.MapJsonKey("urn:google:profile", "link");
            o.ClaimActions.MapJsonKey(ClaimTypes.Email, "email");
        });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM