Asp.net core mvc User.Identity.IsAuthenticated=使用web api成功登录mvc core 3.0后为false
这就是问题所在 api中的我的登录函数Asp.net core mvc User.Identity.IsAuthenticated=使用web api成功登录mvc core 3.0后为false,asp.net-core-mvc,asp.net-core-3.0,Asp.net Core Mvc,Asp.net Core 3.0,这就是问题所在 api中的我的登录函数 public async Task<object> Login([FromBody] LoginDto model) { var user = _context.Users.FirstOrDefault(x => x.Email == model.Email || x.UserName == model.Email); var result = await
public async Task<object> Login([FromBody] LoginDto model)
{
var user = _context.Users.FirstOrDefault(x => x.Email == model.Email || x.UserName == model.Email);
var result = await _signInManager.PasswordSignInAsync(user.UserName, model.Password, model.RememberMe, false);
var IsAuthenticate = User.Identity.IsAuthenticated;
await _signInManager.SignInAsync(user, model.RememberMe);
if (result.Succeeded)
{
var appUser = _userManager.Users.SingleOrDefault(r => r.Email == model.Email);
return await GenerateJwtToken(model.Email, appUser);
}
return BadRequest("INVALID_LOGIN_ATTEMPT");
}
public异步任务登录([FromBody]LoginDto model)
{
var user=_context.Users.FirstOrDefault(x=>x.Email==model.Email | | x.UserName==model.Email);
var result=wait _signInManager.PasswordSignInAsync(user.UserName,model.Password,model.RememberMe,false);
var IsAuthenticate=User.Identity.IsAuthenticated;
wait _signInManager.SignInAsync(user,model.RememberMe);
if(result.successed)
{
var appUser=_userManager.Users.SingleOrDefault(r=>r.Email==model.Email);
return wait wait GenerateJwtToken(model.Email,appUser);
}
返回错误请求(“无效的登录尝试”);
}
我的登录函数在mvc中使用consume api
_LoginAsync()是使用api进行登录的静态函数
public async Task<IActionResult> Login(LoginDto model, string returnUrl = null)
{
ViewData["ReturnUrl"] = returnUrl;
if (ModelState.IsValid)
{
try
{
await _client.LoginAsync<LoginDto>(new Uri(_appSettings.WebApiBaseUrl + "Account/Login"), model);
ApplicationManager.SetMessageToUser("تم تسجيل الدخول بمجاح");
await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, false);
return Redirect("/" + returnUrl);
}
catch
{
}
}
ApplicationManager.SetMessageToUser("تأكد من اسم المستخدم وكلمة المرور");
// If we got this far, something failed, redisplay form
return View(model);
}
public async Task<string> LoginAsync<T>(Uri requestUrl, T content)
{
addHeaders();
var response = await _httpClient.PostAsync(requestUrl.ToString(), CreateHttpContent<T>(content));
string st = response.Content.ReadAsStringAsync().Result;
response.EnsureSuccessStatusCode();
var data = await response.Content.ReadAsStringAsync();
return (string)data;
}
公共异步任务登录(登录到模型,字符串returnUrl=null)
{
ViewData[“ReturnUrl”]=ReturnUrl;
if(ModelState.IsValid)
{
尝试
{
wait _client.LoginAsync(新Uri(_appSettings.WebApiBaseUrl+“Account/Login”),model);
应用程序管理器.SetMessageToUser(“应用程序管理器”);
wait_signInManager.PasswordSignInAsync(model.Email,model.Password,model.RememberMe,false);
返回重定向(“/”+returnUrl);
}
抓住
{
}
}
应用程序管理器.SetMessageToUser(“应用程序管理器”);
//如果我们走到这一步,有些东西失败了,重新显示形式
返回视图(模型);
}
_LoginAsync()是使用api进行登录的函数
public async Task<IActionResult> Login(LoginDto model, string returnUrl = null)
{
ViewData["ReturnUrl"] = returnUrl;
if (ModelState.IsValid)
{
try
{
await _client.LoginAsync<LoginDto>(new Uri(_appSettings.WebApiBaseUrl + "Account/Login"), model);
ApplicationManager.SetMessageToUser("تم تسجيل الدخول بمجاح");
await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, false);
return Redirect("/" + returnUrl);
}
catch
{
}
}
ApplicationManager.SetMessageToUser("تأكد من اسم المستخدم وكلمة المرور");
// If we got this far, something failed, redisplay form
return View(model);
}
public async Task<string> LoginAsync<T>(Uri requestUrl, T content)
{
addHeaders();
var response = await _httpClient.PostAsync(requestUrl.ToString(), CreateHttpContent<T>(content));
string st = response.Content.ReadAsStringAsync().Result;
response.EnsureSuccessStatusCode();
var data = await response.Content.ReadAsStringAsync();
return (string)data;
}
public异步任务LoginAsync(urirequesturl,T content)
{
addHeaders();
var response=wait_httpClient.PostAsync(requestUrl.ToString(),CreateHttpContent(content));
字符串st=response.Content.ReadAsStringAsync().Result;
response.EnsureSuccessStatusCode();
var data=await response.Content.ReadAsStringAsync();
返回(字符串)数据;
}
我的服务配置
public void ConfigureServices(IServiceCollection services)
{
services.AddSession(options => {
options.IdleTimeout = TimeSpan.FromMinutes(60);
});
services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
services.AddDbContext<ApplicationDbContext>(opt =>
opt.UseSqlServer("Data Source=.;Initial Catalog=ECommerceWebDb;Integrated Security=True"));
services.AddIdentity<IdentityUser, IdentityRole>(options =>
{
options.Password.RequireNonAlphanumeric = false;
options.Password.RequiredLength = 8;
options.User.RequireUniqueEmail = true;
})
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.AddControllers();
services.AddCors();
services.AddMvc();
services.AddControllersWithViews();
services.AddRazorPages();
var appSettingsSection = Configuration.GetSection("AppSettings");
services.Configure<AppSettings>(appSettingsSection);
// configure jwt authentication
var appSettings = appSettingsSection.Get<AppSettings>();
var key = Encoding.ASCII.GetBytes(appSettings.Secret);
services.AddAuthentication(x =>
{
x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(x =>
{
x.RequireHttpsMetadata = false;
x.SaveToken = true;
x.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateIssuer = false,
ValidateAudience = false
};
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
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();
app.UseStaticFiles();
app.UseRouting();
app.UseCors();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
endpoints.MapAreaControllerRoute(
name: "areas", "areas",
pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}");
endpoints.MapRazorPages();
});
}
public void配置服务(IServiceCollection服务)
{
services.AddSession(选项=>{
options.IdleTimeout=TimeSpan.frommins(60);
});
services.Configure(Configuration.GetSection(“AppSettings”);
services.AddDbContext(opt=>
opt.UseSqlServer(“数据源=;初始目录=电子商务WebDB;集成安全=True”);
服务.附加性(选项=>
{
options.Password.RequireNonAlphanumeric=false;
options.Password.RequiredLength=8;
options.User.RequireUniqueEmail=true;
})
.AddEntityFrameworkStores()
.AddDefaultTokenProviders();
services.AddControllers();
services.AddCors();
services.AddMvc();
services.AddControllersWithViews();
services.AddRazorPages();
var appsetingssection=Configuration.GetSection(“AppSettings”);
services.Configure(应用设置部分);
//配置jwt身份验证
var appSettings=appSettingsSection.Get();
var key=Encoding.ASCII.GetBytes(appSettings.Secret);
services.AddAuthentication(x=>
{
x、 DefaultAuthenticateScheme=JwtBearerDefaults.AuthenticationScheme;
x、 DefaultChallengeScheme=JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(x=>
{
x、 RequireHttpsMetadata=false;
x、 SaveToken=true;
x、 TokenValidationParameters=新的TokenValidationParameters
{
ValidateSuersigningKey=true,
IssuerSigningKey=新对称性安全密钥(密钥),
validateisuer=false,
ValidateAudience=false
};
});
}
//此方法由运行时调用。使用此方法配置HTTP请求管道。
public void配置(IApplicationBuilder应用程序、IWebHostEnvironment环境)
{
if(env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
其他的
{
app.UseExceptionHandler(“/Home/Error”);
//默认的HSTS值为30天。您可能希望在生产场景中更改此值,请参阅https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseCors();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(端点=>
{
endpoints.MapControllerRoute(
名称:“默认”,
模式:“{controller=Home}/{action=Index}/{id?}”);
endpoints.MapAreaControllerRoute(
名称:“区域”、“区域”,
模式:“{area:exists}/{controller=Home}/{action=Index}/{id?}”);
endpoints.MapRazorPages();
});
}
我把这个错误弄得很复杂
我认为这是每件事,如果你想要更多的帮助,请告诉我。登录为将来的请求保留给定的信息,它不会在当前信息上设置
HttpContext.User
。因此
User.Identity.IsAuthenticated
将在后续请求中为true
指
在ASP.NET中,用户身份验证涉及cookie的使用。任何试图访问私人页面的用户如果未携带有效的身份验证cookie,将被重定向到登录页面。登录页面在验证了所提供的凭据后,会发出cookie,cookie随后会与该用户的任何后续请求一起通过同一浏览器传播,直到过期。这与您可能从以前版本的ASP.NET中了解到的基本工作流相同。在ASP.NET Core中,它只是因为不同的中间件和运行时环境的不同配置而看起来有所不同
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
[Authorize]