【问题标题】:custom authorization and authentication in wcf webhttpbindigwcf webhttpbindig 中的自定义授权和身份验证
【发布时间】:2017-08-21 06:04:12
【问题描述】:

如您所见,我使用 webhttpbinding 创建了一个简单的 wcf 服务:

    [OperationContract]
    [WebInvoke(Method = "GET", UriTemplate = "/Data/{data}")]
    string GetData(string data);

和实施:

   public string GetData(string value)
        {

                return string.Format("You entered: {0}", value);

        }

我想创建一个自定义授权和身份验证大约 2 周,但我做不到。我搜索了很多,但我可以找到 wshttpbinding 而不是 webhttpbinding 的身份验证。

我最近描述主要问题的问题:

My authorize custom function in wcf doesn't execute .Should i define it in webconfig?

My CustomAuthorizationPolicy.Evaluate() method never fires

【问题讨论】:

    标签: c# wcf authentication authorization webhttpbinding


    【解决方案1】:

    您可以实现ServiceAuthorizationManager 以通过 webhttpbinding 为您的 WCF 服务提供授权。

    您的代码可能如下所示:

    public class CustomAuthorizationManager : ServiceAuthorizationManager
    {
        protected override bool CheckAccessCore(OperationContext operationContext)
        {
            try
            {
                ServiceSecurityContext securityContext = operationContext.ServiceSecurityContext;
                WindowsIdentity callingIdentity = securityContext.WindowsIdentity;
    
                WindowsPrincipal principal = new WindowsPrincipal(callingIdentity);
                return principal.IsInRole("Administrators");
            }
            catch (Exception)
            {
                return false;
            }
        }
    }
    

    然后在 web.config 文件中注册您的自定义 ServiceAuthorizationManager:

    <serviceBehaviors>
      <behavior name="ServiceBehaviour">
        <serviceMetadata httpsGetEnabled="true"/>
        <serviceAuthorization serviceAuthorizationManagerType="YourNamespace.CustomAuthorizationManager, YourAssemblyName"/>
      </behavior>
    </serviceBehaviors>
    

    【讨论】:

    • 谢谢,但是我如何检查角色。我的意思是如何检查用户角色是否正确执行操作?
    • principal.IsInRole("Administrators");
    • 当我调用服务 IsInRole 时返回 false
    • 我想用我的数据库角色检查操作角色,stackoverflow.com/questions/45794914/…
    猜你喜欢
    • 1970-01-01
    • 2016-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多