2014-04-29 105 views
8

我在我的ASP.Net MVC 5/WebApi 2項目中使用OWIN的外部身份驗證提供程序,我遇到了一個奇怪的問題。第一次外部登錄嘗試重定向回登錄操作,第二次工作

登錄工作流程與SO完全相同。用戶點擊登錄頁面,挑選供應商,並會記錄我的問題是,在運營商的第一次點擊重定向到同一個登錄頁面:

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

這將使意義,如果將缺少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> 
} 

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

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

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

回答

8

原來的問題是,我的項目最初開始了作爲有這在web.config中引起問題的MVC 4應用程序:

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

我認爲無論OWIN並且表單身份驗證同時處於活動狀態。

+0

這真的解決了我的問題!謝謝 –

0

我有更新ASPNet.Web.Pages.Web.Data 3.1.1 nuget到任何更高版本時發生的相同問題。與3.1.1它是工作!我找到了解決方案here

0

由於表單身份驗證添加我被重定向到登錄頁面。因此,除去該代碼有助於

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

,但我不得不加入這一行以及

<system.webServer> 
    <validation validateIntegratedModeConfiguration="false" /> 
    <modules> 
     <remove name="FormsAuthentication" /> <-- added this line to remove it completely --> 
    </modules> 
</system.webServer> 

希望這可以幫助別人。

相關問題