how to change the default path of the login page?
I have tried
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.LoginPath = "/e-tol/Login";
options.ExpireTimeSpan = TimeSpan.FromMinutes(15);
options.SlidingExpiration = true;
});
but when it runs, we still can use /Login , I need to prevent users from login by using /Login only
I have read many answers that are similar to my case but still do not work
UPDATE
This is my action method
public async Task<IActionResult> Index(string message)
{
ViewBag.Message = message;
if (HttpContext.User.Identity.IsAuthenticated) return RedirectAfterAuthenticated();
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
return View();
}
private IActionResult RedirectAfterAuthenticated()
{
var identity = (ClaimsIdentity)User.Identity;
var role = identity.Claims
.Where(i => i.Type == "IdRole")
.Select(i => i.Value)
.SingleOrDefault();
switch (role)
{
case null:
return RedirectToAction("Index", "Login");
default:
return RedirectToAction("Index", "Home");
}
}
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(string username, string password, string ReturnUrl)
{
var getUsername = await _context.Users.FirstOrDefaultAsync(a => a.Username == username);
var getPassword = await _context.Users.FirstOrDefaultAsync(b => b.Password == password);
if (getUsername != null && getPassword != null)
{
var claims = new List<Claim>
{
new Claim(ClaimTypes.NameIdentifier, Convert.ToString(getUsername.IdUser)),
new Claim("Nama", getUsername.Nama),
new Claim(ClaimTypes.Name, getUsername.Username),
new Claim("IdRole", Convert.ToString(getUsername.IdRole)),
};
var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,
new ClaimsPrincipal(claimsIdentity));
return Redirect(ReturnUrl == null ? "/Home" : ReturnUrl);
}
else
{
return RedirectToAction("Index", new RouteValueDictionary(new { message = "Username / Password Salah" }));
}
}
CodePudding user response:
Because you don't show the Controller catalog and I don't konw what is the corresponding method of /e-tol/Login , So I write a demo to show the situation:
I add [Route("/e-tol/Login")] to Login action in AccountController controller
HomeController
public class HomeController : Controller
{
[Authorize]
public IActionResult Create()
{
return View();
}
}
AccountController
public class AccountController : Controller
{
[Route("/e-tol/Login")]
public IActionResult Login()
{
return View();
}
}
StartUp
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(x => x.LoginPath = "/e-tol/Login");
Then,When I want to Log in ,I can only use /e-tol/Login,When i use /Login ,it will report a 404 error.

