2017-02-17 90 views
0

我實現了AspNetCore.Authorization並用[Authorize]修飾了控制器類。如果我從瀏覽器調用控制器,這將起作用。然而,視圖組件可以訪問數據:ASP.NET核心:調用視圖組件不尊重授權屬性

查看:

@foreach (Category category in Model) { 
    <a class="btn btn-block 
     asp-action="Index" 
    asp-controller="Note" 
    [email protected] 
    asp-route-page="1"> 
    @category.Name 
</a> 

這導致視圖組件從@ category.Name實際上不是由瀏覽器的地址欄訪問充滿了數據。

ViewComponent:

[Authorize] 
public class NavigationMenuViewComponent : ViewComponent 
{ 
    private INoteRepository _Repository; 
    public NavigationMenuViewComponent(INoteRepository repository) 
    { 
     _Repository = repository; 
    } 
    public IViewComponentResult Invoke() 
    { 
     ViewBag.SelectedCategory = RouteData?.Values["category"]; 
     return View(_Repository.Categories 
      .OrderBy(x => x.Name)); 
    } 
} 

其實我想,Authorize屬性將拒絕來自如果沒有實際登錄的視圖組件調用我要如何才能到達這樣的行爲?

回答

0

ViewComponents不參與控制器生命週期,這意味着您不能在視圖組件中使用過濾器。所以,Authorize過濾器不會被執行。

視圖組件必須使用ViewComponent類公開的用戶屬性(獲取當前用戶的System.Security.Principal.IPrincipal。)來根據User屬性的內容做出決定或更改輸出。 根據應用程序使用的身份驗證類型,您需要驗證用戶的憑據。

+0

謝謝!這讓我走向了正確的方向!我用'IHttpContextAccessor context'去到HttpContext並分配'_User = context.HttpContext.User',這樣我就可以檢查'_User.Identity.IsAuthenticated == true'。 – pisker