IdentityServer4 无效的 Redirect_Uri 错误

Nov*_*der 14 c# authorization asp.net-identity asp.net-core identityserver4

我创建了 3 个独立的项目:Web api 项目、Web MVC 项目和 ASP.NET Core 应用程序。我正在将 IdentityServer4 与 asp.net core 身份一起使用。我有一个项目解决方案id,其中包含TestUsers. 在线上RedirectUris = {"https://localhost:5444/signin-oidc"},我将其重定向到该项目WeatherMVC。所有三个文件上的 launchsettings.json 都是正确的,因此也是RedirectUris正确的。是否有什么操作不正确导致我收到此消息?

在此输入图像描述

在此输入图像描述

weatherapi project

----startup.cs

namespace weatherapi
{
    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)
        {
            services.AddAuthentication("Bearer")
                .AddIdentityServerAuthentication("Bearer", options =>
                {
                    options.ApiName = "weatherapi";
                    options.Authority = "https://localhost:5443";
                });

            services.AddControllers();

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "weatherapi", Version = "v1" });
            });
        }

        // 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.UseSwagger();
                app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "weatherapi v1"));
            }

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

----launchsettings.json

{
  "$schema": "http://json.schemastore.org/launchsettings.json",
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:52575",
      "sslPort": 44354
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "launchUrl": "swagger",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "weatherapi": {
      "commandName": "Project",
      "dotnetRunMessages": "true",
      "launchBrowser": true,
      "hotReloadProfile": "aspnetcore",
      "launchUrl": "swagger",
      "applicationUrl": "https://localhost:5445;http://localhost:5002",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

WeatherMVC Project

----launchsettings.json

{
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:65206",
      "sslPort": 44398
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "WeatherMVC": {
      "commandName": "Project",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      },
      "dotnetRunMessages": "true",
      "applicationUrl": "https://localhost:5444;http://localhost:5001"
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

这两个项目属于一个解决方案,我执行多个启动项目。

在另一个项目中,名为id...

id project

----launchsettings.json

{
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:19916",
      "sslPort": 44341
    }
  },
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "id": {
      "commandName": "Project",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      },
      "hotReloadProfile": "aspnetcore",
      "dotnetRunMessages": "true",
      "applicationUrl": "https://localhost:5443;http://localhost:5000"
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

在下面的这个类中Config.cs,我有它将执行以下操作的代码Redirect_uri

        public static IEnumerable<Client> Clients =>
          new[]
          {
        // m2m client credentials flow client
        new Client
        {
          ClientId = "m2m.client",
          ClientName = "Client Credentials Client",

          AllowedGrantTypes = GrantTypes.ClientCredentials,
          ClientSecrets = {new Secret("SuperSecretPassword".Sha256())},

          AllowedScopes = {"weatherapi.read", "weatherapi.write"}
        },

        // interactive client using code flow + pkce
        new Client
        {
          ClientId = "interactive",
          ClientSecrets = {new Secret("SuperSecretPassword".Sha256())},

          AllowedGrantTypes = GrantTypes.Code,

          RedirectUris = {"https://localhost:5444/signin-oidc"},
          FrontChannelLogoutUri = "https://localhost:5444/signout-oidc",
          PostLogoutRedirectUris = {"https://localhost:5444/signout-callback-oidc"},

          AllowOfflineAccess = true,
          AllowedScopes = {"openid", "profile", "weatherapi.read"},
          RequirePkce = true,
          RequireConsent = true,
          AllowPlainTextPkce = false
        },
          };
    }
}
Run Code Online (Sandbox Code Playgroud)

----startup.cs

public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddIdentityServer()
                .AddInMemoryClients(Config.Clients)
                .AddInMemoryIdentityResources(Config.IdentityResources)
                .AddInMemoryApiResources(Config.ApiResources)
                .AddInMemoryApiScopes(Config.ApiScopes)
                .AddTestUsers(Config.Users)
                .AddDeveloperSigningCredential();

            services.AddControllersWithViews();
        }

        // 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.UseRouting();
            app.UseStaticFiles();
            app.UseIdentityServer();
            app.UseAuthorization();

           app.UseEndpoints(endpoints => endpoints.MapDefaultControllerRoute());

        }
    }
Run Code Online (Sandbox Code Playgroud)

更新

按照建议添加调试器后program.cs

public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            })
            .ConfigureLogging(builder =>
            {
                builder.SetMinimumLevel(LogLevel.Debug);
                builder.AddFilter("IdentityServer4", LogLevel.Debug);
            });
Run Code Online (Sandbox Code Playgroud)

WeatherMVC我终于注意到它正在调用属于名为using it's 的项目的重定向 uri sslPort: 44398。请launchsettings.json参阅weathermvc projcect。如果我没有将其设置为该 URI,似乎无法理解为什么它会重定向该 URI。

在此输入图像描述

Ros*_*sco 12

WeatherApi 是 IdentityServer 的客户端,当它进行身份验证时,它会告诉 IdentityServer 它的重定向 uri。IdentityServer 检查其允许的重定向 uri,如果找到匹配则进行重定向。

此代码指定有效重定向 uri 的列表,而不是重定向 uri。

RedirectUris = {"https://localhost:5444/signin-oidc"},
Run Code Online (Sandbox Code Playgroud)

你有 IISExpress 和 Kestrel 设置,launchsettings.json我认为你的 WeatherApi 项目只是使用它找到的第一个设置作为重定向 uri。

一些可能的解决方案是:

将 WeatherApi 的其他 uri 添加到允许的 uri,例如

RedirectUris = {
  "https://localhost:5444/signin-oidc", "https://localhost:44398/signin-oidc"},
Run Code Online (Sandbox Code Playgroud)

您还可以更改launchsettings.jsonWeatherApi 中的 Kestrel 以使用相同的端口

"applicationUrl": "https://localhost:44398;http://localhost:65206"
Run Code Online (Sandbox Code Playgroud)

  • @NoviceCoder 来自 Identityserver 的令牌有效期为 1 小时(默认情况下),因此您不需要登录 (2认同)