Contents tagged with OAuth

  • OAuth in action – Linq2Twitter

    The other day I came across a pretty cool project, Linq2Twitter, that basically implements a linq provider for consuming the Twitter REST Api.  This project is not only interesting because it provides an intuitive model for incorporating Twitter calls into any existing application, but also because it shows how to use the OAuth authentication mode that the Twitter Api supports.

    As it is common with other linq providers, this library provides a root class “TwitterContext” for executing queries or calling other services in the API.

    So you can do things like this,

    var twitterCxt = new TwitterContext();

    var tweets =

        from tweet in twitterCtx.Status

        where tweet.Type == StatusType.Friends

        select tweet;

    tweets.ToList().ForEach(

        tweet => Console.WriteLine(

            "Friend: {0}\nTweet: {1}\n",

            tweet.User.Name,

            tweet.Text));

    The example above shows some code to gets the status of all your friends.

    Before using any of the services available in the API, you must first authenticate in Twitter using either basic authentication (The traditional way with username and password) or OAuth. The authentication mode is specified in the twitter context.

    In case you decide to go with OAuth, it is very simple to use. You only need to provide the OAuth secret and key associated to an application that you previously registered in Twitter.

    Console.Write("Consumer Key: ");

    twitterCtx.ConsumerKey = Console.ReadLine();

    Console.Write("Consumer Secret: ");

    twitterCtx.ConsumerSecret = Console.ReadLine();

    string link = twitterCtx.GetAuthorizationPageLink(false, false);

    Console.WriteLine("Authorization Page Link: {0}\n", link);

    Console.WriteLine("Next, you'll need to tell Twitter to authorize access. This program will not have access to your credentials, which is the benefit of OAuth.  Once you log into Twitter and give this program permission, come back to this console and press Enter to complete the authorization sequence.\n\nPress Enter now to continue.");

    Console.ReadKey();

    // launches browser so you can log in and give permissions

    Process.Start(link);

    Console.WriteLine("\nYou should see your browser navigate to Twitter, saying that your application wants to access your Twitter account. Once you've authorized this program, return to this console and press any key to execute the LINQ to Twitter code.");

    Console.ReadKey();

    var uri = new Uri(link);

    NameValueCollection urlParams = HttpUtility.ParseQueryString(uri.Query);

    string oAuthToken = urlParams["oauth_token"];

    twitterCtx.RetrieveAccessToken(oAuthToken);

    if (twitterCtx.AuthorizedViaOAuth)

    OAuth requires a browser session so you can log into twitter and authorize the client application to get your data. This is not a problem if the client application is a web application, the authentication and authorization processes flow very natural. However, in the case of Windows or Console Application, a browser instance needs to be created, this is what the example above is doing in the line “Process.Start”. If you are already authenticated in twitter, you will see this page where you need to authorize the application that wants to get access to your data.

    Twitter

    It looks like Andrew Arnott have been involved in the OAuth implementation for this library, which is a really good thing since he is the main contributor in two of the most stables projects for OpenID (DotNetOpenId) and OAuth (DotNetOpenAuth) in the .NET world. 

    Read more...

  • Webcast "OpenID, OAuth y Live ID. Cual es la diferencia ?

    El proximo miercoles 20 de mayo a las 3 PM (GMT-05:00 Colombia, Panama), voy a estar presentando un MSDN webcast acerca de OpenID, OAuth y Windows Live ID. El evento va a ser transmitido en castellano para la comunidad de latinoamerica, y se va a enfocar en las caracteristicas principales de estas soluciones/protocolos, como funcionan, y algunos escenarios en donde se pueden aplicar con exito.

    El link al evento es el siguiente, http://msevents.microsoft.com/CUI/EventDetail.aspx?EventID=1032403625&Culture=es-AR 

    Los espero.

    Read more...

  • Some thoughts on OpenID and OAuth for Desktop clients

    OpenID and OAuth are today excellent solutions for "Single Sign On" (SSO)  and "Authorization Delegation" respectively. They are, however, based on Http Redirections and therefore, tied to passive clients or commonly called web browsers.

    An interesting research was made by google some time ago, it can be found here. After reading that article, it looks like they could not get rid of a browser at all :(.

    If that does not work for you, another solution could be WS-Federation Active Profile. 

    "SSO" is an inherent feature of WS-Federation, not doubt about it.

    "Authorization Delegation" can also be emulated with a combination of "SSO" and authorization claims. In this scenario, we always give our credentials to an identity provider we trust, there is no need to give away our credentials to any site or service involved in a transaction. The authorization claims also represent fine-granular permissions of what we are allowed to do on the service side, and again, they can provided by identity provider itself or a resource STS. I discussed this approach in my last post, "Addressing Authorization with OAuth or the .NET Access Control Service", the resource STS in this case would be the ACS service.

    Read more...

  • Addressing authorization with OAuth or the .NET Access Control Service

    OAuth

    As I mentioned in the post, "OAuth Channel for REST services", OAuth allows a client application to obtain user consent (as access tokens) for executing operations over private resources on his behalf. Resources in this context represent anything from the user that the service provider make public through services, they could be for instance contacts, pictures or personal information to name a few.

    The access token that the consumer gets from the service provider represents in some way an Access Control List that maps directly with permissions granted by the user over his resources. For example, John provides read/write access to his contacts on Windows Live (Service provider) to a third party service (consumer).

    A previous direct trust relationship must exist between the consumer and the service provider in order to make all this happen, that relationship in OAuth also takes the form of a Request Token. If the consumer can not get a request token from the service provider, the user is not even redirected to this last one for negotiating the access token.

    As more service providers get involved in a simple scenario, more access tokens the consumer will have to negotiate. In addition, the user should have registered in each one of those service provider prior to use the consumer application, unless he was  lucky enough to have Open ID authentication in some of those services.

    In the image above, the user is authenticated by the service provider during the request token/access token exchange.

    .NET Access Control Service

    The Microsoft .NET Access Control Service was recently announced in the PDC as part of the Windows Azure platform. (It was formerly part of Biztalk services). Today, it is complemented by two other services, the Microsoft .NET Service Bus and Microsoft .NET Workflow Service.

    This service in addition to be a valid Secure Token Service (WS-Trust) that can participate in the identity metasystem, it is a claim transformer. It was conceived with the idea of mapping some input claims (Identity claims usually) into authorization claims that represent an ACL for the service running on the relying party.

    The SAML token containing these output claims would be equivalent to the access token in OAuth. 

    As we saw in OAuth, a prior trust agreement must exist between the relying party and the .NET Access Control Service. In this case, A X509 public key for the relying party must be registered on the .NET ACL service (for encrypting the SAML token), and the relying party must have a X509 public key coming from the .NET ACL for verifying the token signature. As part of this agreement, also some control rules for mapping claims must defined  in the .NET ACL service configuration (The .NET ACL will use the appliesTo header in the WS-Trust RST message to determine which rules have to be used).

    If we analyze now the scenario discussed before with OAuth, a single consumer and multiple service providers, the client always authenticates against the same identity provider, no matter the number of the service providers involved, which is a pretty good thing. OAuth depends on Open ID for getting the same effect.

    The picture below show the complete scenario with a single relying party,

     

     

    Read more...

  • Using the WCF OAuth channel with an ADO.NET service

    As I promised in my previous post "OAuth Channel for WCF RESTful services", it is now time to show this new channel in action with a real service. To make this sample more interesting, I decided to base this implementation on an ADO.NET service that provides information about contacts.

    This post will be a kind of walk-through to demonstrate all the steps required to implement the ADO.NET service, and then, the final integration with OAuth.

    1.Create a custom data source (IQueryable) implementation for using with the ADO.NET data service

    [DataServiceKey("Id")]

    public class Contact

    {

        public int Id { get; set; }

        public string Name { get; set; }

        public string Email { get; set; }

        public string Owner { get; set; }

    }

     

    public class ContactsData

    {

        static Contact[] _contacts;

     

        static ContactsData()

        {

            _contacts = new Contact[]{

              new Contact(){ Id=0, Name="Mike", Email="mike@contoso.com", Owner = "jane" },

              new Contact(){ Id=1, Name="Saaid", Email="Saaid@hotmail.com", Owner = "jane"},

              new Contact(){ Id=2, Name="John", Email="j123@live.com", Owner = "john"},

              new Contact(){ Id=3, Name="Pablo", Email="Pablo@mail.com", Owner = "john"}};

        }

     

        public IQueryable<Contact> Contacts

        {

            get { return _contacts.AsQueryable<Contact>(); }

        }

     

    }

    What I defined here is a simple Contact class representing the contact entity and a ContactsData for the ADO.NET service data source. The service will automatically reflect the IQueryable properties in this data source class. The "DataServiceKey" attribute on top of the contact entity is required by ADO.NET services to define an artificial primary key on custom classes (It took me some to figure this out).

    2. Implement the ADO.NET data service

    public class contacts : DataService<ContactsData>

    {

        // This method is called only once to initialize service-wide policies.

        public static void InitializeService(IDataServiceConfiguration config)

        {

            config.SetEntitySetAccessRule("*", EntitySetRights.AllRead);

        }

     

        [QueryInterceptor("Contacts")]

        public Expression<Func<Contact, bool>> OnQueryContact()

        {

            var name = Thread.CurrentPrincipal.Identity.Name;

            return c => c.Owner.Equals(name, StringComparison.OrdinalIgnoreCase);

        }

    }

    The "QueryInterceptor" in this service implementation basically filters the resulting contacts based on the authenticated user. As I showed in my previous post, the authentication is performed by the OAuth channel.

    3. Configure the OAuth WCF channel for the ADO.NET data service

    <%@ ServiceHost Language="C#" Factory="ExampleOAuthChannel.AppServiceHostFactory" Service="ADOServices.OAuth.contacts" %>

    using System;
    using System.ServiceModel;
    using System.ServiceModel.Activation;
    using Microsoft.ServiceModel.Web;

    namespace ExampleOAuthChannel
    {
      class AppServiceHostFactory : ServiceHostFactory
      {
        protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
        {
            WebServiceHost2 result = new WebServiceHost2(serviceType, true, baseAddresses);
            result.Interceptors.Add(new OAuthChannel.OAuthInterceptor(
       ADOServices.OAuth.OAuthServicesLocator.Provider, ADOServices.OAuth.OAuthServicesLocator.AccessTokenRepository));
            return result;
        }
      }
    }

    Nothing new in this step, I only registered the OAuth interceptor in the WCF service host for the ADO.NET service.

    Download the complete example. (It includes a client application implementation as well)

    Read more...

  • OAuth channel for WCF RESTful services

    While OpenID and WS-Federation focus on delegating user identity (or a collection of identity claims), OAuth was designed to address a different and complementary scenario, the delegation of user authorization. In few words, OAuth allows a client application to obtain user consent (as access tokens) for executing operations over private resources on his behalf.

    The analogy given by Eran Hammer Lahav in this post "Explaining OAuth" is very close to what the specification tries to address,

    "Many luxury cars today come with a valet key. It is a special key you give the parking attendant and unlike your regular key, will not allow the car to drive more than a mile or two. Some valet keys will not open the trunk, while others will block access to your onboard cell phone address book. Regardless of what restrictions the valet key imposes, the idea is very clever. You give someone limited access to your car with a special key, while using another key to unlock everything else."

    Now, if we analyze the specification in more detail, we will see that the real purpose behind OAuth is to create a network of collaboration  between applications. It will not be necessary anymore to keep all our stuff just in a single place, we can have for instance our pictures in a website, our contacts in another place and a third application making use of them, all these applications collaborating together.

    If you want to know more about how OAuth works, you should read the following posts

    When I initially said that OpenID and OAuth complement each other, I meant that the user can first authenticated by an OpenID provider, and then redirected to the relying party to obtain his consent. (Authorization for consuming a private resource).

    Alex Henderson (Aka Bittercoder) has written a pretty good OAuth library in .NET for implementing an OAuth consumer and service provider. The library is available here under a MIT license (do wherever you want with it), and it is very easy to use. Alex has definitively made a very good work.

    My WCF channel implementation for OAuth mounts on top of his library and it basically transforms a OAuth token into a .NET security principal that can be used later within the service implementation. The channel is implemented as a RequestInterceptor, one of new features introduced in the REST WCF Starter Kit. This interceptor basically captures the request at channel level and performs all the validations required by OAuth. The following sample illustrates how the interceptors can be plugged into an existing service host (service.svc),

    <%@ ServiceHost Language="C#" Debug="true" Service="ExampleOAuthChannel.FeedService" Factory="ExampleOAuthChannel.AppServiceHostFactory"%>

    using System;
    using System.ServiceModel;
    using System.ServiceModel.Activation;
    using Microsoft.ServiceModel.Web;

    namespace ExampleOAuthChannel
    {
      class AppServiceHostFactory : ServiceHostFactory
      {
        protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
        {
            WebServiceHost2 result = new WebServiceHost2(serviceType, true, baseAddresses);
            result.Interceptors.Add(new OAuthChannel.OAuthInterceptor(
       OAuthServicesLocator.Provider, OAuthServicesLocator.AccessTokenRepository));
            return result;
        }
      }
    }

    OAuthServicesLocator.Provider and OAuthServiceLocator.AccessTokenRepository are just part of the OAuth implementation.

    The interaction (and all the messages interchanged) between the consumer and the provider was very well summarized by Alex in this post "OAuth for beginners"

    The following code illustrates some of the functionality implemented in the OAuth interceptor,

    Message request = requestContext.RequestMessage;

    HttpRequestMessageProperty requestProperty = (HttpRequestMessageProperty)request.Properties[HttpRequestMessageProperty.Name];

     

    OAuthContext context = new OAuthContextBuilder().FromUri(requestProperty.Method, request.Headers.To);

     

    try

    {

        _provider.AccessProtectedResourceRequest(context);

     

        OAuthChannel.Models.AccessToken accessToken = _repository.GetToken(context.Token);

     

        TokenPrincipal principal = new TokenPrincipal(

            new GenericIdentity(accessToken.UserName, "OAuth"),

            accessToken.Roles,

            accessToken);

     

        InitializeSecurityContext(request, principal);

    }

    catch (OAuthException authEx)

    {

        XElement response = XElement.Load(new StringReader("<?xml version=\"1.0\" encoding=\"utf-8\"?><html xmlns=\"http://www.w3.org/1999/xhtml\" version=\"-//W3C//DTD XHTML 2.0//EN\" xml:lang=\"en\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.w3.org/1999/xhtml http://www.w3.org/MarkUp/SCHEMA/xhtml2.xsd\"><HEAD><TITLE>Request Error</TITLE></HEAD><BODY><DIV id=\"content\"><P class=\"heading1\"><B>" + HttpUtility.HtmlEncode(authEx.Report.ToString()) + "</B></P></DIV></BODY></html>"));

        Message reply = Message.CreateMessage(MessageVersion.None, null, response);

        HttpResponseMessageProperty responseProperty = new HttpResponseMessageProperty() { StatusCode = HttpStatusCode.Forbidden, StatusDescription = authEx.Report.ToString() };

        responseProperty.Headers[HttpResponseHeader.ContentType] = "text/html";

        reply.Properties[HttpResponseMessageProperty.Name] = responseProperty;

        requestContext.Reply(reply);

     

        requestContext = null;

    }

    It basically validates the OAuth ticket using the library written by Alex and initializes a new principal containing the ticket identity. If the ticket can not be validated for some reason, it returns a friendly exception to the consumer.

    UPDATE: Alex has now include the channel as part of the OAuth Library. It is available under the following links,

    http://devdefined-tools.googlecode.com/svn/trunk/projects/oauth/DevDefined.OAuth.Wcf/

    http://devdefined-tools.googlecode.com/svn/trunk/projects/oauth/ExampleOAuthChannel/

    Coming next  "Using the WCF OAuth channel with an ADO.NET service" (The complete source code will be available as part of that post)

    Read more...