2015-04-04 225 views
3

我在構建基於OWIN的身份驗證的基於ASP.NET MVC 5的網站。我在管理員面板的應用程序中創建了一個新的Area。我想有一個不同於普通用戶的登錄頁面。ASP.NET MVC 5 OWIN區域身份驗證

例如,當我去http://site/admin/home/index它應該檢查授權並重定向到http://site/admin/account/login,而不是去站點用戶登錄頁面。

我已經嘗試執行自定義Authorize屬性。不過,我不知何故覺得這不是正確的做法。

有人可以建議一個更好或更正確的解決方案嗎?

編輯:自定義屬性實現

public class AuthorizeAreaAttribute : AuthorizeAttribute 
{ 
    public string Url { get; set; } 

    public override void OnAuthorization(AuthorizationContext filterContext) 
    { 
     if (!filterContext.HttpContext.User.Identity.IsAuthenticated) 
     { 
      filterContext.HttpContext.Response.Redirect(Url); 
      filterContext.HttpContext.Response.End(); 
     } 
     base.OnAuthorization(filterContext); 
    } 
} 
+0

爲什麼你認爲這不是一個很好的解決方案來通過自定義的授權屬性? – tire0011 2015-04-04 09:08:49

+0

@ tire0011,當我使用自定義屬性時,碰巧看到一個內部異常被拋出'Headers has already sent!'。 – 2015-04-04 09:18:56

+0

你可以發佈自定義屬性的代碼嗎? – tire0011 2015-04-04 09:33:58

回答

1

Configuration方法App_Start/Startup.Auth.cs文件,您可以更改重定向behavoir。

app.UseCookieAuthentication(new CookieAuthenticationOptions 
{ 
    AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, 
    LoginPath = new PathString("/Account/Login"), 
    Provider = new CookieAuthenticationProvider 
    { 
     // Enables the application to validate the security stamp when the user logs in. 
     // This is a security feature which is used when you change a password or add an external login to your account. 
     OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, User>(
      validateInterval: TimeSpan.FromMinutes(30), 
      regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager) 
     ), 

     // Change redirect 
     OnApplyRedirect = ApplyRedirect 
    } 
}); 

private static void ApplyRedirect(CookieApplyRedirectContext context) 
{ 
    Uri absoluteUri; 
    PathString ContentVersioningUrlSegments = PathString.FromUriComponent("/admin/"); 

    if (Uri.TryCreate(context.RedirectUri, UriKind.Absolute, out absoluteUri)) 
    { 
     PathString remainingPath; 
     var path = PathString.FromUriComponent(absoluteUri); 
     if (path.StartsWithSegments(ContentVersioningUrlSegments, out remainingPath) && remainingPath.HasValue && remainingPath.Value.Length > 1)) 
       context.RedirectUri = "url" + 
        new QueryString(
         context.Options.ReturnUrlParameter, 
         context.Request.Uri.AbsoluteUri); 
    } 

    context.Response.Redirect(context.RedirectUri); 
} 
+0

感謝您的回答。我使用這裏提到的方法解決了問題:http://stackoverflow.com/questions/2472578/is-it-possible-to-use-redirecttoaction-inside-a-custom-authorizeattribute-clas它運作良好 – 2015-04-05 15:21:53

+0

只是想不使用自定義屬性顯示相同的解決方案。 – 2015-04-05 17:40:17