使用外部提供程序的ASP.NET MVC身份验证 - Google / Facebook

时间:2016-02-15 21:30:32

标签: asp.net-mvc authentication oauth-2.0

我在我的asp.net MVC应用程序中使用Microsoft / Google / Facebook身份验证,该应用程序验证用户&将用户重定向到我的网站。这很好。

问题:拥有Microsoft / Google / Facebook帐户的任何人都可以登录我的应用程序。我应该只允许那些在我们的数据库中注册/映射的用户,即如果一个人只购买了许可证,他应该能够使用外部提供商登录。

示例: 1)User1拥有Microsoft / Google帐户& user1是我们数据库中的有效用户。所以我们可以让他看到我们网站上的内容。   2)user2有一个microsoft / Google帐户,但他在我们的数据库中不是有效用户。他无法访问我们的网站。

如何在ASP.NET MVC中实现此目的。我正在使用客户端ID&来自外部提供商的客户密钥。

启动类的示例代码

  app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
    {
    ClientId = "",
    ClientSecret = ""
    });

2 个答案:

答案 0 :(得分:0)

在AccountController.cs中(默认代码,如果你还没有改变它)

 [AllowAnonymous]
    public ActionResult ExternalLoginCallback(string returnUrl)
    {
        AuthenticationResult result = OAuthWebSecurity.VerifyAuthentication(Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl }));
        if (!result.IsSuccessful)
        {
            return RedirectToAction("ExternalLoginFailure");
        }

        if(EmailNotRegistered(result.ExtraData["userid"]))
        {
            FormsAuthentication.SignOut();
            return RedirectToAction("ExternalLoginFailure");
        }

        var bresult = OAuthWebSecurity.Login(result.Provider, result.ProviderUserId, createPersistentCookie: false);
        if (bresult)
        {
            return RedirectToLocal(returnUrl);
        }

       // etc...
    }

您需要编写函数bool EmailNotRegistered(string email)并执行检查本地数据库的逻辑。会员资格API中可能已经有一些东西需要检查,但我现在还不知道。

顺便说一句,每个提供商都不同,因此ExtraData字段可能是“电子邮件”或其他内容 - 使用调试器查找!

答案 1 :(得分:0)

这是我的AccountController

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);
            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 });
            }
        }
相关问题