Home > Back-end >  my project login doesnt work in asp.net core
my project login doesnt work in asp.net core

Time:12-29

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 >

    <form  onsubmit="return true" name="loginform" method="post" >
        <div >
            <div >
                <i ></i>
                <input asp-for="UserName" name="UserName"  required title="enter your username" />
                <label asp-for="UserName" >username:</label>
                <span asp-validation-for="UserName" ></span>
            </div>
        </div>

        <div >
            <div >
                <i ></i>
                <input asp-for="Password" name="Password"  autocomplete="off" required title="entere your password" />
                <label asp-for="Password" >password:</label>
                <span asp-validation-for="Password" ></span>
            </div>
        </div>

        <div >
            <div >
                <input asp-for="RememberMe"  name="RememberMe" />
                <label asp-for="RememberMe" ></label>
            </div>
        </div>
        <div >
            <input type="submit" value="enter" asp-action="Admin" asp-controller="Home"  />
        </div>

        <div>
            <a asp-action="Index" asp-controller="Home" >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; }
    }
}

And my model validation doesn't work either (asp-validation-for in inputs) - I don't know why.

CodePudding user response:

Where do you have your function call out in the button parameters?

Use https://getbootstrap.com/docs/5.0/components/buttons/ -> use button, not input type="submit". https://stackoverflow.com/a/33663114/11394571

You need a https://www.educba.com/button-in-asp-net/:

OnClick="Login"

CodePudding user response:

Look at this part of your form:

<div >
<input type="submit" value="enter" asp-action="Admin" asp-controller="Home"  />
</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);
}
  • Related