Asp.net core HttpContext.User为null,用户已通过身份验证?
因此,我正在进行一个.NETCore2项目,我们希望创建一个基本平台,用于我们未来的项目。对于登录,我们使用Identity。我们已经全部设置好了,用户可以成功登录并设置cookie。出于某种原因,一旦我们调用HttpContext.User,这将导致空值。我很确定它确实找到了一个身份,但是这个身份是空的。我们已经检查了饼干,它很好,它有它的代币。我们确实添加了令牌身份验证,但在设置cookie时,这不应干扰cookie系统 下面是Startup.csAsp.net core HttpContext.User为null,用户已通过身份验证?,asp.net-core,asp.net-identity,Asp.net Core,Asp.net Identity,因此,我正在进行一个.NETCore2项目,我们希望创建一个基本平台,用于我们未来的项目。对于登录,我们使用Identity。我们已经全部设置好了,用户可以成功登录并设置cookie。出于某种原因,一旦我们调用HttpContext.User,这将导致空值。我很确定它确实找到了一个身份,但是这个身份是空的。我们已经检查了饼干,它很好,它有它的代币。我们确实添加了令牌身份验证,但在设置cookie时,这不应干扰cookie系统 下面是Startup.cs public IConfiguration
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.AddDbContext<MyIdentityDbContext>(options => options
.UseSqlServer("Data Source=PATH;Initial Catalog=DB;Persist Security Info=True;User ID=ID;Password=*******"));
services.AddSingleton<IJwtFactory, JwtFactory>();
services.AddAuthentication(options =>
{
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
}).AddCookie();
services.AddIdentity<User, IdentityRole>(options =>
{
options.SignIn.RequireConfirmedEmail = true;
options.User.RequireUniqueEmail = false;
options.Tokens.PasswordResetTokenProvider = TokenOptions.DefaultEmailProvider;
})
.AddEntityFrameworkStores<MyIdentityDbContext>()
.AddDefaultTokenProviders();
services.Configure<IISOptions>(options =>
{
options.ForwardClientCertificate = false;
});
var jwtAppSettingOptions = Configuration.GetSection(nameof(JwtIssuerOptions));
services.Configure<JwtIssuerOptions>(options =>
{
options.Issuer = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)];
options.Audience = jwtAppSettingOptions[nameof(JwtIssuerOptions.Audience)];
options.SigningCredentials = new SigningCredentials(_signingKey, SecurityAlgorithms.HmacSha256);
});
var tokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidIssuer = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)],
ValidateAudience = true,
ValidAudience = jwtAppSettingOptions[nameof(JwtIssuerOptions.Audience)],
ValidateIssuerSigningKey = true,
IssuerSigningKey = _signingKey,
RequireExpirationTime = false,
ValidateLifetime = true,
ClockSkew = TimeSpan.Zero
};
services
.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(cfg =>
{
cfg.ClaimsIssuer = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)];
cfg.TokenValidationParameters = tokenValidationParameters;
cfg.SaveToken = true;
});
services.Configure<IdentityOptions>(options =>
{
// Password settings
options.Password.RequireDigit = true;
options.Password.RequiredLength = 8;
options.Password.RequireNonAlphanumeric = true;
options.Password.RequireUppercase = true;
options.Password.RequireLowercase = true;
options.Password.RequiredUniqueChars = 6;
// Lockout settings
options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(30);
options.Lockout.MaxFailedAccessAttempts = 5;
options.Lockout.AllowedForNewUsers = true;
// User settings
options.User.RequireUniqueEmail = true;
});
services.ConfigureApplicationCookie(options =>
{
// Cookie settings
options.LoginPath = "/Account/Login"; // If the LoginPath is not set here, ASP.NET Core will default to /Account/Login
options.LogoutPath = "/Account/Logout"; // If the LogoutPath is not set here, ASP.NET Core will default to /Account/Logout
options.AccessDeniedPath = "/Account/AccessDenied"; // If the AccessDeniedPath is not set here, ASP.NET Core will default to /Account/AccessDenied
options.SlidingExpiration = true;
options.Cookie = new CookieBuilder
{
HttpOnly = true,
Name = "MyAuthToken",
Path = "/",
SameSite = SameSiteMode.Lax,
SecurePolicy = CookieSecurePolicy.SameAsRequest
};
});
services.AddAuthorization(options =>
{
options.AddPolicy("EmployeeOnly", policy => policy.RequireClaim("Employee"));
options.AddPolicy("OwnerOnly", policy => policy.RequireClaim("Owner"));
options.AddPolicy("AdminOnly", policy => policy.RequireClaim("Admin"));
options.AddPolicy("ModeratorOnly", policy => policy.RequireClaim("Moderator"));
});
services.AddTransient<IEmailSender, EmailSender>();
services.Configure<AuthMessageSenderOptions>(Configuration);
services.AddMvc().AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver());
}
以及我们用于登录用户的代码:
User _user = await _userManager.GetUserAsync(HttpContext.User);
var result = await _signInManager.PasswordSignInAsync(model.Email,
model.Password, true, false);
您编写了两次
AddAuthentication
,一次用于Cookie
,一次用于JWT
,并覆盖默认值
仅使用AddAuthentication
一次,并向其添加Cookie
和JWT
services.AddAuthentication(options =>
{
// set schema here
})
.AddCookie(config =>
{
//config cookie
})
.AddJwtBearer(config =>
{
//config jwt
});
现在您有了两个身份验证方案,您必须选择要对请求进行身份验证的方案
[授权(CookieAuthenticationDefaults.AuthenticationScheme)]
或
[授权(JwtBearerDefaults.AuthenticationScheme)]
或者两者兼而有之
[Authorize($“{CookieAuthenticationDefaults.AuthenticationScheme},{JWTBeareDefaults.AuthenticationScheme}”)
我可能会快速将此标记为答案。因此,这适用于[授权]身份验证。但是我的HttpContext.User仍然返回null。我已将默认方案设置为cookie身份验证。它确实找到了一个标识,但它的属性都为null。。