用户未在中间件中进行身份验证,但在控制器中进行了身份验证

时间:2020-07-16 09:35:31

标签: .net-core openiddict

我正在使用OpenIddict软件包在我的.net core Api应用中处理身份验证。在我的控制器内部,可以看到用户,用户的声明,角色等。但是在中间件中,我无权访问该用户,就好像该用户未通过身份验证一样。

我认为我在ConfigureServices的{​​{1}}或Configure方法中丢失了一些东西。

Startup.cs
public void ConfigureServices(IServiceCollection services)
        {

            // Add framework services.
            services.AddMvc(
                    config =>
                    {
                        //We are adding a default policy required for all requests
                        var policyBuilder =
                            new AuthorizationPolicyBuilder(OpenIddictValidationDefaults.AuthenticationScheme);
                        
                        var policy = policyBuilder.RequireAuthenticatedUser()
                            .Build();
                        config.Filters.Add(new AuthorizeFilter(policy));
                    }
                );


            services.AddDbContext<TGDbContext>((ctx, options) =>
            {
                options.UseSqlServer(Configuration["ConnectionStrings:DefaultConnection"]);
                options.UseOpenIddict();
            }, ServiceLifetime.Scoped, ServiceLifetime.Scoped);

            
            // Register the OpenIddict services.
            services.AddOpenIddict()
                .AddCore(options =>
                {
                    options.UseEntityFrameworkCore()
                        .UseDbContext<TGDbContext>();
                })
                .AddServer(options =>
                {
                    options.UseMvc();
                    options.EnableTokenEndpoint( "/connect/token");
                    options.AllowPasswordFlow();
                    options.AllowRefreshTokenFlow();
                    options.AcceptAnonymousClients();
                    options.AllowCustomFlow("GuestLogin");
                    options.RegisterScopes("Booking");
                    if (this._env.IsDevelopment())
                        options.DisableHttpsRequirement(); // Note: Requires Https in production
                    options.RegisterScopes(
                        OpenIdConnectConstants.Scopes.OpenId,
                        OpenIdConnectConstants.Scopes.Email,
                        OpenIdConnectConstants.Scopes.Phone,
                        OpenIdConnectConstants.Scopes.Profile,
                        OpenIdConnectConstants.Scopes.OfflineAccess,
                        OpenIddictConstants.Scopes.Roles);
                })
                .AddValidation();

            // add identity
            services.AddIdentity<ApplicationUser, ApplicationRole>()
                .AddEntityFrameworkStores<TGDbContext>()
                .AddDefaultTokenProviders();

            // Configure Identity options and password complexity here
            services.Configure<IdentityOptions>(options =>
            {
                // User settings
                options.User.RequireUniqueEmail = false;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireUppercase = false;
                options.Password.RequireLowercase = false;
                options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(30);
                options.Lockout.MaxFailedAccessAttempts = 5;
                options.ClaimsIdentity.UserNameClaimType = OpenIdConnectConstants.Claims.Name;
                options.ClaimsIdentity.UserIdClaimType = OpenIdConnectConstants.Claims.Subject;
                options.ClaimsIdentity.RoleClaimType = OpenIdConnectConstants.Claims.Role;
            });

            services.AddAuthorization(options =>
            {
                options.AddPolicy(.....);
             ....
             ....
             ....           
            });
  .....
  .....
  .....

}

我正在使用public void Configure(IApplicationBuilder app, IHostingEnvironment env) { .... .... .... app.UseAuthentication(); app.Use(async (context, next) => { var isAuthenticated = context.User.Identity.IsAuthenticated; // isAuthenticated is false here // also context.User.Claims is empty Console.WriteLine(isAuthenticated); await next.Invoke(); }); .... .... .... app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller}/{action=Index}/{id?}"); }); } .Net Core 2.2定位OpenIddict 2.0.1

1 个答案:

答案 0 :(得分:1)

您所看到的行为是预期的(并非特定于OpenIddict):通过注册指向OpenIddict验证处理程序的AuthorizeFilter,您只需配置MVC来验证承载令牌,而不能配置其余部分您的应用,包括中间件。

要将OpenIddict配置为默认身份验证方案,请调用

services.AddAuthentication(options =>
{
    // When targeting OpenIddict 3.0, OpenIddictValidationAspNetCoreDefaults
    // must be used instead of OpenIddictValidationDefaults.
    options.DefaultAuthenticateScheme = OpenIddictValidationDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = OpenIddictValidationDefaults.AuthenticationScheme;
});