c# - IdentityServer4 不会返回 token - 404 未找到

标签 c# .net-core identityserver4

我在我的项目中实现了 IdentityServer4。在我运行它并使用 Postman 发送 token 请求后,我得到了 404 状态代码,表示未找到,即使 URL 存在。

我想使用隐式 grant_type,所以我使用基本身份验证仅发送 client_id。

问题也可能与 OAuth 2 隐式流程的请求格式有关。据我了解,使用此流程时您唯一需要传递的是 client_id 并使用基本身份验证。也许我错了?

enter image description here

在 VisualStudio 中,我可以看到请求正在发送到 IdentityServer

enter image description here

即使我去查看调试消息,我也看不到返回 404 的错误类型,我得到的只是:

Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request starting HTTP/1.1 POST http://localhost:44305/baseurl/connect/token  0
Application Insights Telemetry (unconfigured): {"name":"Microsoft.ApplicationInsights.Dev.Request","time":"2017-01-06T11:02:42.0216819Z","tags":{"ai.device.roleInstance":"DESKTOP-3TKHRTV","ai.operation.id":"p4f7oSz6Ng0=","ai.user.userAgent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36","ai.operation.name":"POST /baseurl/connect/token","ai.internal.sdkVersion":"aspnet5c:1.0.0"},"data":{"baseType":"RequestData","baseData":{"ver":2,"id":"p4f7oSz6Ng0=","name":"POST /baseurl/connect/token","startTime":"2017-01-06T11:02:42.0216819+00:00","duration":"00:00:00.0028138","success":false,"responseCode":"404","url":"https://localhost:44305/baseurl/connect/token","httpMethod":"POST","properties":{"DeveloperMode":"true"}}}}
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request finished in 48.134ms 404 

IdentityServer 的代码非常简单和标准:

public class Startup
{
        private readonly IHostingEnvironment environment;

        public Startup(IHostingEnvironment env)
        {
            environment = env;

            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                .AddEnvironmentVariables();

            if (env.IsDevelopment())
            {
                builder.AddApplicationInsightsSettings(developerMode: true);
            }

            Configuration = builder.Build();
        }

        public IConfigurationRoot Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            var cert = new X509Certificate2(Path.Combine(environment.ContentRootPath, "idsvr3test.pfx"), "idsrv3test");

            services.AddMvc();
            services.AddApplicationInsightsTelemetry(Configuration);

            services.AddIdentityServer()
                .AddSigningCredential(cert)
                .AddInMemoryIdentityResources(ClientConfig.GetIdentityResources())
                .AddInMemoryApiResources(ClientConfig.GetApiResources())
                .AddInMemoryClients(ClientConfig.GetClients())
                .AddInMemoryUsers(ClientConfig.GetUsers());
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            app.UseApplicationInsightsRequestTelemetry();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseApplicationInsightsExceptionTelemetry();
            app.UseStaticFiles();
            app.UseMvcWithDefaultRoute();
        }
}

public class Program
{
        public static void Main(string[] args)
        {
            var host = new WebHostBuilder()
                .UseKestrel()
                .UseContentRoot(Directory.GetCurrentDirectory())
                .UseIISIntegration()
                .UseStartup<Startup>()
                .Build();

            host.Run();
        }
 }

public class ClientConfig
{
    public static IEnumerable<Client> GetClients()
    {
        return new List<Client>
        {
            new Client
            {
                ClientId = "mob.client",
                ClientName = "Mobile client",
                AllowedGrantTypes = GrantTypes.Implicit,
                AccessTokenType = AccessTokenType.Jwt,
                AllowAccessTokensViaBrowser = true,
                RedirectUris = { "http://localhost:5002/signin-oidc" },
                PostLogoutRedirectUris = { "https://localhost:44311/Unauthorized" },
                AllowedScopes = new List<string>
                {
                    IdentityServerConstants.StandardScopes.OpenId,
                    IdentityServerConstants.StandardScopes.Profile
                }
            }
        };
    }

