WCF 4 Step By Step Chapter 5 Note (Authentication in Internet)

When you start connecting client applications and services across a public network such as the Internet, you can no longer make any assumptions about the trustworthiness of client applications, services, or the communications passing between them.


 Authenticating and Authorizing Users by Using the ASP.NET Membership Provider and the ASP.NET Role Provider

            -By hosting a WCF service in "Internet Information Services (IIS)", you can usethe ASP.NET Web Site Administration Tool to easily create a SQL Server database containing the security information for the service and, manage users and roles. You can then configure the WCF service to use the ASP.NET Membership Provider to authenticate users, and the ASP.NET Role Provider to retrieve role information for authorizing users.

            -Setup certificate to IIS




            ConfigWCF

            1.The hostWeb site is configured to use theHTTPS protocol, so the WCF service must be configured to supporttransport-level security

            2. If youare using the HTTPS protocol and you wish to enable the service to publish metadata, you must set the HttpsGetEnabled property of theserviceMetadata behavior

to True. Additionally, you cannot set both theHttpGetEnabled and the HttpsGetEnabled

 

Configuration (Service Part)

          

<ws2007HttpBinding>
    <binding name="ProductsServiceWS2007HttpBindingConfig">
     <security mode="TransportWithMessageCredential">
      <transport clientCredentialType="None" />
      <message clientCredentialType="UserName" />
     </security>
    </binding>
   </ws2007HttpBinding>

  <serviceBehaviors>
    <behaviorname="">
    <serviceMetadata httpGetEnabled="false"httpsGetEnabled="true" />
     <serviceDebugincludeExceptionDetailInFaults="false" />
    <serviceAuthorizationprincipalPermissionMode="UseAspNetRoles"
     roleProviderName="AspNetSqlRoleProvider" />
     <serviceCredentials>
     <userNameAuthenticationuserNamePasswordValidationMode="MembershipProvider"
      membershipProviderName="AspNetSqlMembershipProvider" />
    </serviceCredentials>
    </behavior>
  </serviceBehaviors>

 UserAuthorization

            

Service Code

-via               

 [PrincipalPermission(SecurityAction.Demand,Role = "WarehouseStaff")]
        public intCurrentStockLevel(string productNumber)
        {

            -via"ServiceSecurityContext", The ServiceSecurityContext class contains informationabout the current security context

for the WCF operation being performed.

            

public boolChangeStockLevel(string productNumber, short newStockLevel,
                                     stringshelf, int bin)
        {
            //Determine whether the user is a member of the StockControllers role
           WindowsPrincipal user = new WindowsPrincipal(
                   (WindowsIdentity)Thread.CurrentPrincipal.Identity);
            if(!(user.IsInRole("StockControllers")))
            {
                // Ifthe user is not in the StockControllers role, 
                //throw a SecurityException
                thrownew SecurityException("Access denied");
            }

Client Code

            ProductsServiceClientproxy = new ProductsServiceClient("WS2007HttpBinding_IProductsService");
 
           proxy.ClientCredentials.UserName.UserName = "Fred";
           proxy.ClientCredentials.UserName.Password = "Pa$$w0rd";

 

Authenticating and Authorizing Users by Using Certificates

public key infrastructure (PKI).PKI provides a mechanismboth for encrypting messages and for authenticating them.

(encrypting messages) PKI is based on pairs of keys (a key isa long sequence of random numbers):a public key that you can use to encrypt messages, and a private key that you can use to decrypt them again.

(authenticating messages) Public and private keys can also work the other way around.If you encrypt a message with your private key, anyone with the public key can decrypt it.this provides a convenient mechanism for verifying the source of a message. If a third party receives an encrypted message that purports to come from you but that it cannot decrypt by using the public key that you provided, then the chances are that this message was actually from someone else pretending to be you.

E.G:

When you wish to communicate with a third party, you cansend them a message that includes ahash(a calculated summary, similar to a checksumbut more complicated) of the message contents encrypted with your private key—this is referred toas your signature

Where do you get keys? Well, you can request a pair of keysin a certificate from a certification authority, or CA.


Modify the WCF Service to Require Client Applications to Authenticate by Using Certificates  -(Authenticate Client to be trusted)

            -ChangeService Binding the "MessageClientCredentialType" property toCertificate

                        -"NegotiateServiceCredential":true:theWCF service expects the client application to include the certificate with the messages that it sends

                        -"NegotiateServiceCredential":false:theadministrator for the WCF service must install the client certificate manuallyin the Trusted People certificate store of the computer running the service.


            -Setservice behavior clientCertificate "CertificateValidationMode" propertyto PeerTrust


           

Client Code:

 

ProductsServiceClient proxy = newProductsServiceClient("WS2007HttpBinding_IProductsService");
                        proxy.ClientCredentials.ClientCertificate.SetCertificate(
StoreLocation.CurrentUser, StoreName.My,
X509FindType.FindBySubjectName, "Bert");

You need to modify the definitions of the users and roles inthe SQL Server database to map user identities retrieved from user’s certificates to roles.

The Current.PrimaryIdentity.Name property of the ServiceSecurityContext objectcontains the identifier of the currently authenticated user. The identifier for the authenticated user consists of two parts: the subject name,and the

thumbprint of the certificate.

**Update the User Information in the SQL Server Database

UserName: CN=Bert; c527cb3eabca372ccf661c7afbfb8b86b5a91145

 

Authenticating Service Messages by Using a Certificate -(Authenticate Service to be trusted)

Using the HTTPS protocol with a service gives a clientapplication a reasonable degree of confidence that communications with the service are secure. The service sends the client a certificate with a key that the client application uses for encrypting communications, and the client applicationverifies that the certificate sent by the service has originated from atrusted CA.

However, HTTPS is primarily concerned with ensuring theconfidentiality ofcommunications. Authentication for the purpose of establishing an SSL session is not the same as perform in message authentication, which can verify the identity of themessage sender.


Configure the WCF Service to Authenticate Itself to ClientApplications by Using the Localhost Certificate 

Configuration

<serviceBehaviors>
    <behavior name="">
     <serviceMetadata httpGetEnabled="false" httpsGetEnabled="true" />
     <serviceDebug includeExceptionDetailInFaults="false" />
     <serviceAuthorization principalPermissionMode="UseAspNetRoles"
      roleProviderName="AspNetSqlRoleProvider" />
     <serviceCredentials>
      <clientCertificate>
       <authentication certificateValidationMode="PeerTrust" />
      </clientCertificate>
      <serviceCertificate findValue="localhost" x509FindType="FindBySubjectName" />
      <userNameAuthentication userNamePasswordValidationMode="MembershipProvider"
       membershipProviderName="AspNetSqlMembershipProvider" />
     </serviceCredentials>
    </behavior>
   </serviceBehaviors>
Export the WCF Service Certificate and Import It into the Client Certificate Store
Configure the WCF Client Application to Authenticate the WCF Service

Identifying a Service


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值