What's new

How can I intercept a user in the proccess of logging in and redirect her to another view and prevent successful login?

Fever

Active member
Staff member
My ApplicationUsers are members of Groups. A Group can be closed (if the group admin has not paid the bill or something). In such cases I want to prevent any of the Group members from logging in, and instead redirect them to an unauthorized view with information about why the Group is closed.

I tried modifying Login.cshtml.cs, but I was unable to get the user's Id:

public async Task<IActionResult> OnPostAsync(string returnUrl = null)
{
returnUrl = returnUrl ?? Url.Content("~/");

if (ModelState.IsValid)
{
// This doesn't count login failures towards account lockout
// To enable password failures to trigger account lockout, set lockoutOnFailure: true
var result = await _signInManager
.PasswordSignInAsync(Input.Email, Input.Password, Input.RememberMe, lockoutOnFailure: true);
if (result.Succeeded)
{

// ADDED CHECK:
var userId = User
.FindFirstValue(ClaimTypes.NameIdentifier); // <-- This returns NULL
if (Guid.TryParse(userId, out Guid gId))
{
Group group = await db.UsersInGroups
.Include(g => g.Group)
.Where(u => u.UserId == gId)
.Select(g => g.Group)
.FirstOrDefaultAsync();
if (group.IsClosed)
{
GroupViewModel vm = auto.Map<GroupViewModel>(group);
return RedirectToAction("Closed", "Groups", vm);
}

}
// END ADDED CHECK

_logger.LogInformation("User logged in.");
return LocalRedirect(returnUrl);
}
if (result.RequiresTwoFactor)
{
return RedirectToPage("./LoginWith2fa", new { ReturnUrl = returnUrl, RememberMe = Input.RememberMe });
}
if (result.IsLockedOut)
{
_logger.LogWarning("User account locked out.");
return RedirectToPage("./Lockout");
}
else
{
ModelState.AddModelError(string.Empty, "Ugyldig innloggingsforsøk.");
return Page();
}
}

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

Continue reading...
 
Top