无法到达ConsentController

时间:2018-07-28 08:19:31

标签: identityserver4 angular6 asp.net-core-2.1

我有一个可以在https://localhost:44391访问的Angular 6应用,该应用与另一个服务器进行通信,以在https://localhost:44380进行身份验证和授权。

我能够在客户端应用程序和身份验证服务器之间建立通信。但是,在成功验证用户身份而不是重定向到同意页面之后,它将返回到服务器登录页面。

我正在使用带有IdentityServer4的VS 2017,asp.net core 2.1

以下是我的身份验证服务器启动类

public partial class MainWindow : Window
{
    public Person Obj { get; set; }

    public MainWindow()
    {
        Obj = new Person();

        List<string> subjects1 = new List<string>();

        subjects1.Add("C++");
        subjects1.Add("C");
        subjects1.Add("C#");

        List<string> subjects2 = new List<string>();

        subjects2.Add("JAVA");
        subjects2.Add("JS");
        subjects2.Add("CSS");

        Obj.StudDetail.Add("Kushagra", subjects1);
        Obj.StudDetail.Add("Yash", subjects2);

        DataContext = this;
    }

    public class Person
    {
        private Dictionary<string, List<string>> _studDetail = new Dictionary<string, List<string>>();

        public Dictionary<string, List<string>> StudDetail
        {
            get { return _studDetail; }
            set { _studDetail = value; }
        }
    }
}

我的客户端配置:

public class Startup
{
    private readonly IHostingEnvironment _environment;
    public Startup(IHostingEnvironment env)
    {
        JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
        _environment = env;
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);

        if (env.IsDevelopment())
        {
            // For more details on using the user secret store see https://go.microsoft.com/fwlink/?LinkID=532709
            builder.AddUserSecrets<Startup>();
        }

        builder.AddEnvironmentVariables();
        Configuration = builder.Build();
    }

    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 stsConfig = Configuration.GetSection("stsConfig");
        var userDbConnString = Configuration["ConnectionStrings:DefaultConnection"];
        var useLocalCertStore = Convert.ToBoolean(Configuration["UseLocalCertStore"]);
        var certificateThumbprint = Configuration["CertificateThumbprint"];
        var migrationsAssembly = typeof(UserDbContext).GetTypeInfo().Assembly.GetName().Name;


        X509Certificate2 cert;

        if (_environment.IsProduction())
        {
            if (useLocalCertStore)
            {
                using (X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine))
                {
                    store.Open(OpenFlags.ReadOnly);
                    var certs = store.Certificates.Find(X509FindType.FindByThumbprint, certificateThumbprint, false);
                    cert = certs[0];
                    store.Close();
                }
            }
            else
            {
                // Azure deployment, will be used if deployed to Azure
                var vaultConfigSection = Configuration.GetSection("Vault");
                var keyVaultService = new KeyVaultCertificateService(vaultConfigSection["Url"], vaultConfigSection["ClientId"], vaultConfigSection["ClientSecret"]);
                cert = keyVaultService.GetCertificateFromKeyVault(vaultConfigSection["CertificateName"]);
            }
        }
        else
        {
            cert = new X509Certificate2(Path.Combine(_environment.ContentRootPath, "localhost.pfx"), "##Rojutet11");
        }

        services.AddDbContext<UserDbContext>(options =>
            options.UseSqlServer(Configuration["ConnectionStrings:DefaultConnection"]));

        services.Configure<StsConfig>(Configuration.GetSection("StsConfig"));
        services.Configure<EmailSettings>(Configuration.GetSection("EmailSettings"));

        services.AddSingleton<LocService>();
        services.AddLocalization(options => options.ResourcesPath = "Resources");

        //services.AddAuthentication();
        services.AddAuthentication(
            //o => {
            //    o.DefaultScheme = IdentityServerAuthenticationDefaults.AuthenticationScheme;
            //    o.DefaultAuthenticateScheme = IdentityServerAuthenticationDefaults.AuthenticationScheme;
            //}
        );

        services.AddIdentity<ApplicationUser, UserRole>(config =>
        {
            config.SignIn.RequireConfirmedEmail = true;
        }).AddEntityFrameworkStores<UserDbContext>()
       .AddDefaultTokenProviders();

        services.Configure<RequestLocalizationOptions>(
            options =>
            {
                var supportedCultures = new List<CultureInfo>
                    {
                        new CultureInfo("en-US"),
                        new CultureInfo("de-CH"),
                        new CultureInfo("fr-CH"),
                        new CultureInfo("it-CH")
                    };

                options.DefaultRequestCulture = new RequestCulture(culture: "en-US", uiCulture: "en-US");
                options.SupportedCultures = supportedCultures;
                options.SupportedUICultures = supportedCultures;

                var providerQuery = new LocalizationQueryProvider
                {
                    QueryParameterName = "ui_locales"
                };

                // Cookie is required for the logout, query parameters at not supported with the endsession endpoint
                // Only works in the same domain
                var providerCookie = new LocalizationCookieProvider
                {
                    CookieName = "defaultLocale"
                };
                // options.RequestCultureProviders.Insert(0, providerCookie);
                options.RequestCultureProviders.Insert(0, providerQuery);
            });

        //services.AddCors();

        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
            .AddViewLocalization()
            .AddDataAnnotationsLocalization(options =>
            {
                options.DataAnnotationLocalizerProvider = (type, factory) =>
                {
                    var assemblyName = new AssemblyName(typeof(SharedResource).GetTypeInfo().Assembly.FullName);
                    return factory.Create("SharedResource", assemblyName.Name);
                };
            });
        //services.AddAntiforgery(
        //    options =>
        //    {
        //        options.Cookie.Name = "_af";
        //        options.Cookie.HttpOnly = true;
        //        options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
        //        options.HeaderName = "X-XSRF-TOKEN";
        //    });

        services.AddTransient<IProfileService, IdentityWithAdditionalClaimsProfileService>();

        services.AddTransient<IEmailSender, AuthMessageSender>();



        services.AddIdentityServer(
            //x=>x.IssuerUri="https://localhost:44338"
            ).AddSigningCredential(cert)
          .AddDefaultEndpoints()
          .AddConfigurationStore(options =>
          {
              options.ConfigureDbContext = builder =>
                builder.UseSqlServer(userDbConnString, db => db.MigrationsAssembly(migrationsAssembly));
          })
          .AddOperationalStore(options => {
              options.ConfigureDbContext = builder =>
              builder.UseSqlServer(userDbConnString, db => db.MigrationsAssembly(migrationsAssembly));
          }).AddProfileService<IdentityWithAdditionalClaimsProfileService>();

        services.AddDbContext<UserDbContext>(options =>
            options.UseSqlServer(userDbConnString, b => b.MigrationsAssembly("KAMAAG.Data")));

        services.Configure<MvcOptions>(options =>
        {
            options.Filters.Add(new RequireHttpsAttribute());
        });
        services.AddTransient<IEmailSender, AuthMessageSender>();
        services.AddTransient<ISmsSender, AuthMessageSender>();
        services.Configure<AuthMessageSenderOptions>(Configuration);
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();
        loggerFactory.AddConsole(LogLevel.Trace);

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseDatabaseErrorPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }

        var locOptions = app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>();
        app.UseRequestLocalization(locOptions.Value);



        app.UseCors(builder =>
           builder
           .WithOrigins("https://localhost:44391")              
           .AllowAnyMethod()
           .AllowCredentials()
           .AllowAnyHeader());

        app.UseCsp(opts => opts.DefaultSources(directive => directive.Self())
            .ImageSources(directive => directive.Self()
               .CustomSources("*"))
            .ScriptSources(directive => directive.Self()
                .UnsafeInline())
            .StyleSources(directive => directive.Self()
                .UnsafeInline()));


        app.UseStaticFiles();

        app.UseAuthentication();
        app.UseIdentityServer();

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }
}

