简体   繁体   English

IdentityServer4 不会返回令牌 - 404 未找到

[英]IdentityServer4 won't return token - 404 not found

I have implemented IdentityServer4 in my project.我已经在我的项目中实现了 IdentityServer4。 After I run it and use Postman to send a request for token I get 404 status code for not found, even though URL exists.在我运行它并使用 Postman 发送令牌请求后,即使 URL 存在,我也会得到 404 状态代码未找到。

I want to use Implicit grant_type so I am sending only client_id using Basic Auth.我想使用隐式 grant_type,所以我只使用基本身份验证发送 client_id。

Problem can also be related to the format of request for implicit flow of OAuth 2. As I've understood the only thing you need to pass when you using this flow is client_id and use Basic authentication.问题也可能与 OAuth 2 的隐式流的请求格式有关。据我所知,当您使用此流时,您唯一需要传递的是 client_id 并使用基本身份验证。 Maybe I am wrong about that one?也许我错了?

在此处输入图片说明

In VisualStudio I can see that request are coming to IdentityServer在 VisualStudio 中,我可以看到该请求正在发送至 IdentityServer

在此处输入图片说明

Even if I go to see debug message I don't see what kind of error is returning 404, all I got is this:即使我去看调试消息,我也看不到返回 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 

Code for IdentityServer is pretty straightforward and standard: 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)
                }
            }
        };
    }
}

Does anyone sees what I am doing wrongly?有没有人看到我做错了什么?

What you're missing here is the part where you inject the Identity Server middleware in the pipeline.您在这里缺少的是在管道中注入 Identity Server 中间件的部分。 At the moment, all you're doing is registering the necessary services in the DI container.目前,您所做的只是在 DI 容器中注册必要的服务。

In your Configure method, you need to call app.UseIdentityServer at some point.在您的Configure方法中,您需要在某个时候调用app.UseIdentityServer

Please have a look at the amazing documentation the core developers put together.请查看核心开发人员汇总的惊人文档

Check your IdentityServer project URL.检查您的 IdentityServer 项目 URL。

I see you have "baseurl" as part of your path.我看到您将“baseurl”作为路径的一部分。

mine is: http://localhost:5000/connect/token .我的是: http://localhost:5000/connect/token

To help you verify check your configuration URL to make sure that works.为了帮助您验证,请检查您的配置 URL 以确保其有效。

mine is: http://localhost:5000/.well-known/openid-configuration .我的是: http://localhost:5000/.well-known/openid-configuration

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM