2

I've been trying to work with the Wrike API, but I am having trouble getting my access token using Ajax or ASP.Net. I am currently using the "Wrike for Developers Documentation", and this is my first time working with Oauth2. There aren't any JavaScript or ASP.net examples and I could only find projects on GitHub for node.js and PHP.

Here is the code I am using to try and get the access token:

$.ajax({
    type: 'POST',
    url: "https://www.wrike.com/oauth2/token",
    data: {
        client_id: <client_id>,//I took these details out for the post
        client_secret: <client_secret>,//I took these details out for the post
        grant_type: "authorization_code",
        code: get("code")//from redirect URI
    },
    crossDomain: true,
    dataType: 'jsonp',
    success: function (response) {
        alert(response); // server response
    }
});

However I keep getting Error 400 (bad request). Is there anything obvious that I'm missing? Or is this not possible to do without doing the authentication server side using C#?

I hope this is enough information for you. thanks in advance.

I also had cross origin issues that I think I solved with this post: Cross Origin Stack Over Flow Prior to that I used this as my code:

$.ajax({
  type: 'Post',
  url: "https://www.wrike.com/oauth2/token",
  data: {
    client_id: "<client_id>",
    client_secret: <client_Secret>,
    grant_type: "authorization_code",
    code: get("code")
  },
  success: function (response) {
    alert(response); // server response
  }
});

I also tried this to fix my CORS issue but with no avail: CORS on ASP.NET

Update:

I tried doing it via the ASP.net back end with C# I still get a error 400 bad request but when I take the request I made with it and put it into postman I am able to get the token. Here is the code I'm using. I'll update this question if I fix it completely.

protected void Page_Load(object sender, EventArgs e)
{

    Response.AppendHeader("Access-Control-Allow-Origin", "*");
    HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
    string ClientID = <ClientID>;
    string ClientSecret = <ClientSecret>;
    string code = Request.QueryString["code"];
    string.Format("https://www.wrike.com/oauth2/token?client_id={0}&client_secret={1}&grant_type=authorization_code&code={2}", ClientID, ClientSecret, code);

    if (Request["code"] == null)
    {
        Response.Redirect(string.Format(
            "https://www.wrike.com/oauth2/authorize?client_id={0}&response_type=code",
            ClientID));
    }
    else
    {
        Dictionary<string, string> tokens = new Dictionary<string, string>();

        string url = string.Format("www.wrike.com/oauth2/token?client_id={0}&client_secret={1}&grant_type=authorization_code&code={2}", ClientID, ClientSecret, code);
        HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;

        using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
        {
            StreamReader reader = new StreamReader(response.GetResponseStream());

            string vals = reader.ReadToEnd();

            foreach (string token in vals.Split('&'))
            {
                tokens.Add(token.Substring(0, token.IndexOf("=")),
                    token.Substring(token.IndexOf("=") + 1, token.Length - token.IndexOf("=") - 1));
            }
        }

        string access_token = tokens["access_token"];

    }

}
Community
  • 1
  • 1
Mark
  • 768
  • 3
  • 8
  • 26
  • 1
    Why are you expecting `jsonp` without specifing a callback? I will suggest get rid of corssDomain and change dataType to 'json' – Z.Z. May 19 '16 at 19:02
  • I was using [this post](http://stackoverflow.com/questions/6114436/access-control-allow-origin-error-sending-a-jquery-post-to-google-apis) as a reference. And the result of changing jsonp to json and removing crossdomain gave me this error: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:59614' is therefore not allowed access. The response had HTTP status code 400. – Mark May 19 '16 at 19:11
  • 1
    The reason you are having a Cross-domain issue is because you are posting a bad request, and you dont have the correct response header. I suspect there is something wrong with your post data. i recommend you to use [Postman](https://chrome.google.com/webstore/detail/postman/fhbjgbiflinjbdggehcddcbncdddomop?hl=en) to investigate your request before putting it into ajax. – Z.Z. May 19 '16 at 20:27
  • Thanks, I just did that and got this as my response: { "error": "invalid_grant", "error_description": "Authorization code is invalid" } I copied the authorization code from my browser so that might be causing that problem. I don't tink I can get it from postman because it brings me to a login page. – Mark May 19 '16 at 20:45

1 Answers1

2

Okay guys after a lot of time and effort I've found a solution. Rather than getting the access token using ajax and dealing with Cross Origin issues I decided to get the token via the back end C#. You will still need to parse the token var for the access token but that's easy to do. For reference the var token contains the information below (Wrike API Oauth2 documentation):

{
   "access_token": "2YotnFZFEjr1zCsicMWpAA",
   "refresh_token": "tGzv3JOkF0XG5Qx2TlKWIA",
   "token_type": "bearer",
   "expires_in": 3600
}

Here is my code:

protected void Page_Load(object sender, EventArgs e)
{
    string ClientID = "<clientID>";
    string ClientSecret = "<ClientSecret>";
    string code = Request.QueryString["code"];
    string.Format("https://www.wrike.com/oauth2/token?client_id={0}&client_secret={1}&grant_type=authorization_code&code={2}", ClientID, ClientSecret, code);

    if (Request["code"] == null)
    {
        Response.Redirect(string.Format(
            "https://www.wrike.com/oauth2/authorize?client_id={0}&response_type=code",
            ClientID));
    }
    else
    {
        string url = string.Format("https://www.wrike.com/oauth2/token?client_id={0}&client_secret={1}&grant_type=authorization_code&code={2}", ClientID, ClientSecret, code);
        HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
        request.Headers.Add("Access-Control-Allow-Origin", "*");
        request.Method = "Post";
        using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
        {
            StreamReader reader = new StreamReader(response.GetResponseStream());

            var token = reader.ReadToEnd();
        }
    }
}

This tutorial helped me out with creating the http request using ASP.Net: Post on Facebook User's wall using ASP.Net C#

Mark
  • 768
  • 3
  • 8
  • 26