AccountController:登录方法

public class Clients
{
    public static IEnumerable<Client> Get()
    {
        return new List<Client>
        {
            new Client
            {
                ClientName = "kamaagwebclient",
                ClientId = "kamaagwebclient",
                AccessTokenType = AccessTokenType.Reference,
                AccessTokenLifetime = 330,// 330 seconds, default 60 minutes
                IdentityTokenLifetime = 30,
                AllowedGrantTypes = GrantTypes.Implicit,
                AllowAccessTokensViaBrowser = true,
               AllowRememberConsent=true,

                RedirectUris = new List<string>
                {
                    "https://localhost:44391",
                    "https://localhost:44391/silent-renew.html"
                },
                PostLogoutRedirectUris = new List<string>
                {
                    "https://localhost:44391/unauthorized",
                     "https://localhost:44391"
                },
                AllowedCorsOrigins = new List<string>
                {
                    "https://localhost:44391",
                     "http://localhost:44391"
                },
                AllowedScopes = new List<string>
                {
                    IdentityServerConstants.StandardScopes.OpenId,
                    IdentityServerConstants.StandardScopes.Email,
                    IdentityServerConstants.StandardScopes.Profile,
                   "resourcescope",
                   "securefilescope",
                    "kamaagresource",
                    "securedfiles",
                    "role"
                },
                RequireConsent=true
            }
        };
    }
}

好吧,所以几天后我将脑袋撞墙,我决定尝试使用this tutorial之后的webpack方法。我在本教程中选择了整个angularclient项目,进行了必要的改装,同意页面出现了,这让我有些失望。我认为Angular-Cli方法提供了更加顺畅的行驶体验。也许我只是在某处做某事,真的很愚蠢,因为看来我是唯一遇到此问题的人

0 个答案:

没有答案