【问题标题】:asp.net core identity and identityserverasp.net 核心身份和身份服务器
【发布时间】:2019-03-24 05:32:20
【问题描述】:

我正在关注 this walkthrough 将 asp.net 核心身份与 IdentityServer 集成,但遇到了一些障碍。

如果我遵循指南并使用,我将在哪里更新 ConfigureServices 方法

services.AddIdentity<IdentityUser, IdentityRole>()
        .AddEntityFrameworkStores<ApplicationDbContext>()
        .AddDefaultTokenProviders();

我无法再访问任何与帐户相关的功能。注册链接的路由更改为

~/Identity/Account/Register

~/?area=Identity&page=%2FAccount%2FRegister

这会破坏所有与帐户相关的功能

如果我把它留在

services.AddDefaultIdentity<IdentityUser>()
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultTokenProviders();

那么路由还是可以的,我可以通过登录页面输入我的凭据,登录成功,但是

SignInManager.IsSignedIn(User)

返回 false,所以我猜这里从根本上破坏了一些东西。

我已将身份服务器添加到我的 ConfigureServices:

    services.AddIdentityServer()
                    .AddDeveloperSigningCredential()
                    .AddInMemoryPersistedGrants()
.AddInMemoryIdentityResources(Config.IdentityResources.GetIdentityResources())
                    .AddInMemoryApiResources(Config.APIResources.GetApiResources())
                    .AddInMemoryClients(Config.Clients.GetClients())
                    .AddAspNetIdentity<IdentityUser>();

有什么需要改变的想法 - 我猜它在最新版本的 asp.net 核心中导致了这种情况?

【问题讨论】:

  • Configure 中有app.UseIdentityServer(); 吗?是在app.UseMvc() 之前吗?
  • @KirkLarkin 是的,根据快速入门,我已经完全掌握了

标签: asp.net asp.net-core identityserver4


【解决方案1】:

Identity UI 是使用 Razor Pages 实现的。对于映射这些的端点路由,请在 UseEndpoints 回调中添加对 MapRazorPages 的调用:

app.UseEndpoints(endpoints =>
{
// ...
endpoints.MapRazorPages();
});

【讨论】:

  • 在 .net core 版本 5+ 上有效!谢谢
  • 同意@JhonnatanEduardo
【解决方案2】:

在 Net Core 2.1 中,Microsoft 已删除 AccountController 并将所有身份逻辑移至 Razor 页面(现在没有其他选择),这使得逻辑难以遵循(它让我想起了 ASP 经典或 PHP)。文档中的快速入门完全依赖于保留的 AccountController(不再是这种情况),并且猜测这需要重写为 Razor 页面,然后才能正常工作。但是,当身份验证机制被破坏时,这样做并没有多大意义。

我使用以下 Startup.cs 来演示身份验证在添加到新的 Net Core 2.1 项目时不再适用于 IdentityServer4。它应该可以工作,但在访问受 [Authorize] 保护的控制器方法和显示为登录页面的挑战时会显示以下行为。

1) 输入不正确的凭据会导致显示“无效登录尝试”文本

2) 输入正确的凭据无法进行身份验证,这可以通过没有注销链接或调试并观察 User.isAuthenticated 为假来看出

可以对 Startup.cs 进行一些更改,以便在禁用 IdentityServer 并启用标准身份验证时显示身份验证工作。只需注释掉开始 'services.AddIdentityServer(options => 的块 ' 禁用 IdentityServer。接下来注释掉 'useIdentityServer()' 并取消注释 'useAuthentication()' 并且所有身份验证再次正常工作。

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

        // Add authentication options
        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.ClientSecret = "secret";
            options.ResponseType = "code id_token";
            options.SaveTokens = true;
            options.GetClaimsFromUserInfoEndpoint = true;
            options.Scope.Add("api1");
            options.Scope.Add("offline_access");

        });

        // Identity Context
        services.AddDbContext<ApplicationDbContext>(options =>
        {
            options.UseSqlServer(Configuration["IdentityConnection"],
                                sqlOptions => sqlOptions.MigrationsAssembly(typeof(Startup).GetTypeInfo().
                                Assembly.GetName().Name));
        },
            ServiceLifetime.Scoped
        );

        // Configure default Identity implementation
        services.AddDefaultIdentity<ApplicationUser>()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultUI()
            .AddDefaultTokenProviders()
            .AddEntityFrameworkStores<ApplicationDbContext>();

        // Add application services.
        services.AddTransient<Microsoft.AspNetCore.Identity.UI.Services.IEmailSender, EmailSender>();

        services.AddMvc();

        // configure identity server with in-memory stores, keys, clients and scopes
        services.AddIdentityServer(options =>
        {
            options.UserInteraction.LoginUrl = "/Identity/Account/Login";
            options.UserInteraction.LogoutUrl = "/Identity/Account/Logout";
        })
        .AddDeveloperSigningCredential()
            .AddInMemoryPersistedGrants()
            .AddInMemoryIdentityResources(Config.GetIdentityResources())
            .AddInMemoryApiResources(Config.GetApiResources())
            .AddInMemoryClients(Config.GetClients())
            .AddAspNetIdentity<ApplicationUser>();

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

    // 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();
            app.UseDatabaseErrorPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            app.UseHsts();
        }

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

        //app.UseAuthentication(); // not needed, since UseIdentityServer adds the authentication middleware
        app.UseIdentityServer();

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

我不确定如何在 IdentityServer4 中进行身份验证,因为没有遵循它在 Net Core 2.1 中的工作方式。有没有人比我更进一步并让这个服务器正常工作?

【讨论】:

    【解决方案3】:

    最后想通了。随着 MSFT 迁移到 Razor 页面,这似乎是一个奇怪的错误。 我需要做的就是添加Scaffolding UI,它就开始工作了

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-11-17
      • 2017-07-26
      • 2017-11-26
      • 1970-01-01
      • 2021-05-28
      • 2021-06-11
      • 2017-09-13
      相关资源
      最近更新 更多