如何更改登錄頁面的默認路徑?
我試過了
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.LoginPath = "/e-tol/Login";
options.ExpireTimeSpan = TimeSpan.FromMinutes(15);
options.SlidingExpiration = true;
});
但是當它運行時,我們仍然可以使用 /Login ,我需要僅使用 /Login 來防止用戶登錄
我已經閱讀了許多與我的案例類似但仍然不起作用的答案
更新
這是我的行動方法
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" }));
}
}
uj5u.com熱心網友回復:
因為你沒有顯示Controller目錄,也不知道對應的方法是什么/e-tol/Login,所以寫了個demo來展示一下情況:
我添加 [Route("/e-tol/Login")]到控制器中的Login動作AccountController
家庭控制器
public class HomeController : Controller
{
[Authorize]
public IActionResult Create()
{
return View();
}
}
帳戶控制器
public class AccountController : Controller
{
[Route("/e-tol/Login")]
public IActionResult Login()
{
return View();
}
}
啟動
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(x => x.LoginPath = "/e-tol/Login");
然后,當我想登錄時,我只能使用/e-tol/Login,當我使用時/Login,它會報404錯誤。

轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/374019.html
標籤:网站 asp.net核心 .net核心 asp.net-core-3.1
