Utilizing Ajax and ASP.net to enhance security with Oauth2 for Wrike API version 3

Struggling with the Wrike API and accessing the access token using Ajax or ASP.Net for the first time. Following the "Wrike for Developers Documentation", but facing Error 400 (bad request) when trying to obtain the access token.

Here's the code snippet used:

$.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")//from redirect URI
    },
    crossDomain: true,
    dataType: 'jsonp',
    success: function (response) {
        alert(response); // server response
    }
});

Unable to find JavaScript or ASP.net examples, only projects on GitHub for node.js and PHP. Is there something obvious missing or authentication needs to be done server-side using C#?

Cross-origin issues encountered and attempted fixes mentioned below:

$.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
  }
});

No resolution found for CORS issue despite attempts referenced here: CORS on ASP.NET

Tried backend implementation in ASP.net with C# resulting in error 400 bad request. Request works in Postman. Posting the code for review and will update if resolved.

protected void Page_Load(object sender, EventArgs e)
{
    // Code snippet
}

Answer №1

After dedicating a substantial amount of time and effort, I have successfully discovered a solution to the issue at hand. Rather than opting for the complicated route of obtaining the access token through ajax and dealing with Cross Origin problems, I made the decision to retrieve the token via the backend C#. While you will still need to parse the token variable to extract the access token, this process is relatively straightforward. The contents of the token variable are detailed below (Wrike API OAuth2 documentation):

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

Below is the code snippet that outlines my approach:

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();
        }
    }
}

I found guidance on executing HTTP requests in ASP.Net particularly helpful from this tutorial: Post on Facebook User's wall using ASP.Net C#

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to execute functions depending on a list of <li> elements that have been added?

To maintain a neat post, I have minimized everything. My goal is to append items to the dom after removing the last <li> element from the page, added via jQuery. I am using an .each function that utilizes a JSON array to populate an unordered list t ...

The connection remains open and in an error state as it was not closed properly

I have a grid-view that loops through every row, but I encountered the following error: The variable name '@UserId' has already been declared. Variable names must be unique within a query batch or stored procedure. Although I resolved the initi ...

Error: Oops! Looks like the connection was unexpectedly cut off by the server. The Protocol has abruptly ended

I encountered an issue with my Express service where I received the following error after some time: Error: Connection lost: The server closed the connection. at Protocol.end Here is the code snippet: App.js var createError = require('http-errors& ...

What steps should I take to resolve the "Module Not Found" issue that occurs when I use the command "npm start" after setting up a new React project with npm?

Just starting out with React.js and npm and encountered an issue. After using the command: npm create react-app my-test-npm-react-app I waited for the project to be created successfully. However, when I tried running: npm start I received the followin ...

Using a DELETE method to pass an array of integers in the POST body

There seems to be some ambiguity here. I am attempting to send a DELETE request to remove multiple objects identified by their IDs (stored in an array). This is the controller code : [HttpDelete] public void RemoveRoomWithDevices([FromUri]int roo ...

Discovering user activity through rooms within SocketIO

My goal is to trigger an event when a user switches between online and offline status. The challenge arises from the fact that a user may have multiple tabs open, making it ineffective to track their connection status using on('connect') and on(& ...

Ways to retrieve "this" while utilizing a service for handling HTTP response errors

I have a basic notification system in place: @Injectable({ providedIn: 'root', }) export class NotificationService { constructor(private snackBar: MatSnackBar) {} public showNotification(message: string, style: string = 'success' ...

JavaScript Express is serving up a blank JSON response

Hello there, I have a specific function that is supposed to generate an Object which I want to send back to the browser. However, for some unknown reason, the browser is receiving an empty Object without any content inside: { pName: [ ] } Below you ...

issues I encounter while utilizing MeshLambertMaterial

I am currently using MeshLambertMaterial, but I have encountered a problem. Interestingly, when I use my Windows 10 notebook, everything works fine. However, the issue arises when I try to view an example on Three.js. Here are the errors that I have come a ...

Is there a way to export a modified OBJ geometry from a Three.js scene?

Every time I make changes and export my Three.js scene with a SkinnedMesh model, the original imported model gets saved instead of the updated version. Despite rotating bones and adjusting morph targets, the exported model remains unchanged. Even though t ...

Using ng-click to manipulate variables within a list

In my ionic/angular/phonegap app, I have a list of items and I'm attempting to use an action sheet to pass in the variables. However, I am having trouble accessing the variable on the same line as the ng-repeater. Here is the markup: <ion-view vi ...

"Exploring the creation of multidimensional arrays in Arduino - what steps should I

Is there a way to create a multidimensional array in Arduino? I want something like this. C++ var arr = { name: "John", age: "51", children: [ "Sara", "Daniel" ] }; or maybe like this. JSON ...

Ways to increase the size of an element within an array using JavaScript

I am currently working on expanding an array in JavaScript. Here is the object below const items = [ { id: 1, name: 'Alice', designs: [ { designId: 1, designName: "designA" ...

Embracing Autosuggestion with Flask API

I am currently developing a Flask API for movie recommendations. I have a dataset and I want to implement an auto-suggestion feature where users will get movie suggestions related to the words they type. Here is a snippet from my app.py file: from flask i ...

Employing chained async/await function executions

I am currently troubleshooting a straightforward code. The problem lies within an async function I've created: async function updateResult(event){ let result = db.fetchResult(event.ProcessId); return result; } This function is being called from ...

Diving into Angular2 template forms: unraveling the mysteries of the reset function

After going through the template forms tutorial in Angular2, I'm facing a bit of confusion regarding the behavior of the native reset JavaScript function on Angular2 ngModel. While it's not explicitly clarified in the official documentation, my u ...

What is the best approach to implement this kind of URL in ASP.Net MVC2?

In my database, I have a table named Categories. I would like the user to be able to select a category from a list, and then see a list of all Auctions within that selected category. Seems pretty straightforward, right? One option could be to create a se ...

What sorcery transforms an integer + string into a string?

Recently, I discovered an unconventional method for implementing ToString() and now I'm curious about its workings: public string tostr(int n) { string s = ""; foreach (char c in n-- + "") { //<------HOW IS THIS POSSIBLE ? s = s ...

Add a click event listener to the body element using a button click, without causing it to trigger

What is the current situation: A button is clicked by the user The menu opens (list items display = block) The function to close the menu is connected to the <body> The function to close the menu is immediately triggered, causing the menu to close ...

Integrating image transitions into JavaScript

Could you provide guidance on how to create buttons from the three images within the "fadein" div in order to navigate directly to a specific jpeg? Currently, the three jpgs are displayed in a continuous loop. Thank you. ...