c# - 第一次外部登录尝试重定向回登录操作,第二次成功

标签 c# asp.net-mvc asp.net-mvc-5 owin

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

登录工作流程与此处完全一样。用户点击登录页面,选择一个提供商并登录。我的问题是第一次点击提供商会重定向回同一个登录页面:

http://localhost:57291/Account/Login?ReturnUrl=%2fAccount%2fExternalLogin

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

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

我也尝试过使用不同的浏览器,这个问题在 Chrome、IE11 和 Firefox 上都是一致的。

登录.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>
}

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

挑战结果.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);
    }
}

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

最佳答案

原来问题是我的项目最初是作为一个 MVC 4 应用程序开始的,它在 web.config 中有这个导致问题:

<authentication mode="Forms">
  <forms loginUrl="~/Account/Login" timeout="2880" />
</authentication>

我认为 OWIN 和 Forms 身份验证同时处于事件状态。

关于c# - 第一次外部登录尝试重定向回登录操作,第二次成功,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23359713/

相关文章:

c# - 即使在 javascript 中设置了值之后, <asp.HiddenField> 值在代码隐藏中仍为空

c# - NerdDinner DinnerFormViewModel 错误 CS0030 错误

asp.net-mvc - 使用 bootstrap-datepicker 时如何不显示移动键盘?

javascript - SweetAlert 警报显示部分 View

c# - 使用 C# .NET 通过 Soundcloud API 连接和上传轨道

c# - 如何更改 PictureBox 的图像?

JQuery 标签输入插件 ASP.NET 不工作

c# - ASP.NET WEB API 外部登录

asp.net-mvc - 如何在 Razor 中获取页面原点?

c# - 为什么 ASP.NET Identity 返回 401 而不是重定向到登录页面?