Axios post request not returning response error - express

I have a login function which returns the user id and jwt token on successful login and different errors like username not found or incorrect password etc. if the data provided is incorrect. I tested the api using postman and it works fine but when i make a request from the front end to the login end point. It returns the credentials if the login attempt is valid but does not respond with and error if the login details are incorrect.
Login code
Currently im only logging the axios response to the console
Axios request

As per my comment above, you need to catch errors from your request.
axios.post("[your url here]")
.then(res=>{
console.log(res);
})
.catch(err=>{
console.log(err);
});

Related

How to handle 401 errors in#microsoft/signalr JavaScript client

We are using the #microsoft/signalr JavaScript client in our Vue frontend to establish a websocket connection with our backend (.net core). Also, we use a Bearer token for authentication.
This is the connection builder in the frontend:
this.connection = new HubConnectionBuilder()
.withUrl('/chat', { accessTokenFactory: () => IdService.getToken() })
.configureLogging(LogLevel.Information)
.withAutomaticReconnect()
.build()
Then I start the connection in this code:
HubService.connection.start().then(() => {
console.log('Connection started')
}).catch(err => {
console.error(err)
})
My problem is, when the Bearer token expires in the backend, on a reconnect I get a 401 error in the frontend, which is correct and I want to respond correctly to this error. I can catch the error in the catch block of the start function but I don't know how to handle the error, because I can't read a status code from the request like in a normal HTTP request. Its just a error message from the signalr client. Of course I could search in the string for '401' but that seems wrong.
Error: Failed to start the connection: Error: Failed to complete negotiation with the server: Error: Unauthorized: Status code '401'
I would like to know where in my code and how to properly handle this type of error and other errors to. Any help or ideas are appreciated.
The correct way to to this is your IdService.getToken() get you a refreshed token when it is almost expires because it's said in the Microsoft documentation that this function is called every time that there is an communication from client to hub.
The access token function you provide is called before every HTTP request made by SignalR. If you need to renew the token in order to keep the connection active (because it may expire during the connection), do so from within this function and return the updated token.
There are many examples for the token providers to refresh the token when it is near expiration.
But if that fix/implementation is out of your reach/control, the only thing you can do is catch the exception and just initialize again the connection. Something like this:
Catch the exception;
Emit an event with 401 unauthorized exception.
Catch the event and just call the method that initializes your connection.
But this is a workaround to the original problem, that is the proper token refresh function.

HTTP GET Jwt Request work with postman but same with axios return 401 Unauthorized

I have a request against an enpoint that need a token
With postman request work fine and answere 200 and looks like that:
Axios has previously done a succesfull login request that gave it to have a valid token
In the login callback methode I allowed axios to produce request with a valid jwt token:
axios.defaults.headers.common['Authorization'] = token
Then axios do a call is done by this line:
axios.get("https://localhost:44336/api/CurrentBet")
But it produces 2 requests: one with answer 204 No Content and another one with answer 401 Unauthorized
the first request is:
the second request is :
Do you have any idea about what happens and how to resolve it?
For jwt , axios should be set with code bellow;
axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;

need to mock POST request in cypress

