简体   繁体   中英

ASP.NET MVC Simple logon page, username & password match but getting unauthorized message

I'm creating an application for school that has to be done using the MVC pattern. To begin with, I am trying to get a simple register and logon page up and running as if I can store and retrieve in my DB then the rest of the application should be fairly straightforward. I am using my University's sql server for my DB and using the ADO.NET entity data model (for the first time).

I was using an online tutorial to help me and it all seemed to work well enough, but the trouble now is that when trying to log-on using details already in my table I get a 'Http 401.0 - Unauthorized' page.

I know that what I'm entering in the email & password box is matching what is being retrieved from the DB as I tested with labels and they all matched. I'm using ASP.NET 4.5.2 if that helps.

未经授权的页面

My table is simple-

Email (pk)(varchar) - For logon
Password (varchar) - For logon
First_Name (varchar)

My code is as follows;

UserLogon View -

public class UserLogon
{    
    [Required]
    [Display(Name = "Email")]
    public string Email { get; set; }

    [Required]
    [DataType(DataType.Password)]
    [Display(Name = "Password")]
    public string Password { get; set; }
}

User Manager View -

public class UserManager
{
    private ac9555fEntities dre = new ac9555fEntities();
    public string GetUserPassword(string userEmail)
    {
        var user = from o in dre.UserTables where o.Email == userEmail  select o;
        if (user.ToList().Count > 0)
            return user.First().Password;
        else
            return string.Empty;
    }
}

Account Controller -

public class AccountController : Controller
{

    public ActionResult LogOn()
    {
        return View();
    }

    //
    // POST: /Account/LogOn

    [HttpPost]
    public ActionResult LogOn(UserLogon model, string returnUrl)
    {

        if (ModelState.IsValid)
        {

            UserManager userManager = new UserManager();
            string password = userManager.GetUserPassword(model.Email);


            if (string.IsNullOrEmpty(password))
            {

                ModelState.AddModelError("", "The user login or password provided is incorrect.");
            }

            if (password == model.Password)
            {

                FormsAuthentication.SetAuthCookie(model.Email, false);
                if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                    && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                {
                    return Redirect(returnUrl);
                }
                else
                {
                    return RedirectToAction("Welcome", "Home");
                }
            }
            else
            {
                ModelState.AddModelError("", "The password provided is incorrect.");
            }
        }

        // If we got this far, something failed, redisplay form
        return View(model);
    }
    }

Home Controller -

    public ActionResult Index()
    {         
        return View();
    }

    [Authorize]
    public ActionResult Welcome()
    {
        return View();
    }

LogOn View -

@model WebApplication5.Models.ViewModels.UserLogon
....
@using (Html.BeginForm())
{
    ....
    @Html.EditorFor(model => model.Email)
    ....
    @Html.EditorFor(model => model.Password)
    ....
    <input type="submit" value="Log On" />
}

I do apologize if I have included too much/not enough code, this is my first time using MVC/ADO.NET entity data model. From looking at other stuff on here and elsewhere on the web, I feel like there is an extra layer of authorization that isn't needed but any of the solutions I tried, failed to work. Can anyone spot where my code is flawed?

<system.web>
<compilation debug="true" targetFramework="4.5.2" />
<httpRuntime targetFramework="4.5.2" />
</system.web>

The error is occurring because your weg.config file dos not specify to use Forms Authentication. Modify the <system.web> section to include

<system.web>
    ....
    <authentication mode="Forms">
        <forms loginUrl="~/Account/LogOn" timeout="10" /> // adjust as required
    </authentication>
</system.web>

There however a number of other issues with your code.

  • You should never store passwords in the data base as plain text (they need to be hashed and salted)
  • Your second ModelState.AddModelError(..) code should be identical to the the first (never reveal which of the two values is incorrect)
  • Its not really clear what your trying to do with your if(Url.IsLocalUrl(returnUrl) && ... code, but once you authenticate the user, it should just be if (Url.IsLocalUrl(returnUrl)) { return Redirect(returnUrl); } else { return RedirectToAction("Welcome", "Home"); }

I recommend you work through the basic tutorials on Security, Authentication and Authorization and use the built in features of MVC and Identity to handle all this correctly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM