ASP.NET Core 7 openiddict-core 4 auth 服务器返回强制“token”参数在云中丢失,但在本地工作

Ahm*_*med 5 c# asp.net-core openiddict asp.net-core-webapi

我有 2 个项目,一个身份验证服务器和一个 API,但是当我尝试从 API 获取任何内容时,身份验证服务器总是返回

缺少必需的“token”参数

尽管它在我的机器上本地工作

使用 openiddict core 4.6 构建的身份验证服务器具有以下配置:

services.AddDbContext<AuthDbContext>(options =>
            {
                // Configure the context to use Microsoft SQL Server.
                options.UseSqlServer(configuration.GetConnectionString("DefaultConnection"));
                options.UseOpenIddict();
            });

// Register the Identity services.
services.AddIdentity<ApplicationUser, IdentityRole>(options =>
            {
                options.User.RequireUniqueEmail = true;
            }).AddDefaultUI()
            .AddEntityFrameworkStores<AuthDbContext>()
            .AddDefaultTokenProviders();

services.AddAuthentication()
            .AddGoogle(options =>
            {
                IConfigurationSection googleAuthNSection =
                configuration.GetSection("Authentication:Google");
                options.ClientId = googleAuthNSection["AppId"];
                options.ClientSecret = googleAuthNSection["AppSecret"];
            })
            .AddFacebook(options =>
            {
                IConfigurationSection FBAuthNSection =
                configuration.GetSection("Authentication:Facebook");
                options.ClientId = FBAuthNSection["AppId"];
                options.ClientSecret = FBAuthNSection["AppSecret"];
            })
            .AddMicrosoftAccount(microsoftOptions =>
            {
                microsoftOptions.ClientId = configuration["Authentication:Microsoft:AppId"];
                microsoftOptions.ClientSecret = configuration["Authentication:Microsoft:AppSecret"];
            })
            .AddTwitter(twitterOptions =>
            {
                twitterOptions.ConsumerKey = configuration["Authentication:Twitter:AppId"];
                twitterOptions.ConsumerSecret = configuration["Authentication:Twitter:AppSecret"];
                twitterOptions.RetrieveUserDetails = true;
            });

// Configure Identity to use the same JWT claims as OpenIddict instead
// of the legacy WS-Federation claims it uses by default (ClaimTypes),
// which saves you from doing the mapping in your authorization controller.
services.Configure<IdentityOptions>(options =>
            {
                options.Password.RequireDigit = false;
                options.Password.RequiredLength = 5;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireUppercase = false;
                options.Password.RequireLowercase = false;

                options.ClaimsIdentity.UserNameClaimType = Claims.Name;
                options.ClaimsIdentity.UserIdClaimType = Claims.Subject;
                options.ClaimsIdentity.RoleClaimType = Claims.Role;
            });

