[英]Asp.net Identity 2.0 - redirect externally authenticated user based on role at login
I'm trying to redirect users upon login to different pages, depending on their role. 我试图将用户登录时重定向到不同的页面,具体取决于他们的角色。
Users with a local Identity account are redirected properly in the Login method, by using User.IsInRole("RoleName")
. 通过使用
User.IsInRole("RoleName")
在Login方法中正确重定向具有本地Identity帐户的用户。
However, when I try to conditionally redirect users who are using external validation, it fails to find the role, because the User is not set until after the redirect: 但是,当我尝试有条件地重定向使用外部验证的用户时,它找不到该角色,因为直到重定向之后才设置用户:
public async Task<ActionResult> ExternalLoginCallback(string returnUrl)
{
var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
if (loginInfo == null)
{
return RedirectToAction("Login");
}
// Sign in the user with this external login provider if the user already has a login
var result = await SignInManager.ExternalSignInAsync(loginInfo, isPersistent: false);
if(User.IsInRole("Administrator"))
//always evaluates to false because User is null
{
returnUrl = "~/admin";
} else
{
returnUrl = "~/dashboard";
}
switch (result)
{
case SignInStatus.Success:
return RedirectToLocal(returnUrl);
case SignInStatus.LockedOut:
return View("Lockout");
case SignInStatus.RequiresVerification:
return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = false });
case SignInStatus.Failure:
default:
// If the user does not have an account, then prompt the user to create an account
ViewBag.ReturnUrl = returnUrl;
ViewBag.LoginProvider = loginInfo.Login.LoginProvider;
return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { Email = loginInfo.Email });
}
}
It seems the User isn't completely logged in until after the RedirectToLocal()
call triggers. 直到
RedirectToLocal()
调用触发后,用户似乎才能完全登录。
How can I check the external login user's roles before redirecting? 重定向之前,如何检查外部登录用户的角色?
You are right, at least one new call is needed to apply user authentication. 没错,至少需要一个新呼叫才能应用用户身份验证。 But if you don't want to redirect you could write something like this:
但是,如果您不想重定向,则可以编写如下内容:
public async Task<ActionResult> ExternalLoginCallback(string returnUrl)
{
var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
if (loginInfo == null)
{
return RedirectToAction("Login");
}
var result = await SignInManager.ExternalSignInAsync(loginInfo, isPersistent: false);
if(result==SignInStatus.Success)
{
var user=UserManager.Find(loginInfo.Login);
returnUrl =UserManager.IsInRole(user.Id, "Administrator")
? "~/admin"
: "~/dashboard";
}
// rest of code
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.