通过ASP Core MVC,Web API和IdentityServer4进行身份验证?

Lin*_*yer 13 c# openid asp.net-core identityserver4

我一直致力于迁移单片ASP Core MVC应用程序以使用服务架构设计.MVC前端网站使用HttpClient从ASP Core Web API加载必要的数据.前端MVC应用程序的一小部分还需要使用IdentityServer4(与后端API集成)进行身份验证.这一切都很有效,直到我Authorize在Web API上的控制器或方法上放置了一个属性.我知道我需要以某种方式将用户授权从前端传递到后端才能使其正常工作,但我不确定如何工作.我试过获取access_token:User.FindFirst("access_token")但它返回null.然后我尝试了这个方法,我可以获得令牌:

var client = new HttpClient("url.com");
var token = HttpContext.Authentication.GetTokenAsync("access_token")?.Result;
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
Run Code Online (Sandbox Code Playgroud)

此方法获取令牌但仍未使用后端API进行身份验证.我对这个OpenId/IdentityServer概念很陌生,任何帮助都将不胜感激!

以下是MVC Client Startup类的相关代码:

    private void ConfigureAuthentication(IApplicationBuilder app)
    {
        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationScheme = "Cookies",
            AutomaticAuthenticate = true,
            ExpireTimeSpan = TimeSpan.FromMinutes(60)
        });
        JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
        app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions
        {
            AuthenticationScheme = "oidc",
            SignInScheme = "Cookies",

            Authority = "https://localhost:44348/",
            RequireHttpsMetadata = false,

            ClientId = "clientid",
            ClientSecret = "secret",

            ResponseType = "code id_token",
            Scope = { "openid", "profile" },
            GetClaimsFromUserInfoEndpoint = true,
            AutomaticChallenge = true, // Required to 302 redirect to login
            SaveTokens = true,

            TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
            {
                NameClaimType = "Name",
                RoleClaimType = "Role",
                SaveSigninToken = true
            },


        });
    }
Run Code Online (Sandbox Code Playgroud)

和API的StartUp类:

        // Add authentication
        services.AddIdentity<ExtranetUser, IdentityRole>(options =>
        {
            // Password settings
            options.Password.RequireDigit = true;
            options.Password.RequiredLength = 8;
            options.Password.RequireNonAlphanumeric = true;
            options.Password.RequireUppercase = true;
            options.Password.RequireLowercase = true;

            // Lockout settings
            options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(30);
            options.Lockout.MaxFailedAccessAttempts = 10;

            // User settings
            options.User.RequireUniqueEmail = true;
        })
            .AddDefaultTokenProviders();
        services.AddScoped<IUserStore<ExtranetUser>, ExtranetUserStore>();
        services.AddScoped<IRoleStore<IdentityRole>, ExtranetRoleStore>();
        services.AddSingleton<IAuthorizationHandler, AllRolesRequirement.Handler>();
        services.AddSingleton<IAuthorizationHandler, OneRoleRequirement.Handler>();
        services.AddSingleton<IAuthorizationHandler, EditQuestionAuthorizationHandler>();
        services.AddSingleton<IAuthorizationHandler, EditExamAuthorizationHandler>();
        services.AddAuthorization(options =>
        {
            /* ... etc .... */
        });
        var serviceProvider = services.BuildServiceProvider();
        var serviceSettings = serviceProvider.GetService<IOptions<ServiceSettings>>().Value;
        services.AddIdentityServer() // Configures OAuth/IdentityServer framework
            .AddInMemoryIdentityResources(IdentityServerConfig.GetIdentityResources())
            .AddInMemoryClients(IdentityServerConfig.GetClients(serviceSettings))
            .AddAspNetIdentity<ExtranetUser>()
            .AddTemporarySigningCredential(); // ToDo: Add permanent SigningCredential for IdentityServer
Run Code Online (Sandbox Code Playgroud)

Lin*_*yer 2

此处添加了nuget 包以及以下代码来修复:

app.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions
{
   Authority = "https://localhost:44348/",
   ApiName = "api"
});
Run Code Online (Sandbox Code Playgroud)

这允许 API 托管 IdentityServer4 并使用自身作为身份验证。然后,在 MvcClient 中,可以将不记名令牌传递给 API。