Asp.net Identity 2.0 - 根据登录时的角色重定向外部认证用户

时间:2015-11-13 21:49:18

标签: c# asp.net redirect asp.net-mvc-5 asp.net-identity-2

我尝试在登录到不同页面时重定向用户,具体取决于他们的角色。

使用User.IsInRole("RoleName")在Login方法中正确重定向具有本地身份帐户的用户。

但是,当我尝试有条件地重定向使用外部验证的用户时,它无法找到该角色,因为直到重定向后才设置用户:

        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 });
        }
    }

RedirectToLocal()来电触发后,用户似乎还没有完全登录。

如何在重定向之前检查外部登录用户的角色?

1 个答案:

答案 0 :(得分:2)

您是对的,至少需要一个新的呼叫才能应用用户身份验证。但是如果你不想重定向,你可以写下这样的东西:

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
}