UPDATED 9/16:
I've reworded my question. I'm trying to use cypress to test a work application that has an Angular frontend(http://localhost:4200) and a .NET Core backend (http://localhost:5000).
When the app starts, a login page loads with username and password fields. The cypress code test fills in the username and password and clicks the submit button, as show in my code below.
When the login (submit) button is clicked, it triggers a POST request to the .NET Core backend. The request submits the username and password and if the user is verified, a token comes back in response. The token is added to session storage and the user is logged in. It is this token value in the session storage that signifies the user is logged in. With the token added, the user gets redirected to the homepage.
Now the backend is NOT running. I need to simulate this POST request so the cypress test can get to the actual homepage.
I think I need to stub this POST request but I can't get this code to work. The request just aborts and looking at the console it says the request was not stubbed.
Here's my updated cypress code:
const username = 'johndoe';
const password = 'pass1234';
cy.server();
cy.get('h1').should('contain', 'Login');
cy.get('input[placeholder=Username]').type(username);
cy.get('input[placeholder=Password]').type(password);
cy.get('button[type=submit]').click();
cy.route({
method: 'POST',
url: 'http://localhost:5000/Authentication/Login',
response: {
access_token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9' // some random characters
}
});
You might have more success if you set up the route before invoking the POST (clicking submit),
cy.server();
cy.route({
method: 'POST',
url: 'http://localhost:5000/Authentication/Login',
response: {
access_token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9' // some random characters
}
});
...
cy.get('button[type=submit]').click();
However, if your app uses native fetch as opposed to XHR, core Cypress does not catch this type of request. You have to add a polyfill which essentially modifies the window.fetch method to allow cy.route() to succeed.
cypress.json
{
"experimentalFetchPolyfill": true
}
Please note the limitations section,
Limitations
The experimental polyfill is not foolproof. It does not work with fetch calls made from WebWorkers or ServiceWorker for example. It might not work for streaming responses and canceled XHRs. That's why we felt the opt-in experimental flag is the best path forward to avoid breaking already application under tests.

axios api authentication headers jwt and security

Two questions here:
I was not able to pass in a post request using axios and authorization headers as such:
axios.post('http://localhost/dashboard', {headers: { 'Authorization': 'JWT xxxxxx' }})
But I was able to get it to work with a preset: axios.defaults.headers.common['Authorization'] = 'JWT xxx'
Am I missing something as to why the headers parameter was sending the "headers" as a data payload instead of as an actual header?
Once I generate a JWT from my login page, on each page request after that I am only showing the page if the response.status is 200. Is this the correct way to redirect someone back to a login page if their jwt is fake or invalid for accessing the page?
The flow is:
/login for user to get JWT
immediately directed to /dashboard but before they are an api call is made to /dashboard using the JWT and if status code is 200, then the /dashboard page is shown. Is this correct or should I be implementing something more than just a 200 code?
Am I missing something as to why the headers parameter was sending the "headers" as a data payload instead of as an actual header?
Because you're passing the headers as the data payload. I suggest reading the axios docs for axios.post()
It's common to automatically refresh the JWT instead of logging the user out. Depends on your security requirements. For ex., if you were a bank, it's better to log the user out than to auto refresh the JWT.
Instead of checking for 200, check if the status is 403 (or whatever status your backend returns for an invalid JWT). If your backend errors (500), or receives a bad request (400), it's not relevant to an invalid JWT and you'd be logging the user out for nothing.

403 Forbidden Error from google API Javascript client

I am getting 403 Forbidden Error from google API Javascript client. Following is my code:
gapi.load('client', function () {
console.log('gapi.client loaded.');
var discoveryUrl = 'https://sheets.googleapis.com/$discovery/rest?version=v4';
gapi.client.load(discoveryUrl).then(function () {
console.log('gapi.client.sheets loaded.');
gapi.client
.init({
apiKey: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
clientId: '0000000000000-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com',
scope: 'https://www.googleapis.com/auth/spreadsheets',
})
.then(function () {
return gapi.client.sheets.spreadsheets.get({
spreadsheetId: spreadsheetId,
});
})
.then(
function (response) {
console.log(response);
},
function (response) {
console.log(response);
},
);
});
});
My application is running in servlet container and oauth2 is handled at server side. If I want to add authToken how can I do it?
You may check in this documentation the reasons why you are getting a 403 Forbidden Error. It indicates that the server understood the request but refuses to authorize it. A server that wishes to make public why the request has been forbidden can describe that reason in the response payload (if any).
If authentication credentials were provided in the request, the server considers them insufficient to grant access. The client SHOULD NOT automatically repeat the request with the same credentials. The client MAY repeat the request with new or different credentials. However, a request might be forbidden for reasons unrelated to the credentials.
If I want to add authToken how can I do it?
Follow this documentation about Authorize Requests. You can identify your application using an OAuth 2.0 token.
You may also check on these related threads:
Getting 403 forbidden when using the Google Sheets API and a service account
Make sure that you grant the service account access to the file.
Getting a 403 - Forbidden for Google Service Account
You will get this error if you are emulating a device within Chrome DevTools.
If you try going through the usual "Sign in with Google" flow, you will see the following error:
Error 403: disallowed_useragent
You can’t sign in from this screen because this app doesn’t comply with
Google’s secure browsers policy. If this app has a website, you can open
a web browser and try signing in from there.
You can let the app developer know that this app doesn’t comply with
Google’s secure browsers policy.
See Google's documentation on this topic.
A workaround is to switch to device emulation only after going through the authorization flows.