Linkedin Login API returning Status 500: Internal Server Error - passport.js

been stuck for a while trying to implement LinkedIn Login using the passport framework on nodejs with passport-linkedin-oauth2 strategy.
These are my configurations for the strategy on nodejs
const strategy = new LinkedInStrategy(
{
clientID: LINKEDIN_KEY,
clientSecret: LINKEDIN_SECRET,
callbackURL: BASE_URL + "/auth/linkedin/callback",
scope: ["r_emailaddress", "r_liteprofile"],
},
(
accessToken,
refreshToken,
profile,
done
) => {
process.nextTick(() => {
return done(null, profile);
});
}
)
The callback route defined so:
router.get(
"/auth/linkedin/callback",
passport.authenticate("linkedin",{
successRedirect: "/",
failureRedirect: "/auth/linkedin",
})
);
In the dev environment on http://localhost:3000, this works perfectly fine - image showing redirection success. After a login success, I get redirected to localhost:3000.
In production however, hosted at https://www.(example_website).com, the redirection throws a code 500 internal server error - image showing redirection failure.
I'm lost as to why the issue is happening for the production site. Really appreciate any clues or help to debug this!

Related

Spotify Web Api/Axios/Heroku - POST Request 500 Error

I was running my React project with a node/axios backend in my localhost with no errors. However, since deploying on Heroku, I can't seem to get my Axios POST requests to work, they give the errors seen below.
The useAuth hook, takes in the code okay from the url when the user signs in, pulling it from the url. But it fails to use the useAuth function/request to get an access token, refresh, and expires token on the axios POST request.
In Spotifys dashboard, my heroku urls are in the redirect uris.
Note: I'm hacking my way through debugging this and have little experience in using node/axios. So I may be unaware of things which may seem obvious and doing things which aren't possible - feel free to point them out.
In the client folder, useAuth.js.
# The parameter code is as required in console
console.log(code)
useEffect(() => {
axios.post('https://heroku-url-inserted-here.com/login', {
code,
})
.then(res => {
setAccessToken(res.data.accessToken)
setRefreshToken(res.data.refreshToken)
setExpiresIn(res.data.expiresIn)
window.history.pushState({}, null, '/')
})
.catch((err) => {
console.log("Error in Effect 1: " + err)
console.log(err.response.data)
})
}, [code])
In server.js,
app.post('/login', (req, res) => {
const code = req.body.code;
const spotifyApi = new spotifyWebApi({
redirectUri: process.env.REDIRECT_URI,
clientId: process.env.CLIENT_ID,
clientSecret: process.env.CLIENT_SECRET,
})
spotifyApi.authorizationCodeGrant(code).then(data => {
res.json({
accessToken: data.body.access_token,
refreshToken: data.body.refresh_token,
expiresIn: data.body.expires_in
})
}).catch((err) =>{
console.log(err)
res.sendStatus(400)
})
})
Error in console:
Error in Effect 1: AxiosError: Request failed with status code 500
500 (Internal Server Error)
I'm hoping for the /login post to set and return the three tokens to set State, allowing major functionality to then work as it did when using local host.
ANSWER:
I was using a .env in my localhost testing environment but didn't set any config values within Heroku, as the .env is a part of the .gitignore file. This meant the redirectUri, clientId and clientSecret were all undefined in my server.js.
Configuring vars in Heroku sorted this issue: https://devcenter.heroku.com/articles/config-vars

How to login into Onelogin via custom UI and redirect to a preconfigured APP

We need to be able to login to onelogin and redirect to an APP on clicking a button in our home page. We should also be able to send some custom params. We tried using passport-saml for this but we are getting
The SAMLResponse ID was already processed
Any leads/documentation on how to proceed would be helpful.
Our passport code looks like
passport.use(new SamlStrategy(
{
callbackUrl: '/app/agent-websites/onelogin/callback',
entryPoint: entryPointUrl,
issuer: issuerUrl,
cert: cert,
},
function(profile: any, done: any) {
console.log(profile);
return done(null, profile);
})
);

Authentication using linkedin in a mean stack application

