微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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.jb51.cc/netcore/246848.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