IdentityServer4快速入门问题

4
我目前在IdentityServer 4指南的这个页面:http://docs.identityserver.io/en/dev/quickstarts/3_interactive_login.html,并尝试启动MVC应用程序。
然而,当我启动客户端应用程序时,我不断收到此错误。
InvalidOperationException: Unable to resolve service for type 'IdentityServer4.Services.IIdentityServerInteractionService' while attempting to activate 'IdentityServer4.Quickstart.UI.HomeController'.

我进入了IdentityServer4的GitHub并复制了其中的代码,但它根本无法运行。

我不确定接下来该怎么做。

这是我的Startup.cs文件。

using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;

namespace IdentityServerClient
{
    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.AddMvc();
            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

            services.AddAuthentication(options =>
            {
                options.DefaultScheme = "Cookies";
                options.DefaultChallengeScheme = "oidc";
            })
                .AddCookie("Cookies")
                .AddOpenIdConnect("oidc", options =>
                {
                    options.SignInScheme = "Cookies";

                    options.Authority = "http://localhost:5000";
                    options.RequireHttpsMetadata = false;

                    options.ClientId = "mvc";
                    options.SaveTokens = true;
                });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseAuthentication();

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

enter image description here 我也无法访问文档中显示的登录页面。

2个回答

12

如果您使用的是快速入门UI,则应该使用其上的指南,位于这里:

https://github.com/IdentityServer/IdentityServer4.Quickstart.UI

引用该页面的话:

接下来,您需要配置身份验证处理程序:

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();

        // some details omitted
        services.AddIdentityServer();

        services.AddAuthentication()
        ...  

你缺少:

services.AddIdentityServer()
    .AddInMemoryCaching()
    .AddClientStore<InMemoryClientStore>()
    .AddResourceStore<InMemoryResourcesStore>(); // <-- Add this

结果是,身份服务器服务都没有注册到依赖注入容器中,这就是你看到那个错误的原因。

看起来你链接的教程文档已经过时了。

--

以下是完整的操作步骤:

现在修改你的Startup.cs文件如下:

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    services.Configure<CookiePolicyOptions>(options =>
    {
        // This lambda determines whether user consent for non-essential cookies is needed for a given request.
        options.CheckConsentNeeded = context => true;
        options.MinimumSameSitePolicy = SameSiteMode.None;
    }); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

    services.AddIdentityServer()
        .AddInMemoryCaching()
        .AddClientStore<InMemoryClientStore>()
        .AddResourceStore<InMemoryResourcesStore>();
}

你好,感谢回复!我尝试了那个方法,但是它只是给了我这个错误:InvalidOperationException: 在尝试激活 'IdentityServer4.Validation.AuthorizeRequestValidator' 时无法解析类型为 'IdentityServer4.Stores.IClientStore' 的服务。 - JianYA
另外,如果我按照您给我的链接操作,它会要求我添加app.useidentityserver()。这将导致出现以下错误:“未指定客户端的存储机制。请使用'AddInMemoryClients'扩展方法注册开发版本。”此外,您提供的链接没有显示在Program和Startup.cs中应该放置什么内容。 - JianYA
@JianYA 如果不确定的话,恐怕我也无能为力;我只能说我按照 Github 上的说明进行操作,并忽略了 identityserver.io 上的文档,这样对我来说是有效的。 - Doug
我需要在运行MVC客户端之前先运行控制台吗? - JianYA
不,内存存储仅用于轻松的本地测试。您应该在生产负载平衡部署中使用真实存储。--> http://docs.identityserver.io/en/release/topics/deployment.html - Doug
显示剩余7条评论

0

更新

*请检查这段代码:它可能会有所帮助,因为我也在学习它,并且它对我有效。*

public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;

            // configure identity server with in-memory stores, keys, clients and scopes
            services.AddIdentityServer()
                .AddDeveloperSigningCredential()
                .AddTestUsers(Config.GetUsers())
                //.AddInMemoryClients(Config.GetClients())
                // this adds the config data from DB (clients, resources)
                .AddConfigurationStore(options =>
                {
                    options.ConfigureDbContext = builder =>
                        builder.UseSqlServer(Configuration.GetConnectionString("IdentityConnectionString"), sql =>
                            sql.MigrationsAssembly(migrationsAssembly));
                })

                // this adds the operational data from DB (codes, tokens, consents)
                .AddOperationalStore(options =>
                {
                    options.ConfigureDbContext = builder =>
                        builder.UseSqlServer(Configuration.GetConnectionString("IdentityConnectionString"),
                            sql => sql.MigrationsAssembly(migrationsAssembly));

                    // this enables automatic token cleanup. this is optional.
                    options.EnableTokenCleanup = true;
                    options.TokenCleanupInterval = 30;
                });
                //.AddInMemoryIdentityResources(Config.GetIdentityResources())
                //.AddInMemoryApiResources(Config.GetApiResources())


            services.AddAuthentication();

        }


    // clients want to access resources (aka scopes)
    public static IEnumerable<Client> GetClients()
    {
        // client credentials client
        return new List<Client>
        {
            new Client
            {
                ClientId = "client",
                AllowedGrantTypes = GrantTypes.ClientCredentials,

                ClientSecrets =
                {
                    new Secret("secret".Sha256())
                },
                AllowedScopes = { "api1" }
            },

            // resource owner password grant client
            new Client
            {
                ClientId = "ro.client",
                AllowedGrantTypes = GrantTypes.ResourceOwnerPassword,

                ClientSecrets =
                {
                    new Secret("secret".Sha256())
                },
                AllowedScopes = { "api1" }
            },

            // OpenID Connect hybrid flow and client credentials client (MVC)


        };
    }

如果您没有使用内存服务

如果您遇到以下错误:无法解析类型“IdentityServer4.Stores.IClientStore”的服务

请显式注册存储和实现:(尝试一下)

    services.AddScoped<IUserStore<User>, UserService>();
    services.AddScoped<IClientStore, ClientService>();
    services.AddScoped<IScopeStore, ScopeService>();
    services.AddScoped<IPersistedGrantStore, GrantService>();

嗨,它说我必须生成多个类。这些类应该放在哪里? - JianYA
你是否正在使用内存存储?展示一下你的认证启动。 - Saurin Vala
我的创业公司已经在我的问题中发布了。是的,我正在使用内存存储。 - JianYA
我添加了我的认证启动代码,请查看一下,这可能会有所帮助。 - Saurin Vala

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接