I am new to programming, I don't get any errors in my program but my login doesn't work and when I enter the password and username and click the button, it doesn't go to the admin page - it actually doesn't go anywhere and returns the login page (itself).
My admin action method has [Authorize] attribute and everything is ok in the database I think, and data insert with seed data. Please help.
startup.cs
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseStatusCodePagesWithRedirects("/Home/Error");
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
AccountController.cs
public IActionResult Login()
{
return View();
}
[HttpPost]
public IActionResult Login(Admin login, FormCollection form)
{
if (ModelState.IsValid)
{
var user = loginRepository.IsExistUser(login.UserName, login.Password);
if (user != "")
{
return Redirect("/Home/Admin");
}
else
{
ModelState.AddModelError("UserName", "there is no user");
}
}
var claims = new List<Claim>
{
new Claim(ClaimTypes.NameIdentifier,login.LoginID.ToString()),
new Claim(ClaimTypes.Name,login.UserName),
new Claim(ClaimTypes.Name,login.Password),
};
var Identity = new ClaimsIdentity(claims, `enter code here`CookieAuthenticationDefaults.AuthenticationScheme);
var principal = new ClaimsPrincipal(Identity);
var properties = new AuthenticationProperties
{
IsPersistent = login.RememberMe
};
HttpContext.SignInAsync(principal, properties);
//********recaptcha * ********
string urlToPost = "https://www.google.com/recaptcha/api/siteverify";
string secretKey = "";
string gRecaptchaResponse = form["g-recaptcha-response"];
var postData = "secret=" + secretKey + "&response=" + gRecaptchaResponse;
// send post data
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlToPost);
request.Method = "POST";
request.ContentLength = postData.Length;
request.ContentType = "application/x-www-form-urlencoded";
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
streamWriter.Write(postData);
}
// receive the response now
string result = string.Empty;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
result = reader.ReadToEnd();
}
}
ViewBag.IsSuccess = false;
return View("login");
}
public IActionResult Lougout()
{
HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
return Redirect("/Account/Login");
}
LoginRepository.cs
public string IsExistUser(string username, string password)
{
return db.Admin.SingleOrDefault(u => u.UserName == username && u.Password == password).ToString();
}
ILoginRepository.cs
string IsExistUser(string username, string password);
login.cshtml
@model DataLayer.Admin
@{
ViewData["LoginTitle"] = "sign in";
Layout = "/Views/Shared/_LoginLayout.cshtml";
}
<div class="container">
<form onsubmit="return true" name="loginform" method="post" class="box box1 band form pb-3 pt-3 col-lg-12 col-md-12 col-sm-12 col-12">
<div class="row">
<div class="form-group floating-label-group col-12">
<i class="zmdi zmdi-account userdarkmode userdarkmode1"></i>
<input asp-for="UserName" name="UserName" class="form-control UserName UserName1" required title="enter your username" />
<label asp-for="UserName" class="control-label floating-label-username floating-label-username1">username:</label>
<span asp-validation-for="UserName" class="text-danger"></span>
</div>
</div>
<div class="row">
<div class="form-group floating-label-group col-12">
<i class="zmdi zmdi-key keydarkmode keydarkmode1"></i>
<input asp-for="Password" name="Password" class="form-control Password Password1" autocomplete="off" required title="entere your password" />
<label asp-for="Password" class="control-label floating-label-password floating-label-password1">password:</label>
<span asp-validation-for="Password" class="text-danger"></span>
</div>
</div>
<div class="row">
<div class="form-group">
<input asp-for="RememberMe" class="form-check-input form-control rememberdarkmode rememberdarkmode1 col-1" name="RememberMe" />
<label asp-for="RememberMe" class="form-check-label rememberdarkmode rememberdarkmode1 opt col-11"></label>
</div>
</div>
<div class="form-group col-12">
<input type="submit" value="enter" asp-action="Admin" asp-controller="Home" class="btn btn-outline-success form-control col-6" />
</div>
<div>
<a asp-action="Index" asp-controller="Home" class="text text1 col-6 text-secondary">go to form</a>
</div>
</form>
</div>
@section Scripts {
@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
model.cs
using System.ComponentModel.DataAnnotations;
namespace DataLayer
{
public class Admin
{
[Key]
public int LoginID { get; set; }
[Display(Name = "username")]
[Required(ErrorMessage = "please enter your username")]
[MaxLength(20)]
public string UserName { get; set; }
[Display(Name = "password")]
[Required(ErrorMessage = "please enter your password")]
[MaxLength(20)]
[DataType(DataType.Password)]
public string Password { get; set; }
[Display(Name = "remember me")]
public bool RememberMe { get; set; }
}
}
HomeController
[Authorize]
public IActionResult Admin()
{
return View();
}
And my model validation doesn't work either (asp-validation-for in inputs) - I don't know why.