Security » Authorization » 基于视图的授权

  • View Based Authorization 基于视图的授权

    44 of 46 people found this helpful

    Often a developer will want to show, hide or otherwise modify a UI based on the current user identity. You can access the authorization service within MVC views via dependency injection. To inject the authorization service into a Razor view use the @inject directive, for example @inject IAuthorizationService AuthorizationService. If you want the authorization service in every view then place the @inject directive into the _ViewImports.cshtml file in the Views directory. For more information on dependency injection into views see Dependency injection into views.

  • 开发者经常需要根据当前用户的身份来确定是否展示、隐藏或者是否修改一个页面。你可以通过依赖注入在MVC的视图中使用授权服务。要将授权服务注入Razor视图就要使用@inject 命令,例如@inject IAuthorizationService AuthorizationService。 如果想在左右视图中使用授权服务,就把@inject 命令放置于Views目录内的_ViewImports.cshtml文件中。 更多的依赖注入到视图的信息,请参看Dependency injection into views
  • Once you have injected the authorization service you use it by calling the AuthorizeAsync method in exactly the same way as you would check during resource based authorization.

  • 一旦将授权服务注入后,就可通过调用AuthorizeAsync 方法来使用了,就和resource based authorization(基于资源的授权)中进行的检查一模一样。

    @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;

  • 在某些情况下,资源就是你的视图模型,可通过与resource based authorization(基于资源的授权)中一样的方法来调用AuthorizeAsync

    @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>
    }

     

  • Here you can see the model is passed as the resource authorization should take into consideration.

  • 在这里,您可以看到该模型被作为资源授权而传递了。

    Warning 注意

    Do not rely on showing or hiding parts of your UI as your only authorization method. Hiding a UI element does not mean a user cannot access it. You must also authorize the user within your controller code.

    不要依赖于显示或隐藏你的用户界面的部分作为你唯一的授权方法。隐藏一个用户界面元素并不意味着用户无法访问它。您还必须授权您的控制器代码中的用户。

     

    原文链接

posted @ 2016-10-25 10:32  jqdy  阅读(333)  评论(0编辑  收藏  举报