Docker 如何使Identityserver重定向到我的web应用程序?

Docker 如何使Identityserver重定向到我的web应用程序?,docker,asp.net-identity,microservices,identityserver4,ocelot,Docker,Asp.net Identity,Microservices,Identityserver4,Ocelot,我正在尝试将Identity Server 4与Ocelot集成,并对WebApp(asp.net core 3.1)进行身份验证,然后在请求经过身份验证的情况下访问api 为此,我创建了一个解决方案 网关-Ocelot(最新版本) IdentityService-Identity Server 4(最新版本) 示例API(asp.net core 3.1 web API) WebApp(asp.net core 3.1 web app) 我在webapp的homecontroller中的一

我正在尝试将Identity Server 4与Ocelot集成,并对WebApp(asp.net core 3.1)进行身份验证,然后在请求经过身份验证的情况下访问api

为此,我创建了一个解决方案

  • 网关-Ocelot(最新版本)
  • IdentityService-Identity Server 4(最新版本)
  • 示例API(asp.net core 3.1 web API)
  • WebApp(asp.net core 3.1 web app)
我在webapp的homecontroller中的一个操作方法中添加了[Authorize]属性

以上都是在docker中运行的docker compose

我能做的

  • 通过网关命中api
  • 运行web应用程序并查看UI
  • 已知端点及其来自IdentityService的响应
  • IdentityService正在重定向浏览器登录页
我不能做的事

  • 在登录页面上,当我使用bob/bob登录时,它保持相同的登录页面
  • 我调试了login方法,发现用户已成功验证,最后它创建了一个重定向URL,如下所示
识别服务 Cofig.cs

网关 StartUp.cs

// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.


using IdentityServer4;
using IdentityServer4.Models;
using System.Collections.Generic;

namespace IdentityServer
{
    public static class Config
    {
        private const string SampleAPI_Secret = "tT1CCYyY7P";
        public static IEnumerable<IdentityResource> IdentityResources =>
            new IdentityResource[]
            { 
                new IdentityResources.OpenId()
            };

        public static IEnumerable<ApiScope> ApiScopes =>
            new ApiScope[]
            { 
                new ApiScope("sampleapi.read","Read your data"),
                new ApiScope("sampleapi.write","Write your data"),
                new ApiScope("sampleapi.delete","Delete your data")
            };

        public static IEnumerable<ApiResource> ApiResources =>
             new List<ApiResource>
            {
                new ApiResource("sampleAPI", "Sample API"){
                    Scopes = { "sampleapi.read", "sampleapi.write", "sampleapi.delete" },
                }
            };
        

        public static IEnumerable<Client> Clients =>
            new Client[] 
            {
                new Client(){ 
                    ClientId = "MS.UI",
                    AllowedGrantTypes = GrantTypes.HybridAndClientCredentials,
                    AllowOfflineAccess = true,
                    ClientSecrets = { new Secret("z71C0PyDjR".Sha256()) },
                    RedirectUris ={"http://localhost:5003/signin-oidc" },
                    PostLogoutRedirectUris = { "http://localhost:5003"},
                    FrontChannelLogoutUri = "http://localhost:5003/signout-oidc",
                    AllowedScopes = {
                        IdentityServerConstants.StandardScopes.OpenId,
                        IdentityServerConstants.StandardScopes.Profile,
                        IdentityServerConstants.StandardScopes.Email,
                        "sampleapi.read",
                        "sampleapi"
                    },
                    AllowAccessTokensViaBrowser = true,
                    RequirePkce =false
                },
            
            };
    }
}

using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.AspNetCore.Authentication;

using IdentityModel;
using Microsoft.AspNetCore.Http;

namespace MS.UI
{
    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.Configure<CookiePolicyOptions>(options=> {
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });
            services.AddControllersWithViews();
            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
            services.AddAuthentication(options =>
            {
                Microsoft.IdentityModel.Logging.IdentityModelEventSource.ShowPII = true;
                options.DefaultScheme = "Cookies";
                options.DefaultChallengeScheme = "oidc";
            }).AddCookie("Cookies")
               .AddOpenIdConnect("oidc", options =>
                {
                    options.Authority = "http://localhost:5002";
                    options.MetadataAddress = "http://identityserver/.well-known/openid-configuration";
                    options.RequireHttpsMetadata = false;
                    options.Events.OnRedirectToIdentityProvider = context =>
    {
                        // Intercept the redirection so the browser navigates to the right URL in your host
                        context.ProtocolMessage.IssuerAddress = "http://localhost:5002/connect/authorize";
                        return Task.CompletedTask;
                    };

                    options.SignInScheme = "Cookies";
                    options.ClientId = "MS.UI";
                    options.ClientSecret = "z71C0PyDjR";
                    options.ResponseType = "code id_token";
                    //options.UsePkce = true;

                    options.SaveTokens = true;
                    //options.GetClaimsFromUserInfoEndpoint = true;
                    options.Scope.Clear();
                    options.Scope.Add("profile");
                    options.Scope.Add("sampleapi.read");
                    options.Scope.Add("offline_access");
                 
                });
           
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            //app.UseHttpsRedirection();
            

            app.UseStaticFiles();
            app.UseCookiePolicy();
            app.UseRouting();
            
            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using IdentityServer4.AccessTokenValidation;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Ocelot.DependencyInjection;
using Ocelot.Middleware;

namespace MS.Gateway
{
    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)
        {
            var authenticationProviderKey = "TestKey";

            Action<IdentityServerAuthenticationOptions> options = o =>
            {
                o.RequireHttpsMetadata = false;
                o.Authority = "http://identityserver";
                o.ApiName = "sampleAPI";
                o.SupportedTokens = SupportedTokens.Both;
                o.ApiSecret = "secret";
            };

            services.AddAuthentication()
                .AddIdentityServerAuthentication(authenticationProviderKey, options);
            services.AddOcelot();

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            //app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
            app.UseOcelot().Wait();
        }
    }
}