so I've been trying to implement login with linkedin in my application, and I couldn't find anything online that could show me the steps from A to Z
I implemented the backend and the frontend separateley, however, I don't know how to link them together
In the backend, I'm using passportjs
So here's what I've done so far:
FRONTEND
app.component.html
<button click="loginWithLinkedin()">Linkedin</button>
app.component.ts
window.location.href = `https://www.linkedin.com/uas/oauth2/authorization?response_type=code&state=true&client_id=${environment.LINKEDIN_API_KEY}&redirect_uri=${environment.LINKEDIN_REDIRECT_URL}&scope=${environment.LINKEDIN_SCOPE}`;
redirect.component.ts
const linkedInToken = this.route.snapshot.queryParams["code"];
this.http.get('http://localhost:3000/user/auth/linkedin',
{ params: { token: linkedinToken }}).subscribe(res => {
console.log(res);
});
BACKEND
passport.use(new LinkedInStrategy({
clientID: LINKEDIN_CLIENT_ID,
clientSecret: LINKEDIN_CLIENT_SECRET,
callbackURL: "http://127.0.0.1:8000/user/auth/linkedin/callback",
scope: ['r_emailaddress', 'r_basicprofile'],
passReqToCallback: true
},
function (req, accessToken, refreshToken, profile, done) {
req.session.accessToken = accessToken;
process.nextTick(function () {
return done(null, profile);
});
}));
linkedinRouter.route('/auth/linkedin')
.get(passport.authenticate('linkedin', { state: 'SOME STATE' }),
function(req, res){
// The request will be redirected to LinkedIn for authentication, so this
// function will not be called.
});
linkedinRouter.route('/auth/linkedin/callback')
.get( passport.authenticate('linkedin', { failureRedirect: '/' }),
function (req, res) {
return res.send('hello');
});
I don't understand how would passport work and I don't understand how to link backend and frontend.
I don't know if this is the correct way to implement linkedin authentication
If you have any articles that could guide, or if you can correct that would really help, I've been stuck for a couple of days now.
Thank you very much
I apologize if I formulated the question in a bad way or I didn't know how to ask the question. However, I managed to make it work and I wrote a medium article about it.
here's the link:
https://nour-karoui.medium.com/linkedin-authentication-for-a-mean-stack-application-bd8542b2dc7f
I hope it can help somebody out there !

Google OAuth client authorization error on all devices except my local development machine

I am developing a full stack Node.js web application (MERN Stack based) which has a Google OAuth login system. I successfully deployed the application to Heroku and it is working completely fine on my development Windows Laptop. Google's choose account window successfully pops up, I select an account and get redirected back to dashboard (not completed yet but it is successfully logging in a user with all the data successfully getting updated to MongoDB as well. I even checked on different browsers and tried incognito mode too, the OAuth flow is working correctly as it should but the problem is that I tried opening the website on my mobile device and on clicking the login to google button (I'll add the app link at bottom) it says Authorization Error, Error 400: redirect_uri_mismatch. Now I know that my redirect uri should be updated in developer console dashboard but I have triple checked it is what my instructor told me, otherwise why would it work on my local machine as well?? I'm definitely missing something here that the OAuth fails on all devices except my laptop. Any help would be really appreciated.
App link: https://dry-springs-04824.herokuapp.com
Passport.js file:
const GoogleStrategy = require('passport-google-oauth20').Strategy;
const mongoose = require('mongoose');
const keys = require('../config/keys');
const User = mongoose.model('users');
passport.serializeUser((user, done) => {
done(null, user.id);
});
passport.deserializeUser((id, done) => {
User.findById(id).then(user => {
done(null, user);
});
});
passport.use(new GoogleStrategy({
clientID: keys.googleClientID,
clientSecret: keys.googleClientSecret,
callbackURL: '/auth/google/callback',
proxy: true
}, async (accessToken, refreshToken, profile, done) => {
const existingUser = await User.findOne({ googleId: profile.id });
if(existingUser) {
done(null, existingUser);
} else {
const user = await new User({ googleId: profile.id }).save()
done(null, user);
}
})
);
I am still really confused why it works on my local machine, if it has to fail, it should not work anywhere right?
P.S. I am not testing the website on development mode everything is done from the production Heroku hosted app considering the redirect uri mismatch issue.
Thanks again for any help.

access_token not present in the passport-github2 request

I have registered an OAuth App via my Github account. I am basically trying to authorize my node requests(by sending access_token as part of request cookies) so I can access few APIs on another server. Hence I am using the github-passport2 package. I have setup the github strategy etc. & it seems to be all according to the doc. The flow works well too.
My Issue
After logging into Github(authorized) & getting redirected back to my /auth/github/callback, I ideally should be authorized and should have an access_token in the req. But I don't have it! Because of this I am not able to authorize my future requests with an access_token.
Important to note is that, this access_token is automatically attached when the request is initiated from a browser/client(using withCredentials: true parameter). The same access_token via node doesn't seem to be retrievable.
passport.use(new GitHubStrategy({
clientID: GITHUB_CLIENT_ID,
clientSecret: GITHUB_CLIENT_SECRET,
callbackURL: "http://localhost:8080/auth/github/callback",
},
function(accessToken, refreshToken, profile, done) {
// asynchronous verification, for effect...
process.nextTick(function () {
return done(null, profile);
});
}
));
app.get('/auth/github', passport.authenticate('github', { scope: [ 'user:email' ] }), function(req, res){
// The request will be redirected to GitHub for authentication, so this
// function will not be called.
});
app.get('/auth/github/callback', passport.authenticate('github', { failureRedirect: '/login' }), function(req, res) {
console.log(req); // <- This ideally should have the access_token? but doesn't
});
I have struggling for days on this. Any help is much appreciated.

Resources