I am trying to create custom login logout where whout loged in user can not access home view. and after loged in user can redirect to home view. If user trying to access home view so he has to be redirect to login page.
here is my code...
LoginPartial View
@using Microsoft.AspNetCore.Identity
@inject SignInManager<IdentityUser> SignInManager
@inject UserManager<IdentityUser> UserManager
@using Microsoft.AspNetCore.Http;
@{
var userId = Context.Session.GetString("username");
if (userId == null)
{
Context.Response.Redirect("/Login");
}
else
{
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link text-light mt-2">Hello @Context.Session.GetString("username")!</a>
</li>
<li class="nav-item">
<form class="form-inline" asp-area="Identity" asp-page="/Account/Logout" asp-route-returnUrl="@Url.Action("Index", "Home", new { area = "" })">
<button type="submit" class="nav-link btn btn-link text-white-50">Logout</button>
</form>
</li>
</ul>
}
}
here is my Login controller
public class LoginController : Controller
{
private readonly ApplicationDbContext _db;
public LoginController(ApplicationDbContext context)
{
_db = context;
}
public IActionResult Index()
{
return View("Login");
}
[HttpPost]
public IActionResult LoginProcess(string username, string password)
{
var userId = _db.logins.Where(p=>p.UserName==username && p.Password==password && p.ExpiryDate> DateTime.Now).Select(p=>p.Id).FirstOrDefault();
if (userId>0)
{
HttpContext.Session.SetString("username", username);
return Redirect("~/Reception/Home");
}
else
{
ViewBag.error = "Invalid Login..!";
return View("Login");
}
}
[HttpGet]
public IActionResult Logout()
{
HttpContext.Session.Remove("username");
return RedirectToAction("Index");
}
}
}
User can not open Home view without login.
Without running the code, it looks on first pass like you're setting the user on an infinite loop. Your view checks for a username and redirects to the "/login" endpoint on failure, which subsequently returns the View, which checks again, and so on. Eventually, the browser hits the brakes on you.
From what you're presenting, it looks like you're trying to roll your own login mechanism rather than take advantage of what ASP NET Core can offer to help deal with some of this automatically. Take a look at Simple authorization in ASP.NET Core