VSB
VSB

Reputation: 10375

ASP.NET MVC5 Identity: Avoid changing logged-in user after registration

I want to change the default Register Action of MVC5 ASP.NET Application.My Scenario is such that authorized users (such as admin) will login and they can create new users. However using below snippet, after creating user, current logged-in user will change to registered user.

How can I change below code to avoid changing logged-in user?

// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
    if (ModelState.IsValid)
    {
        var user = new ApplicationUser() { UserName = model.UserName,Name=model.Name };
        var result = await UserManager.CreateAsync(user, model.Password);
        if (result.Succeeded)
        {
            await SignInAsync(user, isPersistent: false);
            return RedirectToAction("Index", "Home");
        }
        else
        {
            AddErrors(result);
        }
    }

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

Upvotes: 2

Views: 932

Answers (2)

Erik Funkenbusch
Erik Funkenbusch

Reputation: 93444

Simply do this:

if (result.Succeeded)
{
    if (!User.IsAuthenticated)  // if they're already logged in, don't log in again
        await SignInAsync(user, isPersistent: false);
    return RedirectToAction("Index", "Home");
}

Upvotes: 1

VSB
VSB

Reputation: 10375

Remove SignInAsync and add [Authorize] annotation:

[HttpPost]
[Authorize]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
    if (ModelState.IsValid)
    {
        var user = new ApplicationUser() { UserName = model.UserName,Name=model.Name };
        var result = await UserManager.CreateAsync(user, model.Password);
        if (result.Succeeded)
        {
            //await SignInAsync(user, isPersistent: false);
            return RedirectToAction("Index", "Home");
        }
        else
        {
            AddErrors(result);
        }
    }

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

Upvotes: 0

Related Questions