Whenever i hit Login the user is Signed in using signinManager.PasswordSignInAsync and result.Succeeded is true. The problem is that if i Call Login second time the user does not presist. User.Identity.IsAuthenticated should be true next time but it is always false
[HttpGet("[action]")]
public async Task<IActionResult> Login()
{
try
{
if (User.Identity.IsAuthenticated)
{
Console.WriteLine("You are alredy Logged In...................");
var claims = User.Claims;
return Ok("Authenticated");
}
else
{
var result = await signinManager.PasswordSignInAsync("myEmail.com", "Password", true, true);
if (result.Succeeded)
{
Console.WriteLine("Logged in successfully....");
}
return Ok("Logged in successfully ");
}
}
catch (System.Exception e)
{
Console.WriteLine("........................................" +e.Message);
return Ok(e.Message);
throw;
}
}
ConfigureServices in StartUp.Cs looks like
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<DbContextBase>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<AppUser, IdentityRole>()
.AddEntityFrameworkStores<DbContextBase>()
.AddDefaultTokenProviders();
services.AddMvc();
}
and Configure Method in Startup.cs looks like:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions
{
HotModuleReplacement = true
});
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
routes.MapSpaFallbackRoute(
name: "spa-fallback",
defaults: new { controller = "Home", action = "Index" });
});
}
The Login Method must return "Authenticated" when hit second time.
To check user is authenticated or not using cookie scheme you can use
public UserService(
IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
public bool IsAuthenticated()
{
return _httpContextAccessor.HttpContext.User.Identity.IsAuthenticated;
}
And in your startup.cs add these to config cookie
services
.AddIdentity<User, ApplicationRole>(options =>
{
options.Password.RequireDigit = false;
options.Password.RequiredLength = 4;
options.Password.RequireLowercase = false;
options.Password.RequireNonAlphanumeric = false;
options.Password.RequireUppercase = false;
//lock out attempt
options.Lockout.AllowedForNewUsers = true;
options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(30);
options.Lockout.MaxFailedAccessAttempts = 3;
})
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
//The default value is 14 days.
services.ConfigureApplicationCookie(options =>
{
options.ExpireTimeSpan = TimeSpan.FromHours(1);
});
Please let me know if you still have any problem
You forgot to configure the actual authentication method, such as cookies.
Use something like this in your ConfigureServices
:
services.ConfigureApplicationCookie(options =>
{
// Cookie settings
options.Cookie.HttpOnly = true;
options.ExpireTimeSpan = TimeSpan.FromMinutes(5);
options.LoginPath = "/Identity/Account/Login";
options.AccessDeniedPath = "/Identity/Account/AccessDenied";
options.SlidingExpiration = true;
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.