How to set credentials property in ReactJs fetch by fetch-interceptor - reactjs

I am working on a project in which we have to include cookies for each service call from frontend (ReactJs) due to authentication. However, all our service calls are implemented by fetch API. Because fetch API does not include cookies by default, we have to add the configuration "credentials: 'include'" to where fetch API is used. It is not maintainable to manually do it everywhere in our code, so we decide to use fetch-interceptor plug in. My code looks like
fetchIntercept.register({
request: function (url, config) {
config.credentials = 'include';
return [url, config];
},
...
};
However, all fetch functions stop working after the change. Here is the message we found in Chrome developer console:
Uncaught (in promise) Error: Failed to fetch login user info:
TypeError: Cannot set property 'credentials' of undefined
I searched online about how to set configuration in fetch-interceptor, but few examples are available. Could someone provide us an example how to set configuration correctly? Thanks.

I see this hasn't been answered in 2 years. Hopefully you have solved the problem by now. If not, just ensure there is a config object associated with every fetch call, a simple
{
method: "GET"
}
will do.

Related

Getting changes on the client with db.collection.watch() and NEXTJS backend api

For starters, this is a NEXTJS project. Basically, I'm trying to get a response similar to a get response every time a document is added or changed in the MongoDB database. In testing, I get the intended results using the axios get method but in the console, I keep getting some errors that I don't know how to get rid of since my backend knowledge is slim, to say the least. Also when I deploy to Vercel I do not get the intended results.
This is the backend of the code
if (method === "GET") {
const taskCollection = Orders;
const changeStream = taskCollection.watch();
changeStream.on("change", (change) => {
return res.status(200).json(change);
});
}
And this is the frontend
useEffect(() => {
axios.get("/api/Orders2").then((res) => {
setNewOrder(res.data);
});
setRefershOrders(true);
}, [newOrder]);
The errors:
Upon page initialization :
API resolved without sending a response for /api/Orders2, this may
result in stalled requests.
Upon changes in the MongoDB document
error - uncaughtException: Error [ERR_HTTP_HEADERS_SENT]: Cannot set
headers after they are sent to the client
In the local environment, I get the response I want (despite the errors) but in production, I get no response.
I know why you cannot set headers after they have already been sent but I honestly didn't mind the error as long as everything worked. Have read some articles that I need to implement sockets but since my backend knowledge is slim I'm having troubles with that as well.
Hope someone can help tnx.

Express API with JWT returns "Unauthorized: Invalid Algorithm error"

I've written a simple React app, following the instructions of a slightly out of date tutorial that is meant to display a list of contacts in the sidebar with individual contact data displayed in an index component but only if you have been authenticated by logging into an Auth0 component and have a JSON Web Token kept in local storage. I have confirmed that I am logged in and have the token. Everything up to this point is working fine.
The problem begins when I click on a contact in the sidebar to view that contact's data, which comes down from a pretty basic API set up with Express. I've been using Postman to troubleshoot since the only error I get from app is "401: Unauthorized"
When I hit my endpoint, suppling an Authorization header with "Bearer [JWT_VALUE_HERE]" Postman responds with "UnauthorizedError: invalid algorithm"
The full output
UnauthorizedError: invalid algorithm
at /Users/Arkham/Documents/Web/eldrac/react-auth-server/node_modules/express-jwt/lib/index.js:102:22
at /Users/Arkham/Documents/Web/eldrac/react-auth-server/node_modules/jsonwebtoken/verify.js:27:18
at _combinedTickCallback (internal/process/next_tick.js:95:7)
at process._tickCallback (internal/process/next_tick.js:161:9)
I've done a bit of googling and tweaked my Auth0 client settings, specifically the Algorithm settings but no matter what I set it to (my options are RS256 and HS256), it doesn't seem to make a difference. I'm dying to get past this.
I use Superagent to make my request
getContact: (url) => {
return new Promise((resolve, reject) => {
request
.get(url)
.set('Authorization', 'Bearer ' + AuthStore.getJwt())
.end((err, response) => {
if (err) reject(err);
resolve(JSON.parse(response.text));
})
});
}
Which seems to be working. I have confirmed that the url is correct and that AuthStore.getJwt() are supplying the correct parameters.
Your question does not provide much information necessary to diagnose the issue - First of all, you should be sending a JWT Access token to the API, not your Id Token.
Upfront questions:
Do you have an API defined in the Auth0 Dashboard?
When you authenticate, are you using an audience parameter? It is
likely that the Access Token is using RS256. Remember for an access
token and Resource API, it is the API that controls the algorithm,
not the Client.
What algorithm is your API using to verify the token?
Presumably, the url in your code snippet is something like
http://localhost:3001/myendpoint?
Take your token, and paste it at https://jwt.io to see what the algorithm used is. Compare that with what is being used to verify the token.
Shall update my answer here as you give more information - please use comments section for this answer.

Getting No response from google drive javascript api

I'm using google drive javascript api(v2) in my reactjs project.
And I'm using this function to get files from google drive.
this.getProjectObjects = function(query, callback)
{
var request = gapi.client.drive.files.list({
corpus : 'DEFAULT',
q : query,
fields : 'items(id,description,title,properties)'
});
request.then(function(resp) {
callback(resp.result.items)
}, function(err) {
console.log(err)
});
};
After authenticate the user, I can get the files using this function.
But, when I navigate to other react component, it's no longer working.
There is no response or error, api just hangs.
Silly thing is when I refresh page, it's working. Again if I navigate to other component, it's not working.
I'm using the same query, nothing changed during navigating.
Anyone have any ideas what the issue could be?
Thanks
You may want to check the Chrome devTools to see if you are encountering any problem when switching pages. Also in the documentation - Getting Started:
There are several ways to use the JavaScript client library to make API requests, but they all follow the same basic pattern:
The application loads the JavaScript client library.
The application initializes the library with API key, OAuth client ID, and API Discovery Document(s).
The application sends a request and processes the response.
The following sections show 3 common ways of using the JavaScript client library.
Option 1: Load the API discovery document, then assemble the request.
Option 2: Use gapi.client.request
Option 3: Use CORS
See the sample for code implementation on effectively loading and making API calls.
Hope this helps.

How to debug a script put in module's config?

My AngularJS project is working with an API. This API provides authentication tokens (Oauth): an access_token and a refresh_token.
Everytime an AngularJS request to the API returns a 401 error, it means that the access_token has expired and it needs to be refreshed by sending the refresh_token to a specific URL. To do that, I followed this tutorial.
But this is not working and I don't know why. I would like to debug the function placed into .config(...) but I don't know how to do that. console.log() and $rootScope = ... doesn't work here.
Thanks for your help !
Use your browser's built-in debugger.
Chrome: https://developer.chrome.com/devtools/docs/javascript-debugging
Firefox: https://developer.mozilla.org/en-US/docs/Tools/Debugger
Firebug: http://getfirebug.com/javascript
IE: https://msdn.microsoft.com/en-us/library/gg699336%28v=vs.85%29.aspx

Angularjs doesn't authenticate with Azure Active Directory

I have an angularjs web application that uses Azure Active Directory for authentication.
The Web Api that the application uses, authenicates without any errors.
For client-side authentication I am using adal.js and adal-angular.js.
When i try to visit any page in my app, authentication fails and prints the following messages in the console
The returned id_token is not parseable.
Route change event for:/
Start login at:https://localhost:44308/#
Navigate url:https://login.windows.net/myapp.onmicrosoft.com/oauth2/authorize
Navigate to:https://login.windows.net/myapp.onmicrosoft.com/oauth2/authorize
TypeError: Cannot read property 'data' of undefined
I have followed this tutorial.
Does anyone know what is going on or how can I debug this?
The error was in the adal.js library when the token which didn't decode correctly utf-8 characters.
An updated version of the library with the bug fix will be available soon.
It's tough to answer without seeing a code sample. If you're using promises, you need to handle the case if the promise is rejected. You probably have something like this:
myAuthService.authenticate(...).then(function(data){
//this handles the successful call.
});
What you need to see the error is something like this:
myAuthService.authenticate(...).then(function(data){
//this handles the successful call.
}, function(e){
//this handles the error case
alert('errror. inspect this.arguments');
});
You should post the code that is throwing the error.

Resources