Sujeet Raman

Sujeet Raman

  • 805
  • 915
  • 334.4k

Nodejs request for oauth2 token produce error 'socket hang up'

Oct 7 2023 7:48 PM

I am currently working on implementing OAuth 2.0 in my React application for user authorization and node js back end for api calling as a proxy server to call auth provider.After a successful login on the authorization server's page,inside the redirect URL specified in my configuration in nodde js  is not generating token and i am getting error socket hang up.Could anyone please help me identify the issue and provide proper guidance on how to resolve it? error happening inside /login

// Function to validate the access token
const validateAccessToken = async (accessToken) => {
	try {
		// Make a request to the authorization server or resource server to validate the token
		const validationResponse = await axios.get(`${config.BASE_URL}${config.INTROSPECTION_URL}`, {
			headers: {
				Authorization: `Bearer ${accessToken}`
			}
		});

		// Check if the validation response indicates that the token is valid
		if (validationResponse.data && validationResponse.data.active === true) {
			return true; // Token is valid
		} else {
			return false; // Token is not valid
		}
	} catch (error) {
		// Handle any errors that occur during the validation process
		console.error('Error validating access token:', error);
		return false; // Assume token is not valid in case of errors
	}
};

// Function to request an access token
const getAccessToken = async (authCode, state) => {
	const accessTokenParams = {
		client_id: config.CLIENT_ID,
		client_secret: config.CLIENT_SECRET,
		code: authCode,
		redirect_uri: config.REDIRECT_URI,
		state,
		grant_type: 'authorization_code'
	};

	try {
		const response = await axios.post(`${config.BASE_URL}${config.TOKEN_URL}`, accessTokenParams);
		return response;
	} catch (error) {
		throw error;
	}
};

// Route to handle the redirect URL after authentication
app.get('/login', async (req, res) => {
	logger.info('Inside redirect URL /login');
	const state = req.query.state;
	const code = req.query.code;

	try {
		// Request an access token using the authorization code
		const accessTokenResponse = await getAccessToken(code, state);

		if (accessTokenResponse.data.access_token) {
			const isAccessTokenValid = await validateAccessToken(accessTokenResponse.data.access_token);

			if (isAccessTokenValid) {
				req.session.token = accessTokenResponse.data.access_token;

				// Redirect to /dashboard after successful login
				res.redirect('/dashboard');
			} else {
				res.status(401).send('Unauthorized');
			}
		} else {
			res.status(401).send('Unauthorized');
		}
	} catch (error) {
		logger.error('Error during login:', error);
		res.status(500).send(error.message);
	}
});

Answers (6)