0

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.

sevada
  • 3
  • 6
  • `And my model validation doesn't work either (asp-validation-for in inputs)`,Have you loaded `jquery.validate.min.js` and `jquery.validate.unobtrusive.min.js` in `_ValidationScriptsPartial` correctly when page loads? – Yiyi You Dec 29 '21 at 06:12
  • i have in my _ValidationScriptsPartial but the validation not working again and the client side validation is working but server side (asp-validation-for ) not working – sevada Dec 29 '21 at 14:28

1 Answers1

0

Look at this part of your form:

<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>

You are posting your request to the Admin action in Home Controller. You are not sending it to your AccountController. Change it to asp-action="Login" asp-controller="Account" .

About the model validation you should have this in your HttpPost Login:

if(!ModelState.IsValid)
{
return View(login);
}
AchoVasilev
  • 454
  • 5
  • 15
  • i have this code in HttpPost Login but when i change it to the admin action account controller in this time i have 500 status code( This page isnt working ,localhost is currently unable to handle this request ) error. – sevada Dec 29 '21 at 14:32
  • Could you post the admin action in the AccountController, because from the above snippet I do not see it. Are you using areas? – AchoVasilev Dec 29 '21 at 14:49
  • Did you try changing the form submit to asp-action="Login" asp-controller="Account" as I have pointed out? – AchoVasilev Dec 29 '21 at 14:56
  • no im not i just make controller and view and model for admin – sevada Dec 29 '21 at 14:58
  • yes i try that but not worked – sevada Dec 29 '21 at 14:59
  • Try setting a break point on if(ModelState.IsValid) and see if you enter it. Also when you send the post request does the login model get the data from the View? If you have problem with the validation you should have this check if(ModelState.IsValid == false) { return View(login) } – AchoVasilev Dec 29 '21 at 15:03