Docker Compose

version: '3.7'

services:
  ms.api:
    image: msapi
    build:
      context: .
      dockerfile: MS.API/Dockerfile
  
  ms.gateway:
    image: ms.gateway
    build: 
      context: .
      dockerfile: MS.Gateway/Dockerfile

  identityserver:
    image: identityserver
    build: 
      context: .
      dockerfile: IdentityServer/Dockerfile
  
  ms.ui:
    image: ms.ui
    build: 
      context: .
      dockerfile: MS.UI/Dockerfile

Docker编写覆盖

version: '3.7'

services:
  ms.api:
    environment:
      - ASPNETCORE_ENVIRONMENT=Development
      - ASPNETCORE_URLS=http://+:80
    ports:
      - "5000:80"
   
    volumes:
      - ${APPDATA}/Microsoft/UserSecrets:/root/.microsoft/usersecrets:ro
      - C:/Users/dheer/.aspnet/https:/https:ro
    networks: 
      - msnetwork

  ms.gateway:
    environment:
      - ASPNETCORE_ENVIRONMENT=Development
      - ASPNETCORE_URLS=http://+:80
    ports:
      - "5001:80"
    networks: 
      - msnetwork

  identityserver:
    environment:
      - ASPNETCORE_ENVIRONMENT=Development
      - ASPNETCORE_URLS=http://+:80
    ports:
      - "5002:80"
    networks: 
      - msnetwork

  ms.ui:
    environment:
      - ASPNETCORE_ENVIRONMENT=Development
      - ASPNETCORE_URLS=http://+:80
    ports:
      - "5003:80"
    networks: 
      - msnetwork

networks: 
  msnetwork:

volumes: 
  gateway_voludme:
请帮帮我。 此完整的源代码也可用@
Branch-Add-IDS4

如果您收到“代码挑战要求”错误,那是因为客户端没有发送以下两个PKCE头:

&code_challenge=XXXXXXXXX...
&code_challenge_method=S256
请在Fiddler中验证这一点

另外,取消注释这一行也是一个好的开始:

//options.UsePkce = true;
查看IdentityServer日志也是进一步诊断此问题的好地方

此外,PKCE仅适用于授权代码流。您正在使用

AllowedGrantTypes = GrantTypes.HybridAndClientCredentials,
当您应该使用此选项时:

AllowedGrantTypes = GrantTypes.Code,
如果仍要使用当前的混合流,则需要使用禁用PKCE 客户端定义中包含以下内容:

RequirePkce = false

这里需要回答StackOverflow中的问题,问题中需要包含所需的代码等。这不是一个在你的回购协议上请求工作的地方。我的目的不是让任何人在我的回购协议上工作,我认为有太多的代码,所以他们可以很容易地在github上查看。。很抱歉,您的身份服务器设置是什么@DheerajKumar,正如James所建议的,试着在这里发布你的代码片段,并添加对gh repo的引用-这将帮助你获得更快的响应,我会做的that@nahidf,我已根据以下[18:13:07调试]IdentityServer4.Validation.AuthorizationRequestValidator检查PKCE参数的提示日志更新了问题[18:13:07错误]缺少IdentityServer4.Validation.AuthorizationRequestValidator代码\u质询[18:13:07错误]IdentityServer4.Endpoints.AuthorizeEndpoint请求验证失败我已对该行进行了注释,是的,这两个标头未发送。请指导我该怎么做?我改进了回答如果我需要禁用Pkce,那么我应该首先将其设置为真吗?否,您在客户端定义中将其设置为假,以禁用该特定c的Pkce留置权。
version: '3.7'

services:
  ms.api:
    image: msapi
    build:
      context: .
      dockerfile: MS.API/Dockerfile
  
  ms.gateway:
    image: ms.gateway
    build: 
      context: .
      dockerfile: MS.Gateway/Dockerfile

  identityserver:
    image: identityserver
    build: 
      context: .
      dockerfile: IdentityServer/Dockerfile
  
  ms.ui:
    image: ms.ui
    build: 
      context: .
      dockerfile: MS.UI/Dockerfile

version: '3.7'

services:
  ms.api:
    environment:
      - ASPNETCORE_ENVIRONMENT=Development
      - ASPNETCORE_URLS=http://+:80
    ports:
      - "5000:80"
   
    volumes:
      - ${APPDATA}/Microsoft/UserSecrets:/root/.microsoft/usersecrets:ro
      - C:/Users/dheer/.aspnet/https:/https:ro
    networks: 
      - msnetwork

  ms.gateway:
    environment:
      - ASPNETCORE_ENVIRONMENT=Development
      - ASPNETCORE_URLS=http://+:80
    ports:
      - "5001:80"
    networks: 
      - msnetwork

  identityserver:
    environment:
      - ASPNETCORE_ENVIRONMENT=Development
      - ASPNETCORE_URLS=http://+:80
    ports:
      - "5002:80"
    networks: 
      - msnetwork

  ms.ui:
    environment:
      - ASPNETCORE_ENVIRONMENT=Development
      - ASPNETCORE_URLS=http://+:80
    ports:
      - "5003:80"
    networks: 
      - msnetwork

networks: 
  msnetwork:

volumes: 
  gateway_voludme:
&code_challenge=XXXXXXXXX...
&code_challenge_method=S256
//options.UsePkce = true;
AllowedGrantTypes = GrantTypes.HybridAndClientCredentials,
AllowedGrantTypes = GrantTypes.Code,
RequirePkce = false