服务器无法授权自己的令牌

时间:2019-11-13 01:46:17

标签: asp.net-core openid-connect

这是设置,我有一个身份验证服务器,可以向有角度的网站发行令牌。我在AuthServer中有一个控制器,该控制器需要使用[Authorize]系统仅允许有效的JWT令牌。当我检查控制器中的User变量时,它始终为null,但是当我检查控制器上的HttpRequestHeaders时,我看到正在发送令牌。

我也有一个Api服务器,可以很容易地使用JWT令牌和[Authorize]系统实现。 另一层,我在docker容器中同时运行Api和Auth服务器。

我从AuthServer获得的整个Startup.cs文件:

var connectionString = Configuration.GetConnectionString("Default");

        if (_env.IsDevelopment())
        {
            try
            {
                using (AppIdentityDbContext identityDb =
                        new AppIdentityDbContextFactory(connectionString).Create())
                {
                    int Pendings = identityDb.Database.GetPendingMigrations().Count();
                    identityDb.Database.Migrate();
                }

                using (PersistedGrantDbContext persistGrantDb =
                    new PersistedGrantDbContextFactory(connectionString).Create())
                {
                    int Pendings = persistGrantDb.Database.GetPendingMigrations().Count();
                    persistGrantDb.Database.Migrate();
                }
            }
            catch (Exception)
            {

            }
        }

        services.AddControllersWithViews();

        services.AddDbContextPool<AppIdentityDbContext>(options => options.UseSqlServer(connectionString));

        services
          .AddIdentity<AppUser, IdentityRole>(config=> {
              config.User.RequireUniqueEmail = true;
              config.SignIn.RequireConfirmedEmail = true;
          })
          .AddEntityFrameworkStores<AppIdentityDbContext>()
          .AddDefaultTokenProviders();

        services.AddIdentityServer().AddDeveloperSigningCredential()
           // this adds the operational data from DB (codes, tokens, consents)
           .AddOperationalStore(options =>
           {
               options.ConfigureDbContext = builder => builder.UseSqlServer(Configuration.GetConnectionString("Default"));
               // this enables automatic token cleanup. this is optional.
               options.EnableTokenCleanup = true;
               options.TokenCleanupInterval = (int)TimeSpan.FromDays(1).TotalSeconds; // interval in seconds
           })
           .AddInMemoryIdentityResources(Config.GetIdentityResources())
           .AddInMemoryApiResources(Config.GetApiResources())
           .AddInMemoryClients(Config.GetClients())
           .AddAspNetIdentity<AppUser>()
           .AddProfileService<AppUserProfileService>()
           .AddJwtBearerClientAuthentication();

        services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
            .AddIdentityServerAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme,
                jwtOptions =>
                {
                    // jwt bearer options
                    jwtOptions.Authority = _env.IsDevelopment() ? "https://localhost:5001" : "";
                    jwtOptions.RequireHttpsMetadata = _env.IsDevelopment() ? false : true;
                    jwtOptions.Audience = "resourceapi";
                    jwtOptions.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters()
                    {
                        ValidateAudience = false,
                        ValidateIssuer = _env.IsDevelopment() ? false : true,
                        ValidateActor = false,
                        ValidateIssuerSigningKey = false
                    };

                },
                referenceOptions =>
                {
                    // oauth2 introspection options


                });

        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
        services.AddCors(options => options.AddPolicy("AllowAll", p => p.AllowAnyOrigin()
           .AllowAnyMethod()
           .AllowAnyHeader()));


        services.Configure<EmailSettings>(Configuration.GetSection("EmailSettings"));
        services.AddSingleton<IEmailSender, SmtpSender>();

配置部分:

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();

            var forwardOptions = new ForwardedHeadersOptions
            {
                ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto,
                RequireHeaderSymmetry = false
            };

            forwardOptions.KnownNetworks.Clear();
            forwardOptions.KnownProxies.Clear();

            // ref: https://github.com/aspnet/Docs/issues/2384
            app.UseForwardedHeaders(forwardOptions);

        }
        app.UseCors("AllowAll");
        app.UseIdentityServer();
        app.UseAuthentication();
        app.UseAuthorization();
        app.UseStaticFiles();
        app.UseRouting();

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

检查AccountController: Controller内的用户

var u = User;
var _user = await _userManager.GetUserAsync(u);
var e = this._httpContextAccessor;

0 个答案:

没有答案