IdentityServer4 Asp.Net核心身份

时间:2018-07-27 14:52:56

标签: c# asp.net-core identityserver4 asp.net-core-identity asp.net-core-mvc-2.1

我正在尝试使用Asp.Net Core Identity创建基本的IdentityServer4,如this教程中所述。

但是当我调用登录方法时:

return Challenge(new AuthenticationProperties { RedirectUri = "/Home/Index" }, "oidc");

我收到404错误:

http://localhost:5000/account/login?returnUrl=%2Fconnect%2Fauthorize%2Fcallback%3Fclient_id%3Dmvc%26redirect_uri%3Dhttps%253A%252F%252Flocalhost%253A44391%252Fsignin-oidc%26response_type%3Dcode%2520id_token%26scope%3Dopenid%2520profile%2520api1%26response_mode%3Dform_post%26nonce%3D636682993147514721.ZDA2MmI5ZTgtMWU3Yi00ZjMzLTkyODMtZjBiNWIzMjUzZTRjZmYxMjIxYWItOTk5NS00OGJlLWE0M2EtOTg3ZTYyM2EzZWVk%26state%3DCfDJ8D1ISazXjTpLmRDTOwhIeT5cVwo-oh7P4hDeZa0Q7cSfU6vKRDTEu3RHraTyz4Wb8oQngGo-qAkzinXV2yFJuqClVRB_1gwLLXIvVK4moxtgGjZUGUJIDmoqQHrQCOxGNJLrGkaBiS74vxd1el8N1wSseoSBlqZD94OlShI53wgPNKXPiDzT0FLOI47MNwHwzW0d5q0n752kZiVp2V31CZemI6wtaEgte3Mb9iouFzrSyAW5XaBMdDEnAGPCNZ2d5Zfgwb2Cmp61B-I9t05aDHqR-5cxYtr0PVVM6PwBKy-1olSFH8uIc8ku0UJn7PY0WA%26x-client-SKU%3DID_NETSTANDARD1_4%26x-client-ver%3D5.2.0.0

我需要任何其他视图和控制器吗?我认为将使用Asp.Net Core Identity中的内容。

我的IdentityServer4配置:

 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.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(
                Configuration.GetConnectionString("DefaultConnection")));
        services.AddDefaultIdentity<IdentityUser>()
            .AddDefaultUI()
            .AddEntityFrameworkStores<ApplicationDbContext>();

        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

        // configure identity server with in-memory stores, keys, clients and scopes
        services.AddIdentityServer()
            .AddSigningCredential("CN=tst")
            .AddInMemoryPersistedGrants()
            .AddInMemoryIdentityResources(Config.GetIdentityResources())
            .AddInMemoryApiResources(Config.GetApiResources())
            .AddInMemoryClients(Config.GetClients())
            .AddAspNetIdentity<IdentityUser>();
    }


public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseDatabaseErrorPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            app.UseHsts();
        }

        //app.UseHttpsRedirection();
        //app.UseCookiePolicy();


        app.UseStaticFiles();
        app.UseIdentityServer();
        app.UseMvcWithDefaultRoute();
        //app.UseMvc(routes =>
        //         {
        //             routes.MapRoute(
        //                 name: "default",
        //                 template: "{controller=Home}/{action=Index}/{id?}");
        //         });
    }

我的客户端配置:

 public void ConfigureServices(IServiceCollection services)
    {
        services.AddAuthentication("oidc")
            .AddCookie("Cookies")
            .AddOpenIdConnect("oidc", optins =>
            {                                       
                optins.SignInScheme = "Cookies";
                optins.Authority = "http://localhost:5000";
                optins.RequireHttpsMetadata = false;

                optins.ClientId = "mvc";
                optins.ClientSecret = "secret";
                optins.ResponseType = "code id_token";
                optins.GetClaimsFromUserInfoEndpoint = true;                    

                optins.Scope.Add("openid");
                optins.Scope.Add("profile");
                //optins.Scope.Add("email");
                optins.Scope.Add("api1");

                optins.ClaimActions.Add(new JsonKeyClaimAction("role", "role", "role"));
                optins.SaveTokens = true;

            });

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


 public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();       
        app.UseAuthentication();
        app.UseCookiePolicy();

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }

IdentityServer4控制台中没有错误。

1 个答案:

答案 0 :(得分:2)

随着ASP.NET Core Identity 2.1的引入,视图,控制器等不再添加到使用Visual Studio或dotnet CLI生成的项目中。而是通过Razor Class Library提供的。

作为此更改的一部分,旧式URL(如/Account/Login(在您的示例中显示)也已更改。这些URL现在以/Identity为前缀-所有这些都是通过位于名为Identity的区域中的ASP.NET Core Razor页面提供的。

IdentityServer4 defaults to using the old-style URLs,正如我已经说过的那样,它不再存在(导致您的404)。为了解决这个问题,您可以在代码中将IdentityServerOptions对象配置为使用新的位置,如下所示:

services.AddIdentityServer(options =>
    {
        options.UserInteraction.LoginUrl = "/Identity/Account/Login";
        options.UserInteraction.LogoutUrl = "/Identity/Account/Logout";
    })
    .AddSigningCredential("CN=tst")
    // ...

只能配置两个与身份相关的URL,为完整起见,我在上面的代码中都添加了它们。