首页 > 解决方案 > 与 Identity Server 集成的 ASP.NET Core Razor 页面

问题描述

我有一个包含 ASP.NET Core 3.1 和 Razor 页面的项目。该应用程序非常简单:一个用于保护静态文件的欢迎页面。当我想将我的小型网站与 Identity Server 4 集成时,我的问题就开始了。

通常,在我的另一个 .NET Core 项目中,我在Startup.cs中添加:

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.AddRazorPages(options => {
            options.Conventions.AuthorizePage("/Login");
        });

        services.Configure<IdentityServerConfiguration>(Configuration.GetSection("IdentityServerConfiguration"));

        services.AddDistributedMemoryCache();

        services.AddSession(options =>
        {
            options.Cookie.Name = ".cello.Session";
            options.IdleTimeout = TimeSpan.FromHours(12);
        });

        services.AddAuthentication(options =>
        {
            options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = "oidc";
        })
        .AddCookie(options =>
        {
            options.ExpireTimeSpan = TimeSpan.FromMinutes(30);
            options.Cookie.Name = "cello.dashboard";
        })
        .AddOpenIdConnect("oidc", options =>
        {
            IdentityServerConfiguration idsrv = Configuration.GetSection("IdentityServerConfiguration").Get<IdentityServerConfiguration>();
            options.Authority = idsrv.Url;
            options.ClientId = idsrv.ClientId;
            options.ClientSecret = idsrv.ClientSecret;

#if DEBUG options.RequireHttpsMetadata = false; #else options.RequireHttpsMetadata = true; #万一

            options.ResponseType = "code";

            options.Scope.Clear();
            options.Scope.Add("openid");
            options.Scope.Add("profile");
            options.Scope.Add("email");
            options.Scope.Add("roles");
            options.Scope.Add("offline_access");

            options.ClaimActions.MapJsonKey("role", "role", "role");

            options.GetClaimsFromUserInfoEndpoint = true;
            options.SaveTokens = true;

            options.SignedOutRedirectUri = "/";

            options.TokenValidationParameters = new TokenValidationParameters
            {
                NameClaimType = JwtClaimTypes.Name,
                RoleClaimType = JwtClaimTypes.Role,
            };
        });
    }

当我尝试添加时Microsoft.AspNetCore.Authentication.OpenIdConnect,出现不兼容错误。

在此处输入图像描述

我必须使用这个库的 3.1.9 版本而不是最新版本。

在此处输入图像描述

有什么想法吗?

标签: c#asp.netidentityserver4

解决方案


在你的情况下使用这个库的 v 3.1.* 是可以的。Microsoft.AspNetCore.Authentication.OpenIdConnect/3.1.10是与 .NET Core 3.1 兼容的最新版本。如果您想使用Microsoft.AspNetCore.Authentication.OpenIdConnect/5.0.1 ,您的应用程序应该是 .NET 5。

此外,我不确定此包中是否有任何针对 .NET 5 的重大更改,除了与 .NET 5 兼容。


推荐阅读