1

我有这个 WCF 服务,我正在尝试在其中应用身份验证和授权机制。
这是我第一次这样做,我所拥有的是该serviceModel服务的 web.config 标记:

  <system.serviceModel>
<services>
  <service name="RoleBasedServices.SecureServiceExternal" behaviorConfiguration="externalServiceBehavior">
    <endpoint contract="AuthService.IService1" binding="wsHttpBinding" bindingConfiguration="wsHttpUsername" />
  </service>
</services>
<bindings>
  <wsHttpBinding>
    <binding name="wsHttpUsername">
      <security mode="Message">
        <message clientCredentialType="UserName" negotiateServiceCredential="false" establishSecurityContext="false" />
      </security>
    </binding>
  </wsHttpBinding>
</bindings>
<behaviors>
  <serviceBehaviors>
    <behavior>
       <!--To avoid disclosing metadata information, set the values below to false before deployment--> 
      <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
       <!--To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information--> 
      <serviceDebug includeExceptionDetailInFaults="false"/>
    </behavior>
    <behavior name="externalServiceBehavior">
      <serviceAuthorization principalPermissionMode="UseAspNetRoles" />
      <serviceCredentials>
        <userNameAuthentication userNamePasswordValidationMode="MembershipProvider" />
        <serviceCertificate findValue="RPKey" x509FindType="FindBySubjectName" storeLocation="LocalMachine" storeName="My"/>
      </serviceCredentials>
    </behavior>
  </serviceBehaviors>
</behaviors>
<protocolMapping>
    <add binding="basicHttpsBinding" scheme="https" />
</protocolMapping>    
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />

我想做的很简单,我不知道我是否需要我正在尝试的所有这些标签。我想要做的是从客户端为服务添加引用并首先调用MyLogin

    AuthService.Service1Client s = new AuthService.Service1Client();
    s.Login();

然后调用另一个受限方法并让它成为GetData

s.GetData()  

Login方法的服务端,仅出于测试目的,我这样做:

public void Login()
{
    Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity("Bob"), new[] { "Admin" });
    FormsAuthentication.SetAuthCookie("BobUserName", false);
}

受限制的方法将是:

[PrincipalPermission(SecurityAction.Demand, Role = "Admin")]
public void GetData()
{
    return "Hello";
}

我在服务和客户方面所拥有的一切,我缺少什么?每次,在调试中,我都会检查我发现equalsThread.CurrentPrincipal的方法,但即使当客户端调用该方法时它也是. PS:我正在使用控制台应用程序进行测试,这有什么不同吗? 谢谢LoginThread.CurrentPrincipal.Identity.IsAuthenticatedtrueGetData()Access Denied

4

2 回答 2

2

这是一篇 非常好的文章,可能会导致解决方案。

一般的想法是您有 2 个对象作为委托人。 HttpContext.Current.UserThread.CurrentPrincipal。您正在设置的Thread.CurrentPrincipal时间HttpContext.Current.User已经实例化,并且它的角色保留为默认值。
您可能想尝试以下方法:

HttpContext.Current.User = new GenericPrincipal(new GenericIdentity("Bob"), new[] { "Admin" });
于 2015-02-08T15:00:35.420 回答
0

拒绝调用的原因GetData()是因为 WCF 不知道在Login().

您是使用控制台应用程序并没有什么区别。您可以尝试以下方法。

将 cookie 设置在Login()

var cookie = FormsAuthentication.GetAuthCookie(username, true);
var ticket = FormsAuthentication.Decrypt(cookie.Value);

HttpContext.Current.User = new GenericPrincipal(new FormsIdentity(ticket), null);
FormsAuthentication.SetAuthCookie(HttpContext.Current.User.Identity.Name, true);

然后在您的控制台应用程序中:

public static void TestLoginAndGetData()
{
    var sharedCookie = string.Empty;

    using (var client = new YourClient())
    using (new OperationContextScope(client.InnerChannel))
    {
        client.Login("username", "password");

        // get the cookie from the response
        HttpResponseMessageProperty response = (HttpResponseMessageProperty)
            OperationContext.Current.IncomingMessageProperties[
            HttpResponseMessageProperty.Name];
        sharedCookie = response.Headers["Set-Cookie"];

        // add it to the request
        HttpRequestMessageProperty request = new HttpRequestMessageProperty();
        request.Headers["Cookie"] = sharedCookie;
        OperationContext.Current.OutgoingMessageProperties[
            HttpRequestMessageProperty.Name] = request;

        var result = client.GetData();

        Console.WriteLine(result);
    }
}

您也可以考虑将返回类型更改GetData()string

于 2015-02-08T15:52:12.010 回答