【问题标题】:How to add security to a EF 5.0 Code First WCF DataService如何为 EF 5.0 Code First WCF DataService 添加安全性
【发布时间】:2013-03-13 03:16:38
【问题描述】:

我创建了几个 POCO 然后创建了一个 DbContext (FooDbContext) - 然后我从 DataService calll FooDatService 创建了一个 DataService 类设备。我可以在我的 silverlight 应用程序中访问我的所有数据,如果我启动 Web 浏览器,我可以按预期通过 URL 访问它。现在我只想在成功登录后才允许 DataService。

【问题讨论】:

  • 您是否使用 WCF 或 MVC 作为数据服务的主机?
  • 我猜是 WCF,因为我没有使用 MVC。

标签: c# entity-framework wcf-data-services wcf-security


【解决方案1】:

我在 3 年前写过博客

http://netpl.blogspot.com/2010/04/aspnet-forms-authentication-sharing-for.html

这个想法是重用表单cookie来保护您的调用,以便只允许登录用户调用服务。

【讨论】:

    【解决方案2】:

    您可以向 WCF 服务添加服务授权管理器,以将该服务的所有方法和端点置于访问控制之下,而无需修改服务的任何实现。

    创建并启动您的 WCF 服务:

        Uri[] restUris = new Uri[] { new Uri(baseUri, "Api/v1/") };
        // substitute your service host type here. I'm using WCF OData DataServiceHost
        restAPIServiceHost = new DataServiceHost(typeof(API.RestAPIService), restUris);
    
        var saz = restAPIServiceHost.Description.Behaviors.Find<ServiceAuthorizationBehavior>();
        if (saz == null)
        {
            saz = new ServiceAuthorizationBehavior();
            restAPIServiceHost.Description.Behaviors.Add(saz);
        }
    
        saz.ServiceAuthorizationManager = new MyServiceAuthorizationManager();
    
        restAPIServiceHost.Open();
    

    以上也可以通过 web.config 魔术来完成。

    在您的 MyServiceAuthorizationManager 实现中:

            public class MyServiceAuthorizationManager: System.ServiceModel.ServiceAuthorizationManager
            {
                public override bool CheckAccess(OperationContext operationContext, ref Message message)
                {
                    var reqProp = message.Properties[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty;
                    var authHeader = new AuthorizationHeader(reqProp.Headers[HttpRequestHeader.Authorization]);
    
                    bool authorized = // your code to decide if caller is authorized;
    
                    if (!authorized)
                    {
                        var webContext = new WebOperationContext(operationContext);
                        webContext.OutgoingResponse.StatusCode = HttpStatusCode.Unauthorized;
    
                        // optional: give caller hints where to go to login
                        webContext.OutgoingResponse.Headers.Add( HttpResponseHeader.WwwAuthenticate, String.Format("Bearer realm=\"{0}\"", baseUri.AbsoluteUri));
                    }
    
                    return authorized;
                }
            }
    

    在将请求分派到 WCF 实现方法之前,将为 WCF 服务收到的每个请求调用此 CheckAccess 方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多