Search code examples
c#asp.net-coreasp.net-core-viewcomponent

ASP.NET Core: calling a view component does not respect authorization attribute


I implemented AspNetCore.Authorization and decorated the controller classes with [Authorize]. This works, if I call the Controller from the Browser. View Component can however access the data:

View:

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

This leads to the View Component been filled with data from @category.Name actually not accessible by the browser's address bar.

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

Actually I thought, the Authorize attribute will reject the call from the view component if not actually logged in. How can I get to such behavior?


Solution

  • ViewComponents does not take part in the controller lifecycle, which means you can't use filters in a view component. So, the Authorize filter will not get executed.

    A View Component must use the User property(Gets the System.Security.Principal.IPrincipal for the current user.) that is exposed by the ViewComponent class to make decisions or change output based on the contents of the User property. Depending upon the type of authentication used by the application, you need to verify the credentials of the user.