Showing posts with label WCF. Show all posts
Showing posts with label WCF. Show all posts

Wednesday, April 18, 2012

Authentication using WCF and asp.net custom-membership-provider

http://aspguy.wordpress.com/2011/07/30/single-sign-on-with-wcf-and-asp-net-custom-membership-provider/
http://www.codewrecks.com/blog/index.php/2009/11/26/wcf-over-https-authentication-with-asp-net-membership/
http://stackoverflow.com/questions/2615316/using-asp-net-membership-provider-authentincation-in-a-wcf-service

Using the ASP.NET Membership Provider and Authentication Service from Windows Phone 7


Those of you who have been building ASP.NET applications for a while now are no doubt familiar with the provider model, which includes provider abstractions for membership (authentication), roles (authorization), profiles (user data), and session state. These providers make it incredibly easy to provide a secure framework for your application. In fact, with an ASP.NET application template right out of the box, you can have a fully functioning authenticated, secure website in minutes.
What a lot of people have less familiarity with is the notion of provider services. You can actually create a WCF service head that sits on top of the ASP.NET membership system. This allows client applications to authenticate against your ASP.NET website using exactly the same authentication scheme that your users use. This means that a user who has access to your website should also be able to have access to the client application seamlessly.
To see how this works, create yourself a new ASP.NET MVC app (you can do this with a regular ASP.NET app, but I just happened to use MVC). Before doing anything, run the app, go to the “Log On” area, register yourself as a user and then quit the app. If you’ve got SQL Express installed properly and everything else is in order, your app now knows who you are.
Next, add a new WCF service to this application (call it Authentication.svc). Delete the files Authentication.svc.cs and the IAuthentication.cs. Open up the Authentication.svc file and replace it’s contents entirely with the following:



<%@ ServiceHost Language="C#"
    Service="System.Web.ApplicationServices.AuthenticationService" %>
Note here that there’s no code-behind. All we’re doing is exposing a service that is already part of the ASP.NET framework at a specific endpoint. You’re not quite ready yet – we have to make this service ASP.NET compatible, so open up your Web.config file and make sure that your system.servicemodel section looks like this:


































<system.serviceModel>
 <services>
 <service name="System.Web.ApplicationServices.AuthenticationService"
behaviorConfiguration="AuthenticationServiceBehaviors">
 <endpoint contract="System.Web.ApplicationServices.AuthenticationService"
     binding="basicHttpBinding" />
 </service>
 <service name="Wp7AspNetMembership.HelloService"
     behaviorConfiguration="AuthenticationServiceBehaviors">
 <endpoint
     contract="Wp7AspNetMembership.IHelloService"
     binding="basicHttpBinding"/>
 </service>
 </services>
 <serviceHostingEnvironment aspNetCompatibilityEnabled="true"
     multipleSiteBindingsEnabled="true" />
 <behaviors>
 <serviceBehaviors>
 <behavior name="AuthenticationServiceBehaviors">
 <serviceMetadata httpGetEnabled="true" />
 </behavior>
 <behavior name="">
 <serviceMetadata httpGetEnabled="true" />
 <serviceDebug includeExceptionDetailInFaults="false" />
 </behavior>
 </serviceBehaviors>
 </behaviors>
 </system.serviceModel>
 
 <system.web.extensions>
 <scripting>
 <webServices>
 <authenticationService enabled="true" requireSSL="false"/>
 </webServices>
 </scripting>
 </system.web.extensions>
What’s going on in this Web.config file is pretty interesting. First, we’re exposing Authentication.svc and HelloService.svc (not yet created) over HTTP, with metadata allowed, with ASP.NET compatibility enabled. We’ve also used the system.web.extensions element to indicate that the authentication service is being enabled. In a production environment, you would set requireSSL to true.
At this point, you should be able to hit the URL /Authentication.svc and see the standard metadata page. Now let’s create HelloService.svc by creating a standard WCF service. Change the interface so it only has a single method called HelloWorld() that returns a string. The following is the implementation of HelloService.svc.cs:

























