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"
[email protected]
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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With