asp.net – 在.NET Core 1.0 MVC中的视图中使用授权策略的任何方式?

前端之家收集整理的这篇文章主要介绍了asp.net – 在.NET Core 1.0 MVC中的视图中使用授权策略的任何方式?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我知道在控制器中,你可以写[Authorize(“policyName”)]没有问题,但有什么办法在视图中使用策略?我宁愿不要每次使用User.IsInRole(…)来授权一些 HTML.

编辑:

这是一些代码

Startup.cs – 政策声明

services.AddAuthorization(options =>
    {
        options.AddPolicy("testPolicy",policy =>
        {
            policy.RequireAuthenticatedUser()
                  .RequireRole("RoleOne","RoleTwo","RoleThree")
                  .RequireClaim(ClaimTypes.Email);
        });
    });

管理控制器

[Authorize("testPolicy")]
public class AdminController : Controller
{
    public IActionResult Index()
    {
        return View();
    }
}

导航栏HTML

<div class="navbar navbar-inverse navbar-fixed-top">
            <div class="container">
                <div class="navbar-collapse collapse">
                    <ul class="nav navbar-nav">
                        <li><a asp-controller="Home" asp-action="Index">Home</a></li> 

                        <!-- I want to implement my policy here. -->
                        @if (User.IsInRole("..."))
                        {
                            <li><a asp-controller="Admin" asp-action="Index">Admin</a></li>
                        }
                    </ul>
                    @await Html.PartialAsync("_LoginPartial")
                </div>
            </div>

解决方法

我发现这个可能有帮助的链接https://docs.asp.net/en/latest/security/authorization/views.html

页面的示例:

@if (await AuthorizationService.AuthorizeAsync(User,"PolicyName"))
{
    <p>This paragraph is displayed because you fulfilled PolicyName.</p>
}

In some cases the resource will be your view model,and you can call AuthorizeAsync in exactly the same way as you would check during resource based authorization;

@if (await AuthorizationService.AuthorizeAsync(User,Model,Operations.Edit))
{
    <p><a class="btn btn-default" role="button"
        href="@Url.Action("Edit","Document",new {id= Model.Id})">Edit</a></p>
}
原文链接:https://www.f2er.com/netcore/246848.html

猜你在找的.NET Core相关文章