首页 文章

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

提问于
浏览
13

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

此方法获取令牌但仍未使用后端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
            },


        });
    }

和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

2 回答

  • 2

    添加了nuget package here和以下代码来修复:

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

    这允许API托管IdentityServer4并将其自身用作身份验证 . 然后在MvcClient中,可以将承载令牌传递给API .

  • 0

    是的,您需要将 IdentityServer4.AccessTokenValidation 包添加到API项目中 . 并查看下面的评论

    app.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions
    {
       Authority = "https://localhost:44348/", //Identity server host uri
       ApiName = "api", // Valid Api resource name 
       AllowedScopes = scopes // scopes:List<string> 
    });
    

    您应该从API的StartUp类和 replace with the above 中获得以下代码: replace with the above

    services.AddIdentityServer() // Configures OAuth/IdentityServer framework
                .AddInMemoryIdentityResources(IdentityServerConfig.GetIdentityResources())
                .AddInMemoryClients(IdentityServerConfig.GetClients(serviceSettings))
                .AddAspNetIdentity<ExtranetUser>()
                .AddTemporarySigningCredential();
    

    您的Identity Server上不需要API或任何其他客户端上面的代码

相关问题