Click here to Skip to main content
15,846,211 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
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

What I have tried:

<pre lang="Javascript">// 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);
	}
});
Posted
Updated 7-Oct-23 10:50am
v3

1 solution

So ... you have no idea what you are doing, and no interest in finding out how to do it properly - just throw some code together form internet samples and get someone else to fix it when it doesn't work?

That may be exaggerating what you are actual facing, but it's certainly the impression that your question history gives us. Same subject, same lack of apparent progress or even effort.

The internet has a term for that: "Help Vampire".

Can I suggest that you Google for "How to implement OAuth" and find yourself a good tutorial? Anything security related should not be implemented by the "hope and pray" approach you appear to be using so far ...
 
Share this answer
 
Comments
Jithu_007 7-Oct-23 23:06pm    
I have attempted various solutions to address the "socket hang up" error. I want to clarify that I'm not requesting specific code samples or asking someone to fix the issue for me. I understand the importance of self-learning in this field, and I'm not randomly seeking code snippets to run.

Given my limited computer science knowledge, I may occasionally refer to existing code or ask what might seem like basic questions. It's important for me to emphasize that while others like you may possess extensive expertise, I am still a beginner in this field, and I am sincerely committed to learning and improving.

Please rest assured that I don't simply post code and leave. I am fully dedicated to the learning process and will diligently research and seek assistance until I gain a better understanding of the issue. I anticipate encountering challenges when starting from scratch with minimal knowledge, but it's through such challenges that I intend to learn and grow.

I genuinely appreciate your concern and willingness to help. Your guidance is invaluable to me as I navigate the complexities of this subject matter. Thank you for your support.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900