如何在 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();
      }
    }
  }
}

最新更新