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";
}

私がサービスとクライアントに持っているのはそれだけですが、何が欠けていますか? 毎回、デバッグで、等しいことがわかったメソッドをチェックThread.CurrentPrincipalインしますが、クライアントがメソッドを呼び出すときでも. PS:コンソール アプリケーションを使用してテストを行っていますが、違いはありますか? ありがとうLoginThread.CurrentPrincipal.Identity.IsAuthenticatedtrueGetData()Access Denied

4

2 に答える 2

2

これは 、解決策につながる可能性のある非常に優れた記事です。

一般的な考え方は、プリンシパルに対して 2 つのオブジェクトがあるということです。 HttpContext.Current.UserThread.CurrentPrincipalThread.CurrentPrincipalその時点での設定HttpContext.Current.Userはすでにインスタンス化されており、その役割はデフォルトのままです。
次のようなことを試してみてください。

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

への呼び出しGetData()が拒否される理由は、WCF が で設定されたフォーム認証 Cookie について何も知らないため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 に答える