Implementing oauth in SugarCRM using .NET

after much pain, I've got my .Net Code working on SugarCRM.....

This is what I did....all in a Console app for me. This a proof of concept and so everthing is hard coded for now!

Use Nuget to Install OAuth by Daniel Crenna

Step 1: Establish Consumer Key

Go into Admin -> OAuth Keys section on SugarCRM and create a new record, I used Key & Secret.

Step 2: Creating a Request Token

private static void CreateRequestToken()
{
    // Creating a new instance directly
    OAuthRequest client = new OAuthRequest
    {
        Method = "GET",
        Type = OAuthRequestType.RequestToken,
        SignatureMethod = OAuthSignatureMethod.HmacSha1,
        ConsumerKey = "Key",
        ConsumerSecret = "Secret",
        RequestUrl = "http://localhost/service/v4/rest.php",
        Version = "1.0",
        SignatureTreatment = OAuthSignatureTreatment.Escaped
    };

    // Using URL query authorization
    string auth = client.GetAuthorizationQuery(new Dictionary<string, string>() { { "method", "oauth_request_token" } });

    var request = (HttpWebRequest)WebRequest.Create("http://localhost/service/v4/rest.php?method=oauth_request_token&" + auth);
    var response = (HttpWebResponse)request.GetResponse();

    NameValueCollection query;
    using (StreamReader sr = new StreamReader(response.GetResponseStream()))
    {
        string result = sr.ReadToEnd();

        query = HttpUtility.ParseQueryString(result);
    }

    Console.WriteLine(query["authorize_url"]);
    Console.WriteLine(query["oauth_token"]);
    Console.WriteLine(query["oauth_token_secret"]);
}

This is the tricky part that took me ages to figure out, notice the requesturl is without the query part in the client, and you have add it to the GetAuthorizationQuery call AND to the actual WebRequest url.

Note down the 3 items ready for Step 4.

Step 3 Approve Request Token

Visit the url "authorize_url" above and also add &token= "oauth_token". For this was:

http://localhost/index.php?module=OAuthTokens&action=authorize&token=adae15a306b5

Authorise the token and record the Token Authorisation Code.

Step 4 Request Access Token

private static void RequestAccessToken()
{
    OAuthRequest client = new OAuthRequest
    {
        Method = "GET",
        Type = OAuthRequestType.AccessToken,
        SignatureMethod = OAuthSignatureMethod.HmacSha1,
        ConsumerKey = "Key",
        ConsumerSecret = "Secret",
        RequestUrl = "http://localhost/service/v4/rest.php",
        Version = "1.0",
        SignatureTreatment = OAuthSignatureTreatment.Escaped,
        Token = "adae15a306b5",
        TokenSecret = "e1f47d2a9e72",
        Verifier = "33e2e437b2b3"
    };

    // Using URL query authorization
   string auth = client.GetAuthorizationQuery(new Dictionary<string, string>() { { "method", "oauth_access_token" } });

   var request = (HttpWebRequest)WebRequest.Create("http://localhost/service/v4/rest.php?method=oauth_access_token&" + auth);
   var response = (HttpWebResponse)request.GetResponse();

   NameValueCollection query;
   using (StreamReader sr = new StreamReader(response.GetResponseStream()))
   {
       string result = sr.ReadToEnd();
       query = HttpUtility.ParseQueryString(result);
   }

   Console.WriteLine(query["oauth_token"]);
   Console.WriteLine(query["oauth_token_secret"]);
}

Token and TokenSecret are from Step 2, Verifier is the Auth Code from Step 3.

Step 5 Use the Access Token

I'm just using the session id as Recommended by the Documentation, so to get the sessionId

private static void GetSessionId()
{
    OAuthRequest client = new OAuthRequest
    {
        Method = "GET",
        Type = OAuthRequestType.ProtectedResource,
        SignatureMethod = OAuthSignatureMethod.HmacSha1,
        ConsumerKey = "Key",
        ConsumerSecret = "Secret",
        RequestUrl = "http://localhost/service/v4/rest.php",
        Version = "1.0",
        SignatureTreatment = OAuthSignatureTreatment.Escaped,
        Token = "adae15a306b5",
        TokenSecret = "2d68ecf5152f"
     };

     string auth = client.GetAuthorizationQuery(new Dictionary<string, string>() 
     { 
        { "method", "oauth_access" }, 
        { "input_type", "JSON" },
        { "request_type", "JSON" },
        { "response_type", "JSON" } 
     });

     var request = (HttpWebRequest)WebRequest.Create("http://localhost/service/v4/rest.php?method=oauth_access&input_type=JSON&request_type=JSON&response_type=JSON&" + auth);
     var response = (HttpWebResponse)request.GetResponse();

     dynamic o;
     using (StreamReader sr = new StreamReader(response.GetResponseStream()))
     {
         string result = sr.ReadToEnd();
         o = Newtonsoft.Json.JsonConvert.DeserializeObject(result);
     }

     Console.WriteLine("SessionId: {0}", o.id);
}

Here I'm using JSON.Net to parse the Json into a dynamic object for easy access to the id.

Step 6 Make it do something....

Over to you!

Pretty painful experience, but at least its working for me.....

Tim


I didn't get what you meant by implementing in SugarCRM way. But if you can't use dotnetopenauth, you can spin your own OAuth using RestSharp or Hammock