    public static IEnumerable<IdentityResource> GetIdentityResources()
    {
        return new List<IdentityResource>
        {
            new IdentityResources.OpenId(),
            new IdentityResources.Profile(),
        };
    }

    public static IEnumerable<ApiResource> GetApiResources()
    {
        return new List<ApiResource>
        {
            new ApiResource("MyLegislatureAPI", "BEE MyLegislature API")
        };
    }

    public static List<InMemoryUser> GetUsers()
    {
        return new List<InMemoryUser>
        {
            new InMemoryUser{Subject = "818727", Username = "alice", Password = "alice",
                Claims = new Claim[]
                {
                    new Claim(JwtClaimTypes.Name, "Alice Smith"),
                    new Claim(JwtClaimTypes.GivenName, "Alice"),
                    new Claim(JwtClaimTypes.FamilyName, "Smith"),
                    new Claim(JwtClaimTypes.Email, "AliceSmith@email.com"),
                    new Claim(JwtClaimTypes.EmailVerified, "true", ClaimValueTypes.Boolean),
                    new Claim(JwtClaimTypes.Role, "Admin"),
                    new Claim(JwtClaimTypes.Role, "Geek"),
                    new Claim(JwtClaimTypes.WebSite, "http://alice.com"),
                    new Claim(JwtClaimTypes.Address, @"{ 'street_address': 'One Hacker Way', 'locality': 'Heidelberg', 'postal_code': 69118, 'country': 'Germany' }", IdentityServerConstants.ClaimValueTypes.Json)
                }
            },
            new InMemoryUser{Subject = "88421113", Username = "bob", Password = "bob",
                Claims = new Claim[]
                {
                    new Claim(JwtClaimTypes.Name, "Bob Smith"),
                    new Claim(JwtClaimTypes.GivenName, "Bob"),
                    new Claim(JwtClaimTypes.FamilyName, "Smith"),
                    new Claim(JwtClaimTypes.Email, "BobSmith@email.com"),
                    new Claim(JwtClaimTypes.EmailVerified, "true", ClaimValueTypes.Boolean),
                    new Claim(JwtClaimTypes.Role, "Developer"),
                    new Claim(JwtClaimTypes.Role, "Geek"),
                    new Claim(JwtClaimTypes.WebSite, "http://bob.com"),
                    new Claim(JwtClaimTypes.Address, @"{ 'street_address': 'One Hacker Way', 'locality': 'Heidelberg', 'postal_code': 69118, 'country': 'Germany' }", IdentityServerConstants.ClaimValueTypes.Json)
                }
            }
        };
    }
}

有没有人看到我做错了什么?

最佳答案

您在这里缺少的是在管道中注入(inject) Identity Server 中间件的部分。目前,您所做的只是在 DI 容器中注册必要的服务。

在您的Configure 方法中,您需要在某个时候调用app.UseIdentityServer

请看amazing documentation核心开发人员放在一起。

关于c# - IdentityServer4 不会返回 token - 404 未找到,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41504473/

相关文章:

c# - IS4 : Request not valid for the application's 'userAudience' configuration

c# - 使用 XmlSerializer 时如何添加换行符

c# - 使用 UnitOfWork 模拟上下文和存储库

macos - 使用 Visual Studio Mac API 无法绑定(bind)到地址(已在使用)错误

c# - .NET Core WebAPI 中的 Fluent Validation 中间件是否足够,还是我应该再次在服务层中进行验证?

c# - 我应该如何在 MVC Core 中管理 DbContext 生命周期?

c# - 鼠标悬停时更改图片

c# - 使用 C# 获取 Active Directory 中用户的父 OU

authentication - 将 IdentityServer 4 与 ASP.NET Core Identity 一起使用的附加值(value)是什么?

asp.net-identity - Multi-Tenancy 身份服务器 openid 认证