Authentication ASP Core 3 react模板HttpContext.User.IsAuthenticated()在登录后返回False
在我的项目上工作了一段时间后,我发布了Authentication ASP Core 3 react模板HttpContext.User.IsAuthenticated()在登录后返回False,authentication,asp.net-core,asp.net-identity,identityserver4,asp.net-authorization,Authentication,Asp.net Core,Asp.net Identity,Identityserver4,Asp.net Authorization,在我的项目上工作了一段时间后,我发布了HttpContext.User.IsAuthenticated()在登录后返回False,我需要知道应该在哪里查找导致此问题的错误。 这是登录,OnPost方法 public async Task<IActionResult> OnPostAsync(string returnUrl = null) { returnUrl = returnUrl ?? Url.Content("~/"); if (ModelState.IsVa
HttpContext.User.IsAuthenticated()
在登录后返回False,我需要知道应该在哪里查找导致此问题的错误。
这是登录,OnPost方法
public async Task<IActionResult> OnPostAsync(string returnUrl = null)
{
returnUrl = returnUrl ?? Url.Content("~/");
if (ModelState.IsValid)
{
var user = _userManager.Users.FirstOrDefault(u => u.StudentNumber == Input.StudentNumber.ToString());
if (!(user is null) && await _userManager.CheckPasswordAsync(user, Input.Password))
await _signInManager.SignInAsync(user, Input.RememberMe);
var isUserAuthenticated = HttpContext.User.IsAuthenticated();
return Redirect(returnUrl);
}
// If we got this far, something failed, redisplay form
return Page();
}
SignInManager.SignInAsync()
仅为给定用户创建cookie。此方法不会设置HttpContext.User
但是在具有cookie的下一个请求中,您可以在AuthenticationMiddleware
和HttpContext.User.IsAuthenticated()之后访问HttpContext.User
AuthenticationMiddleware
始终尝试使用默认方案对用户进行身份验证,由于在AddDefaultIdentity
之后有AddIdentityServer
,identity server将成为您的默认方案,但当您调用SignInManager.SignInAsync
时会触发identity
方案
总之,通过此配置,您的身份验证中间件
始终尝试对IdentityServer
的请求进行身份验证,如果您想要为API提供其他方案,则应使用[授权(AuthenticationSchemes=“Identity.Application”)]
p.S.Identity.Application
是ASP.NET Identity的身份验证方案因为您有密码,所以可以改用PasswordSignInAsync
。它返回一个SignInResult
,您可以检查是否成功或查看错误是什么@crgolden我也试过了,但是虽然结果是成功的,IsAuthenticated
属性是错误的。IsSignedIn
返回什么?既然您正在使用UserManager
和SignInManager
,为什么还要尝试直接访问HttpContext
?这样做会使以后的单元测试更加困难,因为您无法真正模拟HttpContext
。@crgoldenIsSignedIn
也会返回False。我可能不会在项目中使用单元测试,我也不关心HttpContext
。我只需要访问API中经过身份验证的用户,但API返回401错误。在下一个请求中,HttpContext.user.IsAuthenticated()
为False,当我要访问授权API时,我得到401错误。这也有点奇怪,因为react-navbar组件将更新为用户身份验证视图并显示用户的电子邮件。我得到了这个错误“属性参数必须是常量表达式、类型表达式或属性参数类型的数组创建表达式”。这个错误意味着属性参数应该是常量,并且在编译时是已知的。工作。你能把它变成一个答案吗?根据你的更新,颠倒了服务.AddDefaultIdentity
和'services.AddAuthentication'的顺序,并把属性改回了[Authorize]
,这也行得通。我只是想知道这种方法是否有任何问题,或者它很好,不会引起任何问题。这会导致另一个问题,因为现在IdentityServer
依赖默认的身份验证方案
public void ConfigureServices(IServiceCollection services)
{
services.AddAutoMapper();
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.AddDefaultIdentity<ApplicationUser>(option=>option.Password.RequireNonAlphanumeric=false)
.AddEntityFrameworkStores<ApplicationDbContext>();
services.AddIdentityServer()
.AddApiAuthorization<ApplicationUser, ApplicationDbContext>();
services.AddAuthentication()
.AddIdentityServerJwt();
services.AddMvc(options => options.EnableEndpointRouting = false)
.AddNewtonsoftJson();
// In production, the React files will be served from this directory
services.AddSpaStaticFiles(configuration =>
{
configuration.RootPath = "ClientApp/build";
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/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.UseSpaStaticFiles();
app.UseAuthentication();
app.UseIdentityServer();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller}/{action=Index}/{id?}");
});
app.UseSpa(spa =>
{
spa.Options.SourcePath = "ClientApp";
if (env.IsDevelopment())
{
spa.UseReactDevelopmentServer(npmScript: "start");
}
});
}