指定的“redirect_uri”对于ASP.NET核心的OpenIdDict中的此客户端应用程序无效

scyqe7ek  于 2023-01-06  发布在  .NET
关注(0)|答案(1)|浏览(214)

我已经创建了两个项目和安装服务器在一个项目和另一个安装客户端。我已经创建了数据库表来存储客户端信息。我还存储了RedirectUris在数据库中,但每次我得到上述错误。
有人能告诉我我错过了什么吗?
服务器代码:

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 OpenIddict entities.
                    options.UseEntityFrameworkCore().UseDbContext<AuthDbContext>();

                    // Enable Quartz.NET integration.
                    options.UseQuartz();
                })

        // Register the OpenIddict server components.
        .AddServer(options =>
                {
                    // Enable the authorization, logout, token and userinfo endpoints.
                    options
                    .SetAuthorizationEndpointUris("/connect/authorize")
                        .SetLogoutEndpointUris("/connect/logout")
                        .SetTokenEndpointUris("/connect/token")
                        .SetUserinfoEndpointUris("/connect/userinfo");

                    options
                       .AllowClientCredentialsFlow()
                       .AllowAuthorizationCodeFlow()
                       .RequireProofKeyForCodeExchange()
                       .AllowRefreshTokenFlow();

                    options
                        .AddEphemeralEncryptionKey()
                        .AddEphemeralSigningKey()
                        .DisableAccessTokenEncryption();

                    options.AllowPasswordFlow();
                    // Add all auth flows that you want to support

                    // Register your scopes
                    // Scopes are a list of identifiers used to specify what access privileges are requested.
                    options.RegisterScopes(Scopes.Email, Scopes.Profile, Scopes.Roles);

                    // Set the lifetime of your tokens
                    options.SetAccessTokenLifetime(TimeSpan.FromMinutes(30));
                    options.SetRefreshTokenLifetime(TimeSpan.FromDays(7));

                   // Register ASP.NET Core host and configure options
                   options.UseAspNetCore()
                          .EnableAuthorizationEndpointPassthrough()
                          .EnableLogoutEndpointPassthrough()
                          .EnableTokenEndpointPassthrough()
                          .EnableUserinfoEndpointPassthrough()
                          .EnableStatusCodePagesIntegration();
                })

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

客户代码:

services.AddAuthentication(options =>
            {
                options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
            })
        .AddOpenIdConnect(options =>
            {
                // Note: these settings must match the application details
                // inserted in the database at the server level.
                options.ClientId = {ClientId};
                options.ClientSecret = {ClientSecret };
                options.RequireHttpsMetadata = false;
                options.GetClaimsFromUserInfoEndpoint = true;
                options.SaveTokens = true;

                // Use the authorization code flow.
                options.ResponseType = OpenIdConnectResponseType.Code;
                options.AuthenticationMethod = OpenIdConnectRedirectBehavior.RedirectGet;

                options.Authority = "https://localhost:44312";

                options.Scope.Add("email");
                options.Scope.Add("roles");
                options.Scope.Add("profile");
                options.ClaimActions.MapJsonKey(ClaimTypes.Uri, ClaimTypes.Uri, "string");
                options.ClaimActions.MapJsonKey(ClaimTypes.GivenName, ClaimTypes.GivenName, "string");
                options.ClaimActions.MapJsonKey(ClaimTypes.Surname, ClaimTypes.Surname, "string");

                options.SecurityTokenValidator = new JwtSecurityTokenHandler
                {
                    // Disable the built-in JWT claims mapping feature.
                    InboundClaimTypeMap = new Dictionary<string, string>()
                };

                options.TokenValidationParameters.NameClaimType = "name";
                options.TokenValidationParameters.RoleClaimType = "role";
                options.Events.OnSignedOutCallbackRedirect += context =>
                {
                    context.Response.Redirect(context.Options.SignedOutRedirectUri);
                    context.HandleResponse();
                    return Task.CompletedTask;
                };
            });

我在网上查了这么多文件,但没有找到任何合适的解决方案

2lpgd968

2lpgd9681#

创建客户端并设置redirectURI

public class TestData : IHostedService
    {
        private readonly IServiceProvider _serviceProvider;

        public TestData(IServiceProvider serviceProvider)
        {
            _serviceProvider = serviceProvider;
        }

        public async Task StartAsync(CancellationToken cancellationToken)
        {
            using var scope = _serviceProvider.CreateScope();

            var context = scope.ServiceProvider.GetRequiredService<FaDbContext>();
            await context.Database.EnsureCreatedAsync(cancellationToken);

            var manager = scope.ServiceProvider.GetRequiredService<IOpenIddictApplicationManager>();
            var client = await manager.FindByClientIdAsync("postman", cancellationToken);
            if (client is null)
            {
                await manager.CreateAsync(new OpenIddictApplicationDescriptor
                {
                    ClientId = "postman",
                    ClientSecret = "postman-secret",
                    DisplayName = "Postman Client",
                    RedirectUris = { new Uri("https://oauth.pstmn.io/v1/callback") },
                    Permissions =
                    {
                        OpenIddictConstants.Permissions.Endpoints.Authorization,
                        OpenIddictConstants.Permissions.Endpoints.Token,

                        OpenIddictConstants.Permissions.GrantTypes.RefreshToken,
                        //OpenIddictConstants.Permissions.GrantTypes.AuthorizationCode,
                        OpenIddictConstants.Permissions.GrantTypes.ClientCredentials,
                        OpenIddictConstants.Permissions.GrantTypes.Password,

                        OpenIddictConstants.Permissions.Scopes.Email,
                        OpenIddictConstants.Permissions.Scopes.Roles,
                        OpenIddictConstants.Permissions.Scopes.Address,
                        OpenIddictConstants.Permissions.Scopes.Phone,
                        OpenIddictConstants.Permissions.Prefixes.Scope + "faid_client_scope",
                        OpenIddictConstants.Permissions.Prefixes.Scope + "test_scope_1",

                        OpenIddictConstants.Permissions.ResponseTypes.Code,
                        OpenIddictConstants.Permissions.ResponseTypes.IdToken,
                        OpenIddictConstants.Permissions.ResponseTypes.CodeIdToken,
                        OpenIddictConstants.Permissions.ResponseTypes.Token
                    },

                }, cancellationToken);
            }

        public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
    }

然后在program.cs中注册

builder.Services.AddHostedService<TestData>();

这里有一个如何操作的指南:https://dev.to/robinvanderknaap/setting-up-an-authorization-server-with-openiddict-part-iii-client-credentials-flow-55lp

相关问题