我在我的 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/