第一次外部登录尝试重定向回登录操作,第二次登录操作

Oli*_*old 8 c# asp.net-mvc owin asp.net-mvc-5

我在我的ASP.Net MVC 5/WebApi 2项目中使用OWIN的外部认证提供程序,我遇到了一个奇怪的问题.

登录工作流程就像在SO上一样.用户点击登录页面,选择提供商并登录.我的问题是首次点击提供商会重定向回相同的登录页面:

http://localhost:57291/Account/Login?ReturnUrl=%2fAccount%2fExternalLogin
Run Code Online (Sandbox Code Playgroud)

如果ExternalLogin操作缺少AllowAnonymous属性,这将是有意义的.

当用户第二次点击时一切正常.

我也尝试过使用不同的浏览器,问题在Chrome,IE11和Firefox中都是一致的.

Login.cshtml:

@using (Html.BeginForm("ExternalLogin", "Account", new { ReturnUrl = ViewBag.ReturnUrl }))
{
    <fieldset>
        <legend>@Strings.ExternalAuthenticationProvidersDescription</legend>
        <p>
            @foreach (var p in Model.ExternalAuthenticationProviders)
            {
                <button type="submit" name="provider" value="@p.AuthenticationType" title="Log in using your @p.Caption account">@p.Caption</button>
            }
        </p>
    </fieldset>
}
Run Code Online (Sandbox Code Playgroud)

AccountController.cs

public class AccountController : Controller
{
  ...

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

ChallengeResult.cs:

public class ChallengeResult : HttpUnauthorizedResult
{
    public ChallengeResult(string provider, string redirectUrl)
    {
        LoginProvider = provider;
        RedirectUrl = redirectUrl;
    }

    public string LoginProvider { get; set; }
    public string RedirectUrl { get; set; }

    public override void ExecuteResult(ControllerContext context)
    {
        context.HttpContext.GetOwinContext().Authentication.Challenge(new AuthenticationProperties
        {
            RedirectUri = RedirectUrl
        }, LoginProvider);
    }
}
Run Code Online (Sandbox Code Playgroud)

FilterConfig.cs

public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new HandleErrorAttribute());

        // make all api controllers secure by default
        filters.Add(new AuthorizeAttribute());
    }
}
Run Code Online (Sandbox Code Playgroud)

Oli*_*old 9

事实证明,我的项目最初是作为一个MVC 4应用程序启动的,它在web.config中导致了这个问题:

<authentication mode="Forms">
  <forms loginUrl="~/Account/Login" timeout="2880" />
</authentication>
Run Code Online (Sandbox Code Playgroud)

我认为OWIN和Forms身份验证同时处于活动状态.