【问题标题】:ASP.NET Core 'The oauth state was missing or invalid' while redirecting from GoogleAPI从 GoogleAPI 重定向时,ASP.NET Core 'Oauth 状态丢失或无效'
【发布时间】:2019-02-02 09:47:54
【问题描述】:

我有一个 ASP.NET Core (v2.1),它应该为每个经过身份验证的用户获取所有用户的信息。

我的 FE 是 Vue.js,我正在使用 this 包来允许用户通过 Google 进行身份验证(这工作得很好) 我在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中一步一步地跟着 并且有些东西不起作用..

当我在 Vue 组件中使用 'postmessage' 作为我的 redirect_uri 时,我可以使用 googleUser 对象,但 redirect_uri 不正确,因此我无法在后端服务器 (ASP.NET Core) 中交换令牌代码。

但如果我使用的是我在 Google API 控制台中配置的真正的 redirect_uri 我收到“oauth 状态丢失或无效”,并且 URL 与文档 here 中的说明相同。

似乎身份验证中间件没有被初始化或其他什么,但我找不到任何解决方案..

我的 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();
}

我的允许用户登录的 Vue.js 组件:

    <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>

谢谢你:)

【问题讨论】:

  • 您有解决这个问题的办法吗?从谷歌登录重定向时,我在 asp.net core2.2 中面临同样的问题

标签: c# asp.net-core vue.js google-api .net-core


【解决方案1】:

这似乎是与 Google+ 关闭有关的问题..

对于 ASP.NET Core 2.x,请尝试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");
        });

【讨论】:

  • 我已经尝试使用上述解决方案,但它不起作用。您还有其他解决方案吗?
猜你喜欢
  • 2021-04-26
  • 2021-11-06
  • 2023-02-15
  • 2023-01-31
  • 2017-09-22
  • 1970-01-01
  • 2020-04-14
  • 2021-12-27
  • 2021-11-12
相关资源
最近更新 更多