簡體   English   中英

OpenIdDict 3.0 在控制器中接受 Id 令牌而不是訪問令牌

[英]OpenIdDict 3.0 Accepting Id Token instead of Access Token in Controllers

我正在使用 OpenIdDict 3.0 來托管我的身份服務器。 我能夠獲得訪問令牌和 id 令牌,但是當我在授權 header 中使用訪問令牌時,我的控制器以某種方式返回 401,但在我使用 id 令牌時成功通過身份驗證。

我在之前的項目中使用過 OpenIdDict 2.0,效果很好。

以下是我的Start.cs

public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            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)
        {
            #region Database
            var connectionString = Environment.GetEnvironmentVariable("CONNECTION_STRING");
#if DEBUG
            connectionString = Configuration.GetConnectionString("DefaultConnection");
#endif
            services.AddDbContext<ApplicationDbContext>(options => 
            { 
                options.UseMySql(connectionString);

                // Register the entity sets needed by OpenIddict.
                // Note: use the generic overload if you need
                // to replace the default OpenIddict entities.
                options.UseOpenIddict();
            });
            #endregion

            #region Authentication
            services
                .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(options =>
                {
                    options.Authority = Configuration["Jwt:Authority"];
                    options.Audience = Configuration["Jwt:Audience"];
                    options.RequireHttpsMetadata = bool.TryParse(Configuration["Jwt:Https"], out bool isHttps) && isHttps;
                });

            // 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.ClaimsIdentity.UserNameClaimType = ClaimTypes.Name;
                options.ClaimsIdentity.UserIdClaimType = JwtRegisteredClaimNames.Sub;
                options.ClaimsIdentity.RoleClaimType = ClaimTypes.Role;
            });

            services.AddOpenIddict()
                    // Register the OpenIddict core components.
                    .AddCore(options =>
                    {
                        // Configure OpenIddict to use the Entity Framework Core stores and models.
                        // Note: call ReplaceDefaultEntities() to replace the default entities.
                        options.UseEntityFrameworkCore()
                               .UseDbContext<ApplicationDbContext>();
                    })
                    // Register the OpenIddict server components.
                    .AddServer(options =>
                    {
                        // Enable the token endpoint.
                        // Enable the client credentials flow.
                        options
                            .SetTokenEndpointUris("/Account/Token")
                            .AllowPasswordFlow()
                            .SetAccessTokenLifetime(TimeSpan.FromHours(1))
                            .AllowRefreshTokenFlow()
                            .SetRefreshTokenLifetime(TimeSpan.FromDays(7));

                        // Register the signing and encryption credentials.
                        options
                            .AddDevelopmentEncryptionCertificate()
                            .AddDevelopmentSigningCertificate();

                        options.RegisterClaims();

                        // Register the ASP.NET Core host and configure the ASP.NET Core options.
                        options
                            .UseAspNetCore()
                            .EnableTokenEndpointPassthrough();
                    })
                    // 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();
                    });
            #endregion

            services.AddControllers();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();

                app.UseMyPcBuilderOpenIdDict().Wait();
            }

            app.UseRouting();

            app.UseAuthentication();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }

您的配置無效:您正在注冊 JWT 處理程序和 OpenIddict 驗證處理程序。

與 JWT 處理程序不同,OpenIddict 驗證處理程序可以導入用於保護服務器頒發的訪問令牌的加密密鑰(感謝UseLocalServer() )。 由於 JWT 處理程序沒有等效方法,因此它無法解密您的訪問令牌。

OpenIddict 驗證處理程序還帶有內置的typ令牌類型驗證,以確保 API 端點永遠不會接受身份令牌。 這不是 JWT 處理程序所做的事情。

JwtBearerDefaults.AuthenticationScheme替換為OpenIddictValidationAspNetCoreDefaults.AuthenticationScheme ,一切都會正常工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM