Problem accessing to REST API from devices on same network - node.js

I have a REST API running in my PC and vuejs web app sending request.
When I try the app in localhost, found perfectly.
I can access to home ('/') and using the web app, it send others requests at the API ('/something')
But, i need to try app from my mobile, so I connect both at same network and access to localhost from IP.
I can access to home (IP:port) and the app responde from my mobile.
I can access to others endpoints too (IP:port/something).
Normaly only the app use API endpoints. (Useless for the user to access directly)
The problem is: I'm on home page from my mobile, but at start, the web app send a request to an endpoint. But the server respond 0 to status :(
I try with other PC and same... when i try my app from others devices, the app can't use my API.
Connexion to home: (server.js (API))
MyRouter.route('/')
.all(function(req, res){
res.render('home.ejs');
});
Request sended when user access to home (when Vue mounted): (app.js (Application))
mounted () {
this.$http.get(this.website + '/connexion' ).then(response => {
//succes (I need to get some infos from API)
}, response => {
//error
}
Endpoint: (server.js)
MyRouter.route('/connexion')
.get(function(req,res){
res.json({foo: "bar"}); //some infos
})
From localhost I can get json info but from others device I can access home page but the request to endpoint return request status = 0. When I try to access directly to the endpoint it found ! But I need to still on home page...

Some of the situations that produce this status code:
Illegal cross origin request (see CORS)
Firewall block or filtering
The request itself was cancelled in code
I'd bet it's CORS or firewall problem.

Ok, I find the problem... xD From others device i access to the web app from server IP but the variable 'this.website' used in requests was always "localhost" ! So I replaced that by current URL...

Related

Node.js Express API doesn't send headers if its docker image is deployed

I've built an Node.js Express API where whenever the user uses the (POST) /login, if logged successfully, the api will set the Authorization Token such as this:
#Post('/login')
#UseBefore(validationMiddleware(LoginUserDto, 'body'))
async logIn(#Res() res: Response, #Body() userData: LoginUserDto) {
const { cookie, user } = await this.authService.login(userData);
res.setHeader('Set-Cookie', [cookie]);
return user
}
Whenever I run the docker image locally, if it was requested by a React app it would create the token as a cookie in the browser successfully.
Since it was working, I deployed in docker image of the API in Azure and Digitalocean (in order to see if would work on both. But when I tried to login with the deployed API, it would POST with success but the cookie wouldn't be set in the browser when using the React App (in the app the credentials were set to true in order to save).
I tried to call the deployed API with Postman and Insomnia and both would save the cookie from the successful login.
With this last experiment I was really confused because the API works as expected both in postman and in the react app when run locally, but when deployed only works as expected in postman and not in React. I can't understand if the problem is from react or from the API.
I have also tried using RTK and Axios in react and both got the same results.
In the CORS options from the API the origin is set to "*"
Already found out, seems like when creating the cookie I was not setting the Same-Site property and by default was Lax, which didn't let the browser save the cookie. I set it to none and needed to put secure after it.
public createCookie(tokenData: TokenData): string {
return `Authorization=${tokenData.token}; HttpOnly; Max-Age=${tokenData.expiresIn}; SameSite=None; Secure`;
}

https:/3dspace/F5Health.html log in Azure application insights

I have created one Node.Js application and I am using Azure application insights in it. Code is very simple. I have started app insights on top of app.js
const appInsights = require('applicationinsights');
appInsights.setup('instrument-key-here');
appInsights.defaultClient.commonProperties = {
'appName': 'Name-Of-MS'
};
appInsights.start();
import express from 'express';
I am able to see telemetry data in azure but the problem I deploy the application on the dev server (Linux)...run my application through PM2.. then I am seeing a huge volume of failed request in the portal as well.. approx 100k, 404 requests are being logged and these are not proper HTTP calls. When I detail in the portal all I see is the request URL https:/3dspace/F5Health.html .. that's it.
Below are details, I am seeing in the portal
Event time 1/24/2021, 4:48:53 PM (Local time)
Request name GET /3dspace/F5Health.html
Response code 404
Successful request false
Response time 1 ms
Request URL https:/3dspace/F5Health.html
Request Id 3e5b5c01556b9
Performance <250ms
Telemetry type request
Operation name GET /3dspace/F5Health.html
Operation Id 984d066c7222428c896260ea2e5
Parent Id 984d066c7222428c8962a0ea2e5
Application version 0.0.1
Device type PC
Operating system Linux 3.10.0-1160.6.1.el7.x86_64
Client IP address 0.0.0.0
Cloud role name Web
Cloud role instance servername.com
SDK version node:1.8.9
Sample rate 1
I am sure from where this request is being logged but it is creating a huge volume of 404 requests with the same param.
Anyone faced a similar issue. How Can I find out from where this request is being logged?

/signin-oidc redirect not working openid connect with Keycloak

Note -The issue is in my production app which has SSL installed. I have an ASP.NET Core MVC application deployed on Azure web app.
The authentication is done through Keycloak, using OpenID connect. Below is my Startup.cs code.
AddOpenIdConnect(options =>
{
// URL of the Keycloak server
options.Authority = "{keycloak realm url}";
// Client configured in the Keycloak
options.ClientId = "{clientid}";
// For testing we disable https (should be true for production)
options.RequireHttpsMetadata = true;
options.SaveTokens = true;
options.MetadataAddress = "{keycloak metadata url}"
// Client secret shared with Keycloak
options.ClientSecret = "{clientsecret}"
options.GetClaimsFromUserInfoEndpoint = true;
// OpenID flow to use
options.ResponseType = OpenIdConnectResponseType.CodeIdToken;
});
Once the authentication is done , Redirect URL https://{webapp}/signin-oidc gives below Error.
Also it says the "CONNECTION TO THIS SITE IS NOT SECURE" when the url is still https.
THE ISSUE IS INTERMITTENT. AT TIMES IT WILL REDIRECT BACK TO THE APPLICATION PROPERLY.
500 ERROR. WEB APP CANNOT HANDLE THIS REQUEST
One Pattern observed
For the first time if i open the application in Incognito mode, user is redirected to the application properly. and for the second time if i open in the normal tab, it will redirect properly. NO ISSUES
For the first time if I open the application in normal tab, it gives error.
Then the subsequent requests in incognito or normal tabs will throw the mentioned error too.
Could it be that the web-app is hosted in Azure has it HTTPS traffic terminated in the cloud infrastructure and then decrypts the traffic and sends it using HTTP to your application.
Meaning that your application only sees HTTP traffic while users on the public internet sees HTTPS traffic?
I think this is the default that HTTPS is terminated in Aure when you use their HTTPS infrastructure.
It was an error in the code . Changed response type from CodeIdToken to IdToken

NodeJS authentication middleware fails after successful login

I have an angular app running on localhost:8000 and a node express api with passport authentication on localhost:3000.
After the user login the server returns a successful response but when I try to call other services it fails on the authentication middleware. It doesn't make sense since the login was successful. The user should be authenticated!
Using postman I was able to call authenticated services successfully, but when I make calls from my angular application it return that the user is not authenticated, even after a successful login.
Authentication middleware:
exports.isAuthenticated = (request, response, next) => {
if (!request.isAuthenticated()) return next(createError(401, 'Você não está autorizado.'));
next();
};
When I move the api to a real domain everything works. I thinks it's something related to the localhost x localhost connection but don't know what. I need both applications running on the same domain since it's a requirement for my Facebook application.
I'm on this problem for weeks, tried different solutions but nothing works. I don't know more what to do!
The request and response settings:

Get Google Plus user access_token in Azure webapp server

I have set up an Azure webapp successfully running Node.JS with Express and added a Google Plus authentication using the built in Azure Google "Authentication / Authorization". The auth process works just fine using SSL and and I am able to get users authenticated.
Now,
I know the auth process is calling https://mysite.azurewebsites.net/.auth/login/google/callback with the user access_token for future API calls but in this case Azure "intercepts" it (instead of what will normally happen - I would get it on my won server).
The question is - Is there any why to get and use this token on the server?
I have tried to add a route to the .auth/login/google/callback and somewho get the code
router.get('/.auth/login/google/callback', function (req, res, next) {
console.log("CALLBACK");
next();
});
to no avail...
The auth info from google+ will be set in request headers. If you list your request headers in a router function like:
res.send(JSON.stringify(req.headers));
You can the auth info are set in the headers with the prefix x-ms-token-google-.
Refer to https://azure.microsoft.com/en-us/documentation/articles/app-service-api-authentication/ for more details.
Meanwhile, you can simply issue a GET to the /.auth/me endpoint on your site for retrieving additional user information as well as any tokens required for graph calls. Refer to https://azure.microsoft.com/en-us/blog/announcing-app-service-authentication-authorization/ for details.

Resources