WCF基于消息的安全性 [英] WCF Message Based Security

查看:73
本文介绍了WCF基于消息的安全性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,先生,
我遇到有关WCF中基于消息的安全性的问题.在我的代码中,我使用了基于声明的身份模型,X509证书和UserNamePasswordClient凭据类型.下面我将向您展示我的服务和客户端代码.
服务端配置:

Hello Sir,
I am facing a problem regarding Message Based security in WCF.In my code I have used Claim Based Identity Model,X509 certificates and UserNamePasswordClient Credential Type. Below I am showing you my code both of service and client side.
Service Side Configuration:

<system.serviceModel>
   <client>
     <remove contract="IMetadataExchange" name="sb" />
   </client>
   <bindings>
     <wsHttpBinding>
       <binding name="Binding1">
         <security mode="Message">

           <message clientCredentialType="UserName" negotiateServiceCredential="true" />
         </security>
       </binding>
     </wsHttpBinding>
   </bindings>
   <services>
     <service behaviorConfiguration="WCFServiceWebRole1.Service1Behavior"

       name="WCFServiceWebRole1.Service1">
       <endpoint address="" binding="wsHttpBinding" bindingConfiguration="Binding1"

         contract="WCFServiceWebRole1.IService1" />
       <endpoint address="mex" binding="mexHttpBinding" bindingConfiguration=""

         contract="IMetadataExchange" />
     </service>
   </services>
   <behaviors>
     <serviceBehaviors>
       <behavior name="WCFServiceWebRole1.Service1Behavior">
         <serviceMetadata httpGetEnabled="true" />
         <serviceDebug includeExceptionDetailInFaults="false" />
         <serviceCredentials>
           <serviceCertificate findValue="SignedByCANew" storeLocation="LocalMachine"

             storeName="My" x509FindType="FindBySubjectName" />
           <userNameAuthentication userNamePasswordValidationMode="Custom"

             customUserNamePasswordValidatorType="WCFServiceWebRole1.MyUserNamePasswordValidator, App_Code" />
         </serviceCredentials>
         <serviceAuthorization serviceAuthorizationManagerType="">
           <authorizationPolicies>
             <add policyType="WCFServiceWebRole1.MyAuthorizationPolicy, WCFServiceWebRole1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
           </authorizationPolicies>
         </serviceAuthorization>
       </behavior>
     </serviceBehaviors>
   </behaviors>
 </system.serviceModel>


使用IAuthorizationPolicy进行基于声明的转换:


Claim Based Transformation Using IAuthorizationPolicy:

public class MyAuthorizationPolicy : IAuthorizationPolicy
   {
       string id = "Custom_" + Guid.NewGuid().ToString();

       public bool Evaluate(EvaluationContext evaluationContext, ref object state)
       {
           bool isFound = false;

           foreach (ClaimSet cs in evaluationContext.ClaimSets)
           {
               foreach (Claim claim in cs.FindClaims(ClaimTypes.Name, Rights.PossessProperty))
               {
                   if (claim.Resource.ToString().Equals("shiv123", StringComparison.InvariantCultureIgnoreCase))
                   {
                       isFound = true;
                       break;
                   }

               }
           }
           if (isFound)
           {
               evaluationContext.AddClaimSet(this, new DefaultClaimSet(this.Issuer, new Claim[] { new Claim("http://myClaimType", "I am Shiv Prasad", Rights.PossessProperty) }));
           }
           return true;
       }

       public ClaimSet Issuer
       {
           get { return ClaimSet.System; }
       }

       public string Id
       {
           get { return id; }
       }
   }


UserNamePasswordValidatorMode:


UserNamePasswordValidatorMode:

public class MyUserNamePasswordValidator : UserNamePasswordValidator
    {
        public override void Validate(string userName, string password)
        {
            if (userName != "shiv123" || password != "pass123")
                throw new SecurityTokenValidationException("The User Could Not Be Authenticated");
        }
    }


提供的接口和服务:
界面:


Interface And Services Provided:
Interface:

[ServiceContract]
   public interface IService1
   {
       [OperationContract]
       string GetData(int value);
       [OperationContract]
       CompositeType GetDataUsingDataContract(CompositeType composite);
       [OperationContract]
       List<string> Echo();
       // TODO: Add your service operations here
   }


服务:


Service:

