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

时间:2017-05-19 19:34:41

标签: c# asp.net-core openid identityserver4

我一直致力于迁移单片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 个答案:

答案 0 :(得分:2)

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

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

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

答案 1 :(得分: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类删除以下代码,替换为上述

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

您的身份服务器上需要上述代码,而不是API或任何其他客户端