Skip to content

ARCHIVED

!注意“归档”

This chapter has not been updated for the current version of Orchard, and has been ARCHIVED.

Custom permissions are implemented in a permissions.cs file.

自定义权限在permissions.cs文件中实现。

In this file we'll implement the IPermissionProvider interface.

在这个文件中,我们将实现 IPermissionProvider 接口。

The definition is a 3 step process, define the permission, return a list of Permissions used in the Module, and the last step is to map the permissions to the build in roles in Orchard.

该定义是一个3步骤过程,定义权限,返回模块中使用的权限列表,最后一步是将权限映射到Orchard中的角色构建。

Creating a Custom Permissions

创建自定义权限

using System.Collections.Generic;

using Orchard.Environment.Extensions.Models;

using Orchard.Security.Permissions;

namespace Orchard.Comments {

public class Permissions : IPermissionProvider {

    public static readonly Permission AddComment = new Permission { Description = "Add comment", Name = "AddComment" };

    public static readonly Permission ManageComments = new Permission { Description = "Manage comments", Name = "ManageComments" };

    public virtual Feature Feature { get; set; }

    public IEnumerable<Permission> GetPermissions() {

        return new[] {

            AddComment,

            ManageComments,

        };

    }

    public IEnumerable<PermissionStereotype> GetDefaultStereotypes() {

        return new[] {

            new PermissionStereotype {

                Name = "Administrator",

                Permissions = new[] {ManageComments, AddComment}

            },

            new PermissionStereotype {

                Name = "Anonymous",

                Permissions = new[] {AddComment}

            },

            new PermissionStereotype {

                Name = "Authenticated",

                Permissions = new[] {AddComment}

            },

            new PermissionStereotype {

                Name = "Editor",

                Permissions = new[] {AddComment}

            },

            new PermissionStereotype {

                Name = "Moderator",

                Permissions = new[] {ManageComments, AddComment}

            },

            new PermissionStereotype {

                Name = "Author",

                Permissions = new[] {AddComment}

            },

            new PermissionStereotype {

                Name = "Contributor",

                Permissions = new[] {AddComment}

            },

        };

    }

}

}

Using Custom Permissions from Code

使用代码中的自定义权限

From our controller (or any other location) we can call the Services.Authorizer.Authorize to check if the current user has the correct Permission. In this example, even the "anonymous" role has the permission to add comments(check the code above).

从我们的控制器(或任何其他位置),我们可以调用 Services.Authorizer.Authorize 来检查当前用户是否具有正确的权限。在此示例中,即使“匿名”角色也有权添加注释(请检查上面的代码)。

if (!Services.Authorizer.Authorize(Permissions.AddComment, T("Couldn't add comment")))

    return new HttpUnauthorizedResult();