Search code examples
asp.net-mvcasp.net-identity

ASP.NET MVC 5 SignIn BackDoor for development environment


I have an ASP.NET application that is using Microsoft Open ID connect for user authentication. I don't store any passwords in my database. Though I do store role and claims using asp Identity.

I need a way such that I can "log in" as any User for testing.

Controller:

#if DEBUG
[AllowAnonymous]
[HttpGet]
public ActionResult LoginOffline()
{
        if (Request.IsLocal == false)
        {
            return HttpNotFound();
        }

        List<ApplicationUser> model = UserManager.Users.ToList();

        return View(model);
}

[AllowAnonymous]
[HttpPost]
public async Task<ActionResult> LoginOffline(string id)
{
     if (Request.IsLocal == false) 
         return HttpNotFound();

     ApplicationUser user = UserManager.FindById(id);

     if (user != null)
     {
            await SignInManager.SignInAsync(user, true, true);
     }

     List<ApplicationUser> model = UserManager.Users.ToList();
     return View(model);
}
#endif

As you can see the request would need to be local with the project open in DEBUG mode.

@model System.Collections.Generic.List<ApplicationUser>

<h2>Super Secret Login Page</h2>

<h3> Currently Logged in as @User.Identity.Name</h3>   

@using (Html.BeginForm("LoginOffline", "Account", new {ViewBag.ReturnUrl}))
{
  foreach (var user in Model)
  {
     <div class="row form-group col-lg-offset-1">
     <button type="submit" class="btn btn-primary pull-left" id="@user.Id" name="id" value="@user.Id" title="Login as @user.FirstName @user.LastName">Sign in as @user.UserName</button>
     <span>
         @foreach (var role in user.Roles)
         {
         @role 

             @Html.Raw(", ");
         }
     </span>
     </div>
     }
}

Question

Why is the code sample I have working on the 2nd attempt but not the first, and how can I correct that?

Update

added RedirectToAction

        [AllowAnonymous]
    [HttpPost]
    public async Task<ActionResult> LoginOffline(string id)
    {
        if (Request.IsLocal == false) return HttpNotFound();
        ApplicationUser user = UserManager.FindById(id);
        if (user != null)
        {
            await SignInManager.SignInAsync(user, true, true);
        }
        return RedirectToAction("LoginOffline");
    }

This Code is now working but I still don't Understand why the Original method failed?


Solution

  • Instead of your POST method return View(model); - could you try:

    return RedirectToAction("LoginOffline");