public class Service1 : IService1
   {
       public string GetData(int value)
       {
           return string.Format("You entered: {0}", value);
       }
       public CompositeType GetDataUsingDataContract(CompositeType composite)
       {
           if (composite == null)
           {
               throw new ArgumentNullException("composite");
           }
           if (composite.BoolValue)
           {
               composite.StringValue += "Suffix";
           }
           return composite;
       }
       public List<string> Echo()
       {
           List<string> claims = new List<string>();
           foreach(ClaimSet set in OperationContext.Current.ServiceSecurityContext.AuthorizationContext.ClaimSets)
           {
               foreach (Claim claim in set)
               {
                   claims.Add(string.Format("{0} - {1} - {2}",claim.ClaimType,claim.Resource.ToString(),claim.Right));
               }
           }
           return claims;
       }
   }


客户端配置:


Client Side Configuration:

<system.serviceModel>
      <behaviors>
          <endpointBehaviors>
              <behavior name="ServiceEndpointBehavior">
                  <clientCredentials>
                      <serviceCertificate>
                          <authentication revocationMode="NoCheck"/>
                      </serviceCertificate>
                  </clientCredentials>
              </behavior>
          </endpointBehaviors>
      </behaviors>
      <bindings>
          <wsHttpBinding>
              <binding name="WSHttpBinding_IService1" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" bypassProxyOnLocal="false" transactionFlow="false" hostNameComparisonMode="StrongWildcard" maxBufferPoolSize="524288" maxReceivedMessageSize="65536" messageEncoding="Text" textEncoding="utf-8" useDefaultWebProxy="true" allowCookies="false">
                  <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384"/>
                  <reliableSession ordered="true" inactivityTimeout="00:10:00" enabled="false"/>
                  <security mode="Message">
                      <transport clientCredentialType="Windows" proxyCredentialType="None" realm=""/>
                      <message clientCredentialType="UserName" negotiateServiceCredential="true" algorithmSuite="Default"/>
                  </security>
              </binding>
          </wsHttpBinding>
      </bindings>
      <client>
 <endpoint address="http://localhost:1853/Service1.svc" behaviorConfiguration="ServiceEndpointBehavior"

  binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IService1"

  contract="ServiceReference1.IService1" name="WSHttpBinding_IService1">
  <identity>
   <dns value="SignedByCANew" />
   <certificate encodedValue="" />
  </identity>
 </endpoint>
</client>
  </system.serviceModel>



提供身份验证凭据的客户端:-



Client Providing Credentials For Authentication:-

ServiceReference1.Service1Client client = new ServiceReference1.Service1Client();

       client.ClientCredentials.UserName.UserName = "shiv123";
       client.ClientCredentials.UserName.Password = "pass123";

       try
       {
           string[] claims = client.Echo();

           foreach (string claim in claims)
           {
               Response.Write(claim);
           }
       }
       catch (TimeoutException exception)
       {
           Response.Write(exception.GetType());
           client.Abort();
       }
       catch (CommunicationException exception)
       {
           Response.Write(exception.GetType());
           client.Abort();
       }



到这里为止一切正常.但是我的需要是,当客户端要访问服务时,应该对他进行身份验证,但是对于后续的服务调用,如果已经对第一个服务调用进行了身份验证,则不应一次又一次地对客户端进行身份验证.请为我提供解决方案.请世界超级头脑的人帮帮我.寻求您的答复.



Till here everything is working fine. But my need is that when a client wants to access a service he should be authenticated but for subsequent service calls the client should not be authenticated again and again if he is already authenticated for the first service call. Please provide me the solution.Please Super Mind human beings of the world help me out.Seeking your response.

推荐答案

如果再次要求身份验证,再次是由于WCF服务所在的服务器上的iis设置.IIS设置和WCF端点设置的不匹配组合可能会导致再次要求身份验证.只是一个猜测:)


默认情况下,IIS使用匿名身份验证.您必须为要启用其他身份验证方法的任何网站,Web应用程序或Web服务禁用匿名身份验证.
If it''s asking for an authentication again & again.It could be because of the iis settings done on server where your WCF service resides.Unmatched combinations of IIS settings and WCF endpoint settings may result in asking for authentication again & again.Just a guess :)


By default, IIS uses Anonymous authentication. You must disable Anonymous authentication for any Web site, Web application, or Web service for which you want to enable other authentication methods.


这篇关于WCF基于消息的安全性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