using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.Web;
using System.ServiceModel.Activation;
 
namespace MvcApplication1
{
 [AspNetCompatibilityRequirements(
    RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
 public class HelloService : IHelloService
 {
  public string HelloWorld()
  {
   if (HttpContext.Current.User.Identity.IsAuthenticated)
     return HttpContext.Current.User.Identity.Name;
   else
     return "Unauthenticated Person";
  }
 }
}
This is a pretty simple service. Just pretend that instead of returning the name of the authenticated user, we’re actually performing some vital business function that requires a valid user context.
Now, we can get to the good stuff : the WP7 application :) In this WP7 application we’re going to create a login form, submit user credentials over the wire, get validation results and, if the user was authenticated, we’re going to call the HelloWorld() method with a validated, secure context – all of this with an incredibly small amount of work on the part of the WP7 client.
Add a new WP7 application (just the stock one, not the list view) to the solution, I called mine TestMembershipClient but you can pick whatever you like. Add service references to Authentication.svc and to HelloWorld.svc (I named the reference namespaces MvcWebAppReference for authentication and AspNetMvcRealReference for the service that simulates doing real work).
On your main page, drop a couple text block labels, two text boxes, and a submit button. When you run the app at this point, it should look like this screenshot:
WP7 Login Form
WP7 Login Form
Now rig up a click handler for the submit button with code that looks like this:





































private void LoginButton_Click(object sender, RoutedEventArgs e)
{
 MvcWebAppReference.AuthenticationServiceClient authService =
   new MvcWebAppReference.AuthenticationServiceClient();
 cc = new CookieContainer();
 authService.CookieContainer = cc;
 authService.LoginCompleted +=
   new EventHandler<MvcWebAppReference.LoginCompletedEventArgs>(
 authService_LoginCompleted);
 authService.LoginAsync(UsernameBox.Text, PasswordBox.Text, "", true);
}
 
void authService_LoginCompleted(object sender,
 MvcWebAppReference.LoginCompletedEventArgs e)
{
 if (e.Error != null)
 {
 MessageBox.Show("Login failed, you Jackwagon.");
 }
 else
 {
   AspNetMvcRealReference.HelloServiceClient helloService =
    new AspNetMvcRealReference.HelloServiceClient();
   helloService.CookieContainer = cc;
   helloService.HelloWorldCompleted +=
   new EventHandler<AspNetMvcRealReference.HelloWorldCompletedEventArgs>(
     helloService_HelloWorldCompleted);
   helloService.HelloWorldAsync();
 }
}
 
void helloService_HelloWorldCompleted(object sender,
 AspNetMvcRealReference.HelloWorldCompletedEventArgs e)
{
 MessageBox.Show("You're logged in, results from svc: " + e.Result);
}
Most of this is pretty straightforward. When the user clicks the submit button, it calls the LoginAsync method on the membership service (remember that all service calls in Silverlight are asynchronous). When we get the results of that call, we either tell the user that their login has failed, or we invoke the HelloWorld method (also asynchronously). When the hello world method comes back from the server, we display the results of the execution in a message box that looks like the one in the screenshot below:
Results of Calling a Secured Service from WP7
Results of Calling a Secured Service from WP7
One thing to take very careful note of is the CookieContainer. Because we’re using two different proxies: 1 to talk to the authentication service and 1 to talk to the hello world service, we have to ensure that these two proxies are using the same cookie container so that the auth cookie can be used by subsequent method calls on other services. You can do this for an unlimited number of services that are on the same DNS domain, so long as they all share the same cookie container. To enable the use of cookie containers in WCF services in Silverlight (it’s disabled by default), you have to set the enableHttpCookieContainer property to true. in the binding element in the ServiceReferences.ClientConfig file.
On the surface you might not think this is all that big of a deal. You might also think this is difficult but, keep in mind that I provided a pretty detailed walkthrough. This whole thing only took me about 15 minutes to set up from start to finish once I’d figured out how the CookieContainer thing worked. So why bother with this?
Consider this: If you already have an ASP.NET application that is using the membership provider, role provider, and profile provider you can quickly, easily, and securely expose services to a mobile (WP7) client that allow that client to have secured, remote access to services exposed by that site. In short, any user of your existing web application can use their existing credentials to log in from their WP7 device and access any services you decide to make available.
ASP.NET provider services, coupled with WP7 and the fact that Silverlight has access to WCF client proxy generation, means you can very easily prep your site for a rich WP7 experience.

Friday, January 27, 2012

What is DataContract and ServiceContract?

Data represented by creating DataContract which expose the
data which will be transefered /consumend from the serive
to its clients.

**Operations which is the functions provided by this
service.

To write an operation on WCF,you have to write it as an
interface,This interface contains the "Signature" of the
methods tagged by ServiceContract attribute,and all methods
signature will be impelemtned on this interface tagged with
OperationContract attribute.

and to implement these serivce contract you have to create
a class which implement the interface and the actual
implementation will be on that class.


Code Below show How to create a Service Contract:


[ServiceContract]
Public Interface IEmpOperations
{
[OperationContract]
Decimal Get EmpSal(int EmpId);

}

Class MyEmp: IEmpOperations
{
Decimal Get EmpSal()
{
// Implementation of this method.
}
}

Thursday, December 15, 2011

How Wcf is more secure than Websevices?

Following security used in WCF

Transfer security:- Responsible for providing message confidentiality, data integrity, and authentication of communicating parties.

Authorization:- Responsible for providing a framework for making authorization decisions.

Auditing:- Responsible for logging security-related events to the audit log.

For more Details:-
http://wcfsecurityguide.codeplex.com/wikipage?title=Ch%2004%20-%20WCF%20Security%20Fundamentals&referringTitle=Home


Security
WSE 3.0 Web services that are secured using a policy file

WCF services can use a configuration file to secure a service and that mechanism is similar to a WSE 3.0 policy file. In WSE 3.0 when securing a Web service using a policy file, you use either a turnkey security assertion or a custom policy assertion. The turnkey security assertions map closely to the authentication mode of a WCF security binding element. Not only are the WCF authentication modes and WSE 3.0 turnkey security assertions named the same or similarly, they secure the messages using the same credential types. For instance, the usernameForCertificate turnkey security assertion in WSE 3.0 maps to the UsernameForCertificate authentication mode in WCF. The following code examples demonstrate how a minimal policy that uses the usernameForCertificate turnkey security assertion in WSE 3.0 maps to a UsernameForCertificate authentication mode in WCF in a custom binding.

WSE 3.0
Copy

<policies>
<policy name="MyPolicy">
<usernameForCertificate messageProtectionOrder="SignBeforeEncrypt"
requireDeriveKeys="true"/>
</policy>
</policies>

WCF
Copy

<customBinding>
<binding name="MyBinding">
<security authenticationMode="UserNameForCertificate" 
messageProtectionOrder="SignBeforeEncrypt"
requireDerivedKeys="true"/>
</binding>
</customBinding>

To migrate the security settings of a WSE 3.0 Web service that are specified in a policy file to WCF, a custom binding must be created in a configuration file and the turnkey security assertion must be set to its equivalent authentication mode. Additionally, the custom binding must be configured to use the August 2004 WS-Addressing specification when WSE 3.0 clients communicate with the service. When the migrated WCF service does not require communication with WSE 3.0 clients and must only maintain security parity, consider using the WCF system-defined bindings with appropriate security settings instead of creating a custom binding.

The following table lists the mapping between a WSE 3.0 policy file and the equivalent custom binding in WCF.
WSE 3.0 Turnkey Security Assertion WCF custom binding configuration

<usernameOverTransportSecurity />

Copy

<customBinding>
<binding name="MyBinding">
<security authenticationMode="UserNameOverTransport" />
<textMessageEncoding messageVersion="Soap12WSAddressingAugust2004" />
</binding>
</customBinding>

<mutualCertificate10Security />

Copy

<customBinding>
<binding name="MyBinding">
<security messageSecurityVersion="WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10" authenticationMode="MutualCertificate" />
<textMessageEncoding messageVersion="Soap12WSAddressingAugust2004" />
</binding>
</customBinding>

<usernameForCertificateSecurity />

Copy

<customBinding>
<binding name="MyBinding">
<security authenticationMode="UsernameForCertificate"/>
<textMessageEncoding messageVersion="Soap12WSAddressingAugust2004" />
</binding>
</customBinding>

<anonymousForCertificateSecurity />

Copy

<customBinding>
<binding name="MyBinding">
<security authenticationMode="AnonymousForCertificate"/>
<textMessageEncoding messageVersion="Soap12WSAddressingAugust2004" />
</binding>
</customBinding>

<kerberosSecurity />

Copy

<customBinding>
<binding name="MyBinding">
<security authenticationMode="Kerberos"/>
<textMessageEncoding messageVersion="Soap12WSAddressingAugust2004" />
</binding>
</customBinding>

<mutualCertificate11Security />

Copy

<customBinding>
<binding name="MyBinding">
<security authenticationMode="MutualCertificate"/>
<textMessageEncoding messageVersion="Soap12WSAddressingAugust2004" />
</binding>
</customBinding>

For more information about creating custom bindings in WCF, see Custom Bindings.
WSE 3.0 Web services that are secured using application code

Whether WSE 3.0 or WCF is used, the security requirements can be specified in application code instead of in configuration. In WSE 3.0, this is accomplished by creating a class that derives from the Policy class and then by adding the requirements by calling the Add method. For more details about specifying the security requirements in code, see How to: Secure a Web Service Without Using a Policy File. In WCF, to specify security requirements in code, create an instance of the BindingElementCollection class and add an instance of a SecurityBindingElement to the BindingElementCollection. The security assertion requirements are set using the static authentication mode helper methods of the SecurityBindingElement class. For more details about specifying security requirements in code using WCF, see How to: Create a Custom Binding Using the SecurityBindingElement and How to: Create a SecurityBindingElement for a Specified Authentication Mode.
WSE 3.0 Custom Policy Assertion

In WSE 3.0 there are two types of custom policy assertions: those that secure a SOAP message and those that do not secure a SOAP message. Policy assertions that secure SOAP messages derive from WSE 3.0 SecurityPolicyAssertion class and the conceptual equivalent in WCF is the SecurityBindingElement class.

An important point to note is that the WSE 3.0 turnkey security assertions are a subset of the WCF authentication modes. If you have created a custom policy assertion in WSE 3.0, there may be an equivalent WCF authentication mode. For example, WSE 3.0 does not provide a CertificateOverTransport security assertion that is the equivalent to UsernameOverTransport turnkey security assertion, but uses an X.509 certificate for client authentication purposes. If you have defined your own custom policy assertion for this scenario, WCF makes the migration straightforward. WCF defines an authentication mode for this scenario, so you can take advantage of the static authentication mode helper methods to configure a WCF SecurityBindingElement.

When there is not a WCF authentication mode that is equivalent to a custom policy assertion that secures SOAP messages, derive a class from TransportSecurityBindingElement, SymmetricSecurityBindingElement or AsymmetricSecurityBindingElement WCF classes and specify the equivalent binding element. For more details, see How to: Create a Custom Binding Using the SecurityBindingElement.

To convert a custom policy assertion that does not secure a SOAP message, see Filtering and the sample Custom Message Interceptor.
WSE 3.0 Custom Security Token

The WCF programming model for creating a custom token is different than WSE 3.0. For details about creating a custom token in WSE, see Creating Custom Security Tokens. For details about creating a custom token in WCF, see How to: Create a Custom Token.


http://www.codeproject.com/KB/webservices/SOAPHeaderAuthentication.aspx

Thursday, December 1, 2011

What is the advantage of using WCF over other distributed programming models like Web Services(ASMX), .NET Remoting, Enterprise Services stack etc.?

To understand the advantage of using WCF over other distributed programming models like Web Services(ASMX), .NET Remoting, Enterprise Services stack etc, let's consider the following scenario. We have developed an application using web services. As we know web services use HTTP protocl and XML SOAP formatted messages, they are good for developing interoperable applications in a heterogeniuos environment. We have a new client. Our new client is using .NET and he wants binary formmatted messages over TCP protocol, because interoperability is not a concern and binary formmatted messages over TCP protocol are much faster than XML SOAP formmatted messages over HTTP. To satisfy the requirement of this client, now we cannot use our existing web service. So, we have to develop a brand new remoting application from the scratch. The business functionality is the same in web services and remoting application. Since our different clients have different requirements, we ended up creating the same business application using web services and remoting technologies. This approach has several disadvantages as listed below.
1. Developers have to be familiar with two different technologies (Web Services and Remoting).
2. We end up creating duplicate business applications with different technologies which also leads to maintainance overhead.


On the other hand WCF unifies Web Services, .NET Remoting, and Enterprise Services stacks under one roof. For the same requirement that we have seen untill now, we just create one application and expose multiple end points to satisfy the requirements of multiple clients. In WCF configuration drives protocol choices, messaging formats, process allocation, etc. WCF services are loosely coupled, meaning that a WCF service is not bound to a particular protocol, encoding format, or hosting environment. Everything is configurable.

Thursday, November 24, 2011


EndPoint

WCF Service is a program that exposes a collection of Endpoints. Each Endpoint is a portal for communicating with the world.
All the WCF communications are take place through end point. End point consists of three components.

Address

Basically URL, specifies where this WCF service is hosted .Client will use this url to connect to the service. e.g
http://localhost:8090/MyService/SimpleCalculator.svc

Binding

Binding will describes how client will communicate with service. There are different protocols available for the WCF to communicate to the Client. You can mention the protocol type based on your requirements.
A binding has several characteristics, including the following:
  • Transport -Defines the base protocol to be used like HTTP, Named Pipes, TCP, and MSMQ are some type of protocols.
  • Encoding (Optional) - Three types of encoding are available-Text, Binary, or Message Transmission Optimization Mechanism (MTOM). MTOM is an interoperable message format that allows the effective transmission of attachments or large messages (greater than 64K).
  • Protocol(Optional) - Defines information to be used in the binding such as Security, transaction or reliable messaging capability
The following table gives some list of protocols supported by WCF binding.
Binding Description
BasicHttpBinding Basic Web service communication. No security by default
WSHttpBinding Web services with WS-* support. Supports transactions
WSDualHttpBinding Web services with duplex contract and transaction support
WSFederationHttpBinding Web services with federated security. Supports transactions
MsmqIntegrationBinding Communication directly with MSMQ applications. Supports transactions
NetMsmqBinding Communication between WCF applications by using queuing. Supports transactions
NetNamedPipeBinding Communication between WCF applications on same computer. Supports duplex contracts and transactions
NetPeerTcpBinding Communication between computers across peer-to-peer services. Supports duplex contracts
NetTcpBinding Communication between WCF applications across computers. Supports duplex contracts and transactions

Contract

Collection of operation that specifies what the endpoint will communicate with outside world. Usually name of the Interface will be mentioned in the Contract, so the client application will be aware of the operations which are exposed to the client. Each operation is a simple exchange pattern such as one-way, duplex and request/reply.
Below figure illustrate the functions of Endpoint


Example:

Endpoints will be mentioned in the web.config file on the created service.
<system.serviceModel>
<services>
      <service name="MathService"
        behaviorConfiguration="MathServiceBehavior">
       <endpoint
         address="http://localhost:8090/MyService/MathService.svc" contract="IMathService"
          binding="wsHttpBinding"/> 
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="MathServiceBehavior">
          <serviceMetadata httpGetEnabled="True"/>
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>
  

Thursday, August 25, 2011

Creating and Consuming Your First WCF Service


Introduction
In this article, I will examine how to create and consume a WCF service. WCF is a next-generation programming platform and runtime system for building, configuring and deploying service-oriented applications. For more details, please see here.
Creating a WCF Service
I will create a stock service to demonstrate a WCF service. To create a WCF service, please follow these steps:
  1. Launch Visual Studio 2008.
  2. Click on File -> new -> project, then select WCF service application.
  3. It will create a WCF service application template.
I will delete the default contract and then create an IStock contract as shown below.
Using the Code
[ServiceContract]
    public interface IStock
    {
        [OperationContract]
        Stock GetStock(string Symbol);  
    }
The above contract has one method that returns a stock object for a given symbol. Here is our Stock class that has Symbol, Date, Company and Close properties respectively.
[DataContract]
    public class Stock
    {
        [DataMember]
        public string Symbol { get; set; }
        [DataMember]
        public DateTime Date { get; set; }
        [DataMember]
        public string Company { get; set; }
        [DataMember]
        public decimal Close { get; set; }
    }
Next, I will delete the default service and create a Stock service that will implement the Istock contract as shown below:
 public class Stocks : IStock
    {
        #region IStock Members
        public Stock GetStock(string Symbol)
        {
            Stock st = null;
            switch (Symbol.ToUpper())
            {
                case "GOOG":
                    st = new Stock { Symbol = Symbol, Date = DateTime.Now,
                          Company = "Google Inc.", Close = 495 };
                    break;
                case "MSFT":
                    st = new Stock { Symbol = Symbol, Date = DateTime.Now,
                          Company = "Microsoft Corporation", Close = 25 };
                    break;
                case "YHOO":
                    st = new Stock { Symbol = Symbol, Date = DateTime.Now,
                          Company = "Yahoo! Inc.", Close = 17 };
                    break;
                case "AMZN":
                    st = new Stock { Symbol = Symbol, Date = DateTime.Now,
                          Company = "Amazon.com, Inc.", Close = 92 };
                    break;
            }
            return st;
        }
        #endregion
    }
In the above service, I implemented IStock contract that has a GetStock method which returns stock object for a given Symbol.
Now, I will have the following endpoints in my web.config:
<service behaviorConfiguration="WcfSample.Service1Behavior" name="WcfSample.Stocks">
<endpoint address="" binding="wsHttpBinding" contract="WcfSample.IStock">
<identity>
 <dns value="localhost"/>
 </identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
In the above configuration, we have address="" which is localhost, binding="wsHttpBinding" and contract="WcfSample.IStock".
Now I will compile the service and build a client to consume the service.
Creating a Client to Consume Service

  1. Right Click on Solution -> Add -> new project, then select ASP.NET web application.
  2. It will create a web application template.
  3. Now, I will add the service reference. To add a service reference, select client application, then add a service reference. Since our client is in a same solution, I will click discover and service in the solution as shown below:


  4. In default.aspx, I will create a simple UI, a textbox to enter the stock symbol and a button to call the service to get stock information. Here is our code behind:
  5. ServiceReference2.StockClient sc = new ServiceReference2.StockClient();
  6. ServiceReference2.Stock st = sc.GetStock(TextBox1.Text.Trim());
  7. StringBuilder sb = new StringBuilder();
  8. sb.AppendFormat("<B>Company:</B> {0}<br />", st.Company);
  9. sb.AppendFormat("<B>Date: </B>{0}<br />", st.Date);
  10. sb.AppendFormat("<B>Close: </B>{0}<br />", st.Close);
  11. sb.AppendFormat("<B>Symbol: </B>{0}<br />", st.Symbol);
12.Label1.Text = sb.ToString();
  
Here are a few screenshots from our final application:

Summary
In this article, we examined how to create and consume a WCF service. As you can see, creating and consuming WCF service with Visual studio 2008 is pretty simple.