if (!environment.IsDevelopment())
{
    // OpenIddict offers native integration with Quartz.NET to perform scheduled tasks
    // (like pruning orphaned authorizations/tokens from the database) at regular intervals.
    services.AddQuartz(options =>
                {
                    options.UseMicrosoftDependencyInjectionJobFactory();
                    options.UseSimpleTypeLoader();
                    options.UseInMemoryStore();
                });

    // Register the Quartz.NET service and configure it to block shutdown until jobs are complete.
    services.AddQuartzHostedService(options =>
                {
                    options.WaitForJobsToComplete = true;
                });
            }

    services.AddOpenIddict()
              // Register the OpenIddict core components.
              .AddCore(options =>
              {
                  options.UseEntityFrameworkCore().UseDbContext<AuthDbContext>();
                  if (!environment.IsDevelopment())
                  {
                      options.UseQuartz();
                  }
              })
              // Register the OpenIddict server components.
              .AddServer(options =>
              {
                  options.SetIssuer(new Uri(configuration["OpenIddict:App:Issuer"]));

                  options.SetTokenEndpointUris("connect/token")
                  .SetLogoutEndpointUris("connect/logout")
                  .SetIntrospectionEndpointUris("connect/introspect");

                  options.AllowPasswordFlow();
                  options.AllowRefreshTokenFlow();
                  options.AllowClientCredentialsFlow();

                  options.RegisterScopes(
                      Scopes.OpenId,
                      Scopes.Email,
                      Scopes.Profile,
                      Scopes.Roles,
                      Scopes.Phone
                  );

                  options.AddEncryptionKey(new SymmetricSecurityKey(Convert.FromBase64String(configuration["OpenIddict:App:Key"])));

                  // Register the signing credentials.
                  options.AddDevelopmentSigningCertificate();

                  // Register the ASP.NET Core host and configure the ASP.NET Core-specific options.
                  options.UseAspNetCore()
                 .EnableStatusCodePagesIntegration()
                 .EnableAuthorizationEndpointPassthrough()
                 .EnableLogoutEndpointPassthrough()
                 .EnableTokenEndpointPassthrough()
                 .DisableTransportSecurityRequirement(); // During development, you can disable the HTTPS requirement.
              })
              // Register the OpenIddict validation components.
              .AddValidation(options =>
              {
                  // Import the configuration from the local OpenIddict server instance.
                  options.UseLocalServer();

                  // Register the ASP.NET Core host.
                  options.UseAspNetCore();
              });
Run Code Online (Sandbox Code Playgroud)

API 定义如下:

services.AddDbContext<AuthDbContext>(options =>
            {
                // Configure the context to use Microsoft SQL Server.
                options.UseSqlServer(configuration.GetConnectionString("DefaultConnection"));
                options.UseOpenIddict();
            });

// Register the Identity services.
services.AddIdentity<ApplicationUser, IdentityRole>(options =>
            {
                options.User.RequireUniqueEmail = true;
            }).AddDefaultUI()
            .AddEntityFrameworkStores<AuthDbContext>()
            .AddDefaultTokenProviders();

services.AddAuthentication()
            .AddGoogle(options =>
            {
                IConfigurationSection googleAuthNSection =
                configuration.GetSection("Authentication:Google");
                options.ClientId = googleAuthNSection["AppId"];
                options.ClientSecret = googleAuthNSection["AppSecret"];
            })
            .AddFacebook(options =>
            {
                IConfigurationSection FBAuthNSection =
                configuration.GetSection("Authentication:Facebook");
                options.ClientId = FBAuthNSection["AppId"];
                options.ClientSecret = FBAuthNSection["AppSecret"];
            })
            .AddMicrosoftAccount(microsoftOptions =>
            {
                microsoftOptions.ClientId = configuration["Authentication:Microsoft:AppId"];
                microsoftOptions.ClientSecret = configuration["Authentication:Microsoft:AppSecret"];
            })
            .AddTwitter(twitterOptions =>
            {
                twitterOptions.ConsumerKey = configuration["Authentication:Twitter:AppId"];
                twitterOptions.ConsumerSecret = configuration["Authentication:Twitter:AppSecret"];
                twitterOptions.RetrieveUserDetails = true;
            });

// Configure Identity to use the same JWT claims as OpenIddict instead
// of the legacy WS-Federation claims it uses by default (ClaimTypes),
// which saves you from doing the mapping in your authorization controller.
services.Configure<IdentityOptions>(options =>
            {
                options.Password.RequireDigit = false;
                options.Password.RequiredLength = 5;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireUppercase = false;
                options.Password.RequireLowercase = false;

                options.ClaimsIdentity.UserNameClaimType = Claims.Name;
                options.ClaimsIdentity.UserIdClaimType = Claims.Subject;
                options.ClaimsIdentity.RoleClaimType = Claims.Role;
            });

