如何将MVC应用程序配置为仅OAuth-login

时间:2015-03-29 10:37:37

标签: oauth asp.net-mvc-5 owin steam

我正在尝试将MVC 5应用程序配置为仅使用Steam登录,即没有用户注册等。我是ASP.NET MVC 5和Owin的新手,所以我有点挣扎了解我的内容基本流程应该是。

我正在使用通过NuGet安装的Owin.Security.Providers.Steam

下面我列出了我的Startup.Auth.cs和AccountController。您会注意到我已经实现了自定义UserManager和SignInManager以及自定义用户存储。这部分工作正常,但当我完成用户登录时,User.Identity.IsAuthenticated仍然是假的。为了解决这个问题,我尝试在我的Startup.Auth.cs中添加cookie身份验证,但是当我这样做时,我的ExternalLoginCallback中出现以下异常:

Line 79:             var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();

[InvalidOperationException: Sequence contains more than one element]
System.Linq.Enumerable.SingleOrDefault(IEnumerable`1 source) +4098162
Microsoft.Owin.Security.<AuthenticateAsync>d__8.MoveNext() +358

这是我的Startup.Auth.cs:

app.CreatePerOwinContext<SteamUserManager>(SteamUserManager.Create);
app.CreatePerOwinContext<SteamSignInManager>(SteamSignInManager.Create);
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
    AuthenticationType = DefaultAuthenticationTypes.ExternalCookie,
    LoginPath = new PathString("/Account/Login")
});
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
app.UseSteamAuthentication("XXXXXXXXXXXXXXXXXXXXX"); // My Steam key

AccountController.cs:

[AllowAnonymous]
public ActionResult Login(string returnUrl)
{
    return ExternalLogin("Steam", returnUrl);
}

[HttpPost]
[AllowAnonymous]
public ActionResult ExternalLogin(string provider, string returnUrl)
{
    return new ChallengeResult(provider, Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl }));
}

[AllowAnonymous]
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);
    switch (result)
    {
        case SignInStatus.Success:
            return RedirectToLocal(returnUrl);
        case SignInStatus.Failure:
        default:
            // If the user does not have an account, then prompt the user to create an account
            return await CreateFirstTimeUser(loginInfo, returnUrl);
        }
    }
}

1 个答案:

答案 0 :(得分:0)

答案很简单。 CookieAuthenticationOptions上的AuthenticationType应该是ApplicationCookie而不是ExternalCookie。

app.UseCookieAuthentication(new CookieAuthenticationOptions
{
    AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
    LoginPath = new PathString("/Account/Login")
});