如何在wcf中结合自定义用户名验证实现授权

如何在wcf中结合自定义用户名验证实现授权,wcf,validation,authorization,Wcf,Validation,Authorization,我在WCF服务中有自定义用户名/密码验证。我按照上的步骤创建此身份验证 我想根据已经验证的凭据开发某种授权,但不知道在哪里可以找到此类信息。我在谷歌上搜索了很多,找到了很多方法来规范授权,但找不到一种基于自定义用户名验证的授权方法 我是wcf的新手,被各种各样的方法弄得不知所措。 有人能给我提供一些链接,让我可以找到关于这个特定主题的信息吗?我发现这篇文章是对WCF为支持授权而提供的所有东西的一个很好的总结。本文从最简单的实现开始,然后讨论复杂性中的每一个增量步骤,一直到完全基于声明的授权 根据

我在WCF服务中有自定义用户名/密码验证。我按照上的步骤创建此身份验证

我想根据已经验证的凭据开发某种授权,但不知道在哪里可以找到此类信息。我在谷歌上搜索了很多,找到了很多方法来规范授权,但找不到一种基于自定义用户名验证的授权方法

我是wcf的新手,被各种各样的方法弄得不知所措。 有人能给我提供一些链接,让我可以找到关于这个特定主题的信息吗?

我发现这篇文章是对WCF为支持授权而提供的所有东西的一个很好的总结。本文从最简单的实现开始,然后讨论复杂性中的每一个增量步骤,一直到完全基于声明的授权

根据您提供的关于您的具体情况的信息,我建议您创建IPrincipal的自定义实现,如我链接的文章的图3所示。我在这里也包含了文章中的代码示例

class CustomPrincipal : IPrincipal
{
    IIdentity _identity;
    string[] _roles;
    Cache _cache = HttpRuntime.Cache;

    public CustomPrincipal(IIdentity identity)
    {
        _identity = identity;
    }

    // helper method for easy access (without casting)
    public static CustomPrincipal Current
    {
        get
        {
            return Thread.CurrentPrincipal as CustomPrincipal;
        }
    }

    public IIdentity Identity
    {
        get { return _identity; }
    }

    // return all roles (custom property)
    public string[] Roles
    {
        get
        {
            EnsureRoles();
            return _roles;
        }
    }

    // IPrincipal role check
    public bool IsInRole(string role)
    {
        EnsureRoles();

        return _roles.Contains(role);
    }

    // cache roles for subsequent requests
    protected virtual void EnsureRoles()
    {
        // caching logic omitted – see the sample download
    }
}
在原始帖子中引用的自定义用户名和密码验证器中,您只需填充新IPrincipal的一个实例并将其附加到静态值Thread.CurrentPrincipal。这将允许您使用PrincipalPermission属性简单地修饰您希望控制访问的任何方法,如下所示。这个代码示例也是我链接的文章中的图1

class Service : IService {
  // only 'users' role member can call this method
  [PrincipalPermission(SecurityAction.Demand, Role = 'users')]
  public string[] GetRoles(string username) {
    // only administrators can retrieve the role information for other users
    if (ServiceSecurityContext.Current.PrimaryIdentity.Name != username) {
      if (Thread.CurrentPrincipal.IsInRole('administrators')) {
        ...
      }
      else {
        // access denied
        throw new SecurityException();
      }
    }
  }
}