簡體   English   中英

通過ASP Core MVC,Web API和IdentityServer4進行身份驗證?

[英]Pass through authentication with ASP Core MVC, Web API and 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

這里添加了nuget包和以下代碼來修復:

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

這允許API托管IdentityServer4並將其自身用作身份驗證。 然后在MvcClient中,可以將承載令牌傳遞給API。

是的,您需要將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();

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM