admin管理员组

文章数量:1405993

I am working on ASP.NET Core 2.2. After the user registers for the first time, the user is redirected to their personal page, which requires logging in.

This is the script in my login.cshtml:

<script>
$('#btnregister').on('click', function (e) {
    e.preventDefault();
       $.ajax({
          type: 'POST',
          url: '@Url.Action("Register", "Account")',
          data: { username: $("#username").val(), pass: $('#pass').val() }
     }).done(function (res) {
        if (res.status === 'success') {
        window.location.href = 'https://localhost:5001/UserPanel/UserInfo/Index';
     });
});
</script>

And this is my code in AccountController:

[HttpPost]
public async Task<IActionResult> Register(string username, string pass)
{
    var user = new ApplicationUsers
    {
       PasswordHash = pass,
       UserName = username,
    };

    // Register
    IdentityResult registerResult = await _userManager.CreateAsync(user, pass);

    if (registerResult.Succeeded)
    {
        registerResult = await _userManager.AddToRoleAsync(user, "normaluser");
    }

    // Login
    var result = await _signInManager.PasswordSignInAsync(username, pass , true, lockoutOnFailure: false);

   if (result.Succeeded)
   {
       return Json(new { status = "success" });
   }
}

In this code, the user is first registered, then the user is logged in and redirected to the path

window.location.href = 'https://localhost:5001/UserPanel/UserInfo/Index';

The user is successfully redirected to the specified path and the page is displayed. But as soon as he clicks on any button, user is logged out.

How can I prevent the user from being logged out after registration?

Update

This is UserInfo controller

[Area("UserPanel")]
[Authorize(Roles = "normaluser")]
public class UserInfoController : Controller
{
    private readonly UserManager<ApplicationUsers> _userManager;
    public UserInfoController(UserManager<ApplicationUsers> userManager)
    {
        _userManager = userManager;
    }

    public IActionResult Index()
    {
        ViewBag.getuser = _userManager.GetUserName(HttpContext.User);
        return View();
    }
}

I am working on ASP.NET Core 2.2. After the user registers for the first time, the user is redirected to their personal page, which requires logging in.

This is the script in my login.cshtml:

<script>
$('#btnregister').on('click', function (e) {
    e.preventDefault();
       $.ajax({
          type: 'POST',
          url: '@Url.Action("Register", "Account")',
          data: { username: $("#username").val(), pass: $('#pass').val() }
     }).done(function (res) {
        if (res.status === 'success') {
        window.location.href = 'https://localhost:5001/UserPanel/UserInfo/Index';
     });
});
</script>

And this is my code in AccountController:

[HttpPost]
public async Task<IActionResult> Register(string username, string pass)
{
    var user = new ApplicationUsers
    {
       PasswordHash = pass,
       UserName = username,
    };

    // Register
    IdentityResult registerResult = await _userManager.CreateAsync(user, pass);

    if (registerResult.Succeeded)
    {
        registerResult = await _userManager.AddToRoleAsync(user, "normaluser");
    }

    // Login
    var result = await _signInManager.PasswordSignInAsync(username, pass , true, lockoutOnFailure: false);

   if (result.Succeeded)
   {
       return Json(new { status = "success" });
   }
}

In this code, the user is first registered, then the user is logged in and redirected to the path

window.location.href = 'https://localhost:5001/UserPanel/UserInfo/Index';

The user is successfully redirected to the specified path and the page is displayed. But as soon as he clicks on any button, user is logged out.

How can I prevent the user from being logged out after registration?

Update

This is UserInfo controller

[Area("UserPanel")]
[Authorize(Roles = "normaluser")]
public class UserInfoController : Controller
{
    private readonly UserManager<ApplicationUsers> _userManager;
    public UserInfoController(UserManager<ApplicationUsers> userManager)
    {
        _userManager = userManager;
    }

    public IActionResult Index()
    {
        ViewBag.getuser = _userManager.GetUserName(HttpContext.User);
        return View();
    }
}
Share Improve this question edited Mar 7 at 15:58 topcool asked Mar 6 at 14:27 topcooltopcool 2,7207 gold badges32 silver badges56 bronze badges 1
  • as is there's really no reason to use Ajax for this. Just do a standard form POST and redirect to a relative page from backend. (that'll ensure domain is same...) ex: return RedirectToPage("./UserPanel/UserInfo/Index"), or use appropriate path depending on where the register page is located. You'll probably need to add more info to get an answer to your question though... is this a cross-domain request? (remember that localhosts with different ports are treated as separate... 'withCredentials' might be needed) Are you using cookies for auth? Maybe also show your UserInfo/Index controller. – browsermator Commented Mar 6 at 17:05
Add a comment  | 

1 Answer 1

Reset to default 0

Based on your code, you are using Asp Core Identity to achieve the register and login function.

After register the user success, you could try to check the AspNetUsers table, whether the new user is insert into the database, if you are enabled EmailConfirmed, we need to make user the EmailCongirmed column is True.

Then, by default, after login success using Identity, the user identity will be stored in the cookie, so the logged-out issue might relate the Identity cookie.

Try to use F12 developer tools to check the Identity Cookie expires time:

If the issue relates the cookie expires time, you could use the following code to extend the expiration time:

services.ConfigureApplicationCookie(options =>
    {
        options.ExpireTimeSpan = TimeSpan.FromMinutes(30);
    });

More detail information, see Asp Core Identity Cookie settings.

Besides, you can also check the Browser setting, make sure it does not disable/clear cookie.

本文标签: jqueryASPNET Core prevent logout after register new userStack Overflow