ASP.NET MVC记住我

zsohkypk  于 2023-01-27  发布在  .NET
关注(0)|答案(5)|浏览(214)

我有一个基于ASP.NETMVC4的项目,简单的身份验证.
我尝试让我的网站在用户选中"记住我"复选框时自动让用户登录。但是我遇到了问题。关闭浏览器并重新打开后,用户从未登录过。
检查后(http://forums.asp.net/t/1654606.aspx#4310292)我添加了一个机器密钥,由IIS生成。我设置了 * 在运行时自动生成 * 和 * 为每个应用程序生成唯一的密钥 * 都被禁用,我生成了密钥)。不幸的是,这没有工作。
看一下"Remember me" with ASP.NET MVC Authentication is not working,我已经添加了 * FormsAuthentication. SetAuthCookie(model. UserName,model. RememberMe)* 这一行,但是这也不起作用,所以我现在将其注解掉。
我尝试了ASP.NET MVC RememberMe上给出的答案,但似乎也不起作用。
我错过了什么明显的东西吗?

//FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);

if (model.RememberMe)
{
    //int timeout = model.RememberMe ? 525600 : 2; // Timeout in minutes,525600 = 365 days
    int timeout = 525600;
    var ticket = new FormsAuthenticationTicket(model.UserName, model.RememberMe, timeout);
    string encrypted = FormsAuthentication.Encrypt(ticket);
    var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encrypted);
    cookie.Expires = System.DateTime.Now.AddMinutes(timeout);//My Line
    Response.Cookies.Add(cookie);
}
7d7tgy0s

7d7tgy0s1#

我就是这么做的

public class MyAuthentication
{
    public static HttpCookie GetAuthenticationCookie(LoginModel model, bool persistLogin)
    {
         // userData storing data in ticktet and then cookie 
        JavaScriptSerializer js = new JavaScriptSerializer();

        var userData = js.Serialize(model);
        FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
                 1,
                 "akash",
                 DateTime.Now,
                 DateTime.Now.AddHours(1),
                 persistLogin,
                 userData);

        string encTicket = FormsAuthentication.Encrypt(authTicket);
        HttpCookie cookie= new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
        cookie.Expires = authTicket.Expiration; //must do it for cookie expiration 
        return cookie;
    }

    internal static bool Login(string UserName, string Password)
    {
        //UserName="akash" Password="akash"
        //check can be done by DB
        if (UserName== "akash" && Password == "akash")
            return true;
        else
            return false;
    }
}

然后

[HttpGet]
    [AllowAnonymous]
    public ActionResult Login()
    {
        //ViewBag.Message = "Your contact page.";
        HttpCookie cookie =  Request.Cookies[FormsAuthentication.FormsCookieName];
       // var ek = cookie.Value;
        try
        {
            //some times no cookie in browser
            JavaScriptSerializer js = new JavaScriptSerializer();
            FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);
            //string data = ticket.UserData;
            LoginModel model = js.Deserialize<LoginModel>(ticket.UserData);
            if (MyAuthentication.Login(model.UserName, model.Password) == true)
            {
                RedirectToAction("Index", "Home");
            }
        }
        catch
        {

        }
        return View();

你可以在Global.asax或授权过滤器上检查它.确保你有web.config有

<authentication mode="Forms">
  <forms defaultUrl="/Home/Login" loginUrl="/home/Login" timeout="2880">
  </forms>
</authentication>

和[Authorize]属性。

tnkciper

tnkciper2#