if (!environment.IsDevelopment())
{
    // OpenIddict offers native integration with Quartz.NET to perform scheduled tasks
    // (like pruning orphaned authorizations/tokens from the database) at regular intervals.
    services.AddQuartz(options =>
                {
                    options.UseMicrosoftDependencyInjectionJobFactory();
                    options.UseSimpleTypeLoader();
                    options.UseInMemoryStore();
                });

    // Register the Quartz.NET service and configure it to block shutdown until jobs are complete.
    services.AddQuartzHostedService(options =>
                {
                    options.WaitForJobsToComplete = true;
                });
            }

    services.AddOpenIddict()
              // Register the OpenIddict core components.
              .AddCore(options =>
              {
                  options.UseEntityFrameworkCore().UseDbContext<AuthDbContext>();
                  if (!environment.IsDevelopment())
                  {
                      options.UseQuartz();
                  }
              })
              // Register the OpenIddict server components.
              .AddServer(options =>
              {
                  options.SetIssuer(new Uri(configuration["OpenIddict:App:Issuer"]));

                  options.SetTokenEndpointUris("connect/token")
                  .SetLogoutEndpointUris("connect/logout")
                  .SetIntrospectionEndpointUris("connect/introspect");

                  options.AllowPasswordFlow();
                  options.AllowRefreshTokenFlow();
                  options.AllowClientCredentialsFlow();

                  options.RegisterScopes(
                      Scopes.OpenId,
                      Scopes.Email,
                      Scopes.Profile,
                      Scopes.Roles,
                      Scopes.Phone
                  );

                  options.AddEncryptionKey(new SymmetricSecurityKey(Convert.FromBase64String(configuration["OpenIddict:App:Key"])));

                  // Register the signing credentials.
                  options.AddDevelopmentSigningCertificate();

                  // Register the ASP.NET Core host and configure the ASP.NET Core-specific options.
                  options.UseAspNetCore()
                 .EnableStatusCodePagesIntegration()
                 .EnableAuthorizationEndpointPassthrough()
                 .EnableLogoutEndpointPassthrough()
                 .EnableTokenEndpointPassthrough()
                 .DisableTransportSecurityRequirement(); // During development, you can disable the HTTPS requirement.
              })
              // Register the OpenIddict validation components.
              .AddValidation(options =>
              {
                  // Import the configuration from the local OpenIddict server instance.
                  options.UseLocalServer();

                  // Register the ASP.NET Core host.
                  options.UseAspNetCore();
              });
Run Code Online (Sandbox Code Playgroud)

来自服务器的日志

services.AddAuthentication(options =>
            {
                options.DefaultScheme = OpenIddictValidationAspNetCoreDefaults.AuthenticationScheme;
                options.DefaultAuthenticateScheme = OpenIddictValidationAspNetCoreDefaults.AuthenticationScheme;
            });

// Register the OpenIddict validation components.
services.AddOpenIddict().AddValidation(options =>
              {
                  // Note: the validation handler uses OpenID Connect discovery
                  // to retrieve the address of the introspection endpoint.
                  options.SetIssuer(Configuration["OpenIddict:App:Issuer"]);
                  //options.AddAudiences(Configuration.GetSection("OpenIddict:App:Audiences").Get<string[]>());

                  // Configure the validation handler to use introspection and register the client
                  // credentials used when communicating with the remote introspection endpoint.
                  options.UseIntrospection()
                   .SetClientId(Configuration["OpenIddict:App:ClientId"])
                   .SetClientSecret(Configuration["OpenIddict:App:ClientSecret"]);

                  options.AddEncryptionKey(new SymmetricSecurityKey(Convert.FromBase64String(Configuration["OpenIddict:App:Key"])));

                  // Register the System.Net.Http integration.
                  options.UseSystemNetHttp();

                  // Register the ASP.NET Core host.
                  options.UseAspNetCore();
              });
Run Code Online (Sandbox Code Playgroud)

我如何注册该应用程序:

if (await manager.FindByClientIdAsync("api_service") == null)
{
    var descriptor = new OpenIddictApplicationDescriptor
                {
                    ClientId = "api_service",
                    DisplayName = "API Service",
                    ClientSecret = "6C59DC5E-682C-45BD-A1F9-9F15869905C1",