MVC 5 login custome DB

I am moving from mvc 3 to mvc 5, I know that they changed authentication in .Net 4.5.1 (OWIN autonomy).

all I need to get into the site is that Request.IsAuthenticated is right, I do not want microsoft membership, I want to use my database.

I tried everything, but even this one did not work

var claims = new List<Claim>();
claims.Add(new Claim(ClaimTypes.Name, "Name"));
claims.Add(new Claim(ClaimTypes.Email, "mail@mail.com"));
var identity = new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie);

var ctx = HttpContext.GetOwinContext();
var authenticationManager = ctx.Authentication;
authenticationManager.SignIn(identity);

I really don't know what to do, but I want to log in using my own database, only has a username and password

+3
source share
2 answers

Try this, I hope this helps you.

    [AllowAnonymous]
    public ActionResult Login(string returnUrl)
    {
        ViewBag.ReturnUrl = returnUrl;
        return View();
    }

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
    {
        if (ModelState.IsValid)
        {
            var user = MyViewModels.checkUser(model.UserName, model.Password);
            if (user!=null)
            {
                SignInAsync();
                return RedirectToAction("Welcome");
            }
            else
            {
                ModelState.AddModelError("", "Invalid username or password.");
            }
        }
        return View(model);
    }

    private void SignInAsync()
    {
        var claims = new List<Claim>();
        claims.Add(new Claim(ClaimTypes.Name, "UserName"));
        claims.Add(new Claim(ClaimTypes.Email, "User@mail.com"));
        var id = new ClaimsIdentity(claims,
                                    DefaultAuthenticationTypes.ApplicationCookie);

        var ctx = Request.GetOwinContext();
        var authenticationManager = ctx.Authentication;
        authenticationManager.SignIn(id);
    }

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

If you add the [Authorize] attribute to the action, it only redirects the username and password that allow

Function to get username and password from database

    public static UserTable checkUser(string userName, string password)
    {
        DemoEntities db = new DemoEntities();
        var query = (from u in db.UserTables
                     where u.UserName == userName && u.Password == password
                     select u).FirstOrDefault();
        if(query!=null)
            return query;
        else
            return null;
    }
+3
+1

All Articles