2015-11-25 29 views
3

我一直在尋找這個問題的解決方案很長一段時間,但不幸的是還沒有找到任何漂亮和優雅的方式來處理它。MVC 6區域和多個登錄頁面重定向

下面是詳細信息:

  1. 我的MVC 6應用程序的使用領域。每個區域具有基於標準的出存儲在SQL Server中使用用戶帳戶的盒子Web應用程序模板的

  2. 認證的控制器,視圖等單獨的目錄

  3. 我想實現的是:

    • 當用戶輸入/ AREAA /受限/頁那麼他將被重定向到/ AREAA /帳號/登錄
    • 當用戶輸入/ AreaB /受限/頁那麼他將被重定向到/ AreaB /帳號/登錄等。 ..
  4. 即使我可以改變斯塔納德登錄頁面,從「/帳號/登錄」重定向到不同的是這樣的:

    services.Configure<IdentityOptions>(options=> { 
        options.Cookies.ApplicationCookie.LoginPath = 
         new Microsoft.AspNet.Http.PathString("/HardcodedAreaName/Account/Login"); 
    }); 
    

我不能夠重定向到不同的動作/登錄每個區域的頁面。

此前MVC 6我能夠使用AuthorizeAttribute與URL參數:

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

     // redirect to login page with the original url as parameter. 
     protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) 
     { 
      filterContext.Result = new RedirectResult(Url + "?returnUrl=" + filterContext.HttpContext.Request.Url.PathAndQuery); 
     } 

    } 

,然後通過裝飾每個控制器經過區相關網址:

[CustomAuthorization(Url = "/Admin/Account/Login"] 
public class AdminAreaController : Controller 
{ ... 

但它不工作了:(

+0

你有沒有結束得到這個工作?由於'services'不可用,您是如何將這些更改放在'Configure'方法中的? –

回答

2

請嘗試以下,看看它是否有效(我做過這個,它工作正常,但不知道如果我已經涵蓋所有情況):

,你註冊,你CookieAuthentication中間件的地方,你可以這樣做

app.UseCookieAuthentication(o => 
{ 
    o.LoginPath = "/area1/login1"; 
    o.AuthenticationScheme = "scheme1"; 
    //TODO: set other interesting properties if you want to 
}); 

app.UseCookieAuthentication(o => 
{ 
    o.LoginPath = "/area2/login2"; 
    o.AuthenticationScheme = "scheme2"; 
    //TODO: set other interesting properties if you want to 
}); 

在您控制器/動作,指定認證scheme..example:

[Authorize(ActiveAuthenticationSchemes = "scheme1")] 
public IActionResult Test1() 
{ 
    return Content("Test1"); 
} 

[Authorize(ActiveAuthenticationSchemes = "scheme2")] 
public IActionResult Test2() 
{ 
    return Content("Test2"); 
} 
+0

嗨Kiran。感謝你的付出。你提出的解決方案几乎沒有問題,只有一件事... 當試圖按照你的建議配置cookie認證時,只保存最後一個選項。 因此,如果我這樣做: app.UseCookieAuthentication(o => {o.LoginPath =「/ area1/login1」; o.AuthenticationScheme =「scheme1」;}); {o.LoginPath =「/ area2/login2」; o.AuthenticationScheme =「scheme2」;}); scheme1/loginpath 1被忽略,應用程序只能看到scheme2和登錄路徑2。 您能準確顯示您是如何在Startup.cs文件中應用這兩個選項的? – Konrad

+0

嗯......我已經分享了上面的代碼來設置上面的選項......你可以分享你的Startup.cs文件的外觀嗎? –

+0

Startup.cs 公共無效ConfigureServices(IServiceCollection服務) { ... // 「前」 區域 - 此選項將被忽略 services.Configure (O => { o.Cookies.ApplicationCookie .LoginPath =「/ Front/Account/Login」; o.Cookies.ApplicationCookie.AuthenticationScheme =「FrontAuthScheme」; }); // 「管理」 區 - 這個選項工作正常,但將覆蓋前一個 services.Configure (O => { o.Cookies.ApplicationCookie.LoginPath = 「/管理員/帳戶/登錄」; o.Cookies.ApplicationCookie.AuthenticationScheme =「AdminAuthScheme」; }); } – Konrad