Hi
I was tried to prevent end user to direct access url from web browser.
I want is every end user must login befor use the system, but I have trouble.
The problem is when I tried to log in always redirect back to login form though username and password was enter corretly. Please hepl me.
Startup.cs
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(x => x.LoginPath = "/Akun/Login");
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Akun}/{action=Login}/{id?}");
});
AkunController.cs
public class AkunController : Controller
{
private readonly db_penginapanContext _context;
public AkunController(db_penginapanContext context)
{
_context = context;
}
[HttpGet]
[Authorize]
public IActionResult Index()
{
return View();
}
[HttpGet]
public IActionResult Login(string ReturnUrl = "/")
{
TblUser objLoginModel = new TblUser();
objLoginModel.ReturnUrl = ReturnUrl;
return View(objLoginModel);
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(TblUser login)
{
if (ModelState.IsValid)
{
var _login = _context.TblUsers.FirstOrDefaultAsync(x => x.Username == login.Username && x.Password == login.Password);
if (_login != null)
{
TempData["pesan"] = "Anda berhasil Login";
var claims = new List<Claim>() {
new Claim("username", "admin"),
new Claim(ClaimTypes.Name, login.Username),
new Claim(ClaimTypes.Role, "admin"),
};
var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
var principal = new ClaimsPrincipal(identity);
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal, new AuthenticationProperties()
{
IsPersistent = login.RememberLogin
});
return Redirect(nameof(Index));
}
else
{
ViewBag.Message = "Login gagal. Username atau Password anda salah !!!";
return View(login);
}
}
return View(login);
}
}