#region Register
public IActionResult Register()
{
    return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Register(RegisterViewModel registerVM)
{
    if (!ModelState.IsValid) { return View(registerVM); }
    AppUser appUser = new()
    {
        Fullname = registerVM.Fullname,
        UserName = registerVM.Username,
        Email = registerVM.Email,
        IsActive = true
    };
    var identityResult = await _userManager.CreateAsync(appUser, registerVM.Password);
    if (!identityResult.Succeeded)
    {
        foreach (var error in identityResult.Errors)
        {
            ModelState.AddModelError("", error.Description);
        }
        return View(registerVM);
    }
    return RedirectToAction(nameof(Login));
}
#endregion

#region Login and Logout
public IActionResult Login()
{
    return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Login(LoginViewModel loginViewModel)
{
    if (!ModelState.IsValid) return Content("ModelState");
    var user = await _userManager.FindByNameAsync(loginViewModel.UsernameOrEmail);
    if (user == null)
    {
        user = await _userManager.FindByEmailAsync(loginViewModel.UsernameOrEmail);
        if (user == null)
        {
            ModelState.AddModelError("", "Username/Email or Password incorrect");
            return View(loginViewModel);
        }

    }
    var signInResult = await _signInManager.PasswordSignInAsync(user, loginViewModel.Password, (bool)loginViewModel.RememberMe, true);

    if (signInResult.IsLockedOut)
    {
        ModelState.AddModelError("", "Biraz gözle");
        //return Content("IsLockedOut");
        return View(loginViewModel);
    }
    if (!signInResult.Succeeded)
    {
        ModelState.AddModelError("", "Username/Email or Password incorrect");
        //return Content("Succeeded");
        return View(loginViewModel);
    }
    if ((bool)!user.IsActive)
    {
        ModelState.AddModelError("", "not found");
        //return Content("IsActive");
        return View(loginViewModel);
    }
    return RedirectToAction("Index", "Home");
}

public async Task<IActionResult> Logout()
{
    if (User.Identity.IsAuthenticated)
    {
        await _signInManager.SignOutAsync();
        return RedirectToAction("Index", "Home");
    }
    return BadRequest();
}
#endregion
3pmvbmvn

3pmvbmvn3#

builder.Services.AddControllersWithViews();
    var constr = builder.Configuration["ConnectionStrings:Default"];
    builder.Services.AddDbContext<AppDbContext>(opt =>
    {
        opt.UseSqlServer(constr);
    });
    builder.Services.AddIdentity<AppUser, IdentityRole>(opt =>
    {
        opt.Password.RequiredLength = 8;
        opt.Password.RequireDigit= true;
        opt.Password.RequireLowercase= true;
        opt.Password.RequireUppercase= true;
        opt.Password.RequireNonAlphanumeric= true;
        opt.User.RequireUniqueEmail= true;
        opt.Lockout.MaxFailedAccessAttempts= 5;
        opt.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromSeconds(10);
        opt.Lockout.AllowedForNewUsers= true;
    }).AddEntityFrameworkStores<AppDbContext
().AddDefaultTokenProviders();
    
       builder.Services.AddSession(opt =>
       {
             opt.IdleTimeout = TimeSpan.FromSeconds(15);
       });
    
        builder.Services.ConfigureApplicationCookie(opt =>
    {
        opt.LoginPath = "/Auth/Login";
    });
app.UseSession();

app.UseAuthentication();
app.UseAuthorization();
polkgigr

polkgigr4#

#region ForgotPassword
public IActionResult ForgotPassword()
{
    return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ForgotPassword(ForgotPasswordViewModel model)
{
    if (model.YourEmail == null)
    {
        return View(model);
    }
    if (!ModelState.IsValid)
    {
        ModelState.AddModelError("", " 'New Password'-la 'Confirm Password' eyni olmalıdır");
        return View();
    }
    var user = await _userManager.FindByEmailAsync(model.YourEmail);
    if (user == null)
    {
        ModelState.AddModelError("", "İstifadəçi tapılmadı. Emailinizi düzgün daxil edib yenidən yoxlayın");
        return View();
    }
    var token = await _userManager.GeneratePasswordResetTokenAsync(user);
    var result = await _userManager.ResetPasswordAsync(user, token, model.NewPassword);
    if (!result.Succeeded)
    {
        foreach (var error in result.Errors)
        {
            ModelState.AddModelError("", error.Description);
        }
        return View(model);
    }

    return RedirectToAction(nameof(Login));
}
#endregion
ars1skjm

ars1skjm5#

//Extension
    public static async Task<string> CopyFileAsync(this IFormFile file,string wwwroot , params string[] folders)
        {
            try
            {
                var fileName = Guid.NewGuid().ToString() + file.FileName;
                var resultPath = wwwroot;
                foreach (var folder in folders)
                {
                    resultPath = Path.Combine(resultPath, folder);
                }
                resultPath = Path.Combine(resultPath, fileName);
                using (FileStream stream = new FileStream(resultPath, FileMode.Create))
                {
                    await file.CopyToAsync(stream);
                }
                return fileName;
            }
            catch (Exception)
            {
                throw;
            }
        }

//Helper
public static bool DeleteFile(params string[] path)
    {
        var resultPath = String.Empty;
        foreach (var item in path)
        {
            resultPath = Path.Combine(resultPath, item);
        }
        if (File.Exists(resultPath))
        {
            File.Delete(resultPath);
            return true;
        }
        return false;
    }

相关问题