There are multiple ways to authenticate/authorize users. I took a look at Oauth, token based, and identity authentication, and I didn't like any of them. What I ended up doing is when I come to let the user log in, I would run a SQL procedure, or run it against my Dbcontext and when a user successfully logs in, I would set a session variable to true. I fully understand all of the other authorization/authentication method but I feel like I want to own the code more.
So my main question would be, how secure is the code below? Or if I wanted to do it "manually", what other secure ways are there?
Page to only allow authorized users
if (HttpContext.Session.GetString(isAuthenticated) == true ) // authorized users only page
{
Response.Redirect("Login");
}
Login would look like this
public IActionResult OnPost()
{
var user = _context.UsersTableTest.FirstOrDefault(u => u.UserName == Username);
if (user != null && user.PasswordHash == Password)
{
// Successful login logic
HttpContext.Session.SetString("IsAuthenticated", "true");
return RedirectToPage("/Index"); // Redirect to a protected page
}
else
{
ModelState.AddModelError("", "Invalid login attempt.");
return Page();
}
}
Something like this in layout
@if (isAuthenticated == "true")
{
<div>
<form method="post" asp-page-handler="Logout" class="form-inline">
<button type="submit" class="btn btn-link text-dark">Logout</button>
</form>
</div>
}
else
{
<div>
<a class="btn btn-primary" asp-area="" asp-page="/Login">Login</a>
</div>
}
The approach you're taking, where you manually manage user authentication and authorization using session variables and custom database checks, can work, but there are several security concerns that you need to check:
Balancing control and security is important. Make sure you're not introducing vulnerabilities that could compromise user data or your application's security.