How to create Oauth2 with graphql - node.js

I am using feathers server and I want to implement Oauth2 authentification with facebook or github strategy or whatever. But I also would like to use with graphql
But I dont know how to implement with graphql I'm using https://github.com/feathersjs/feathers-authentication-oauth2 it works as a API if I send GET request on callback url it works correctly I get token but I'd like do this with graphql as for example in LOCAL or LDAP strategy
const authentication = feathers()
authentication.configure(hooks())
.configure(rest(base).superagent(superagent))
.configure(auth({ storage: localStorage }));
RootMutation: {
signInLocal(root, {email, password}, context){
return authentication.authenticate({
strategy: 'local',
email: email,
password: password
}, context).then(data=>{
// console.log(data)
return data
})
},
signInLdap(root, {username, password}, context){
return authentication.authenticate({
strategy: 'ldap',
username: username,
password: password
}, context).then(data=>{
// console.log(data)
return data
})
}
}
I tried
RootQuery: {
signInGithub(root, data, context){
return authentication.authenticate({
strategy: 'github',
}, context).then(data=>{
console.log(data)
return data
})
}
},
But I got error
feathers-authentication:passport:authenticate 'github' authentication redirecting to https://github.com/login/oauth/authorize?response_type=code&redirect_uri=https%3A%2F%2Flocalhost%3A3000%2Fauth%2Fgithub
%2Fcallback&scope=user&client_id=0b786a43497059d2a28b 302 +3ms
feathers-authentication:middleware:failure-redirect Redirecting to https://github.com/login/oauth/authorize?response_type=code&redirect_uri=https%3A%2F%2Flocalhost%3A3000%2Fauth%2Fgithub%2Fcallback&scope=
user&client_id=0b786a43497059d2a28b after failed authentication. +7ms
Error: Unexpected end of JSON input
Thanks for any help

Related

How to get access token in Nodejs using #okta/okta-auth-js signInWithCredentials method

I am new to Okta authentication in nodejs, I've been struggling to get an access token. I am using okta-auth-js's signInWithCredentials.
new OktaAuth({
issuer: OKTA_AUTHORISER_ISSUER_URI,
clientId: OKTA_WEB_APP_CLIENT_ID,
redirectUri: OKTA_REDIRECT_URI,
responseType: "token",
});
await this.authClient.signInWithCredentials({
username: email,
password,
});
But this only gets me a sessionToken. How can I get an access token after this? I think I am missing setting an authState here but I am not sure how to do it.
Thanks
You should use something like that to get back the access token :
await this.authClient.signInWithCredentials({
username: email,
password,
});
this.authClient.isAuthenticated().then(value => {
if (!value) {
console.log('not authenticated');
} else {
authClient.tokenManager.get('accessToken').then(value => {
console.log(value.accessToken);
})
}
})

How to add JWT authentication with passport-steam

Simple JWT authenticated mern app (here) in place using redux and create-react-app. I want to add passport-steam as an authentication method, however I'm not sure how to handle adding a JWT to the passport-steam strategy. Below is what I have:
// Steam
router.get('/steam', passport.authenticate('steam', { session: false }));
router.get(
'/steam/return',
passport.authenticate('steam', { session: false }),
(req, res) => {
const user = req.user
jwt.sign(
{ id: user.id },
'JWT_secret',
{ expiresIn: '2h' },
(err, token) => {
if (err) throw err;
res.json({
user: user,
token,
});
}
);
res.redirect('/')
}
)
Using the default steam strategy It works and user data is added to the DB, but there's no token in local storage. I'm not sure how to do it with steam as I'm not dispatching an action/not sure If I can. Do I need to authenticate via steam, grab and save the data to the database and then dispatch another action to retrieve it and add the JWT, or is there a better method?

Saving JWT token to local storage

I want to save a JWT token into local storage in order to authenticate routes. My code is below but when this route is hit the browser just sits on loading and then says this page isnt working. Removing the localStorage.setItem() makes it work. Im wondering why this is happening. Thanks.
} else {
bcrypt.compare(password, user.password).then(Matched => {
if (Matched) {
//Create the payload for JWT to code
const payload = { id: user.id, name: user.name, email: user.email };
jwt.sign(
payload,
keys.JWT_KEY,
{ expiresIn: 3600 },
(err, token) => {
**localStorage.setItem("token", token);
res.redirect("/");**
}
);
} else {
Because localStorage.setItem("token", token) doesn't exist in nodejs, so the app will crash on this line and res.redirect("/"); is never executed, so the response is never sent back and your browser hangs while waiting for the response.
To fix it, send token back to client using res.json({ token: token }); and run localStorage.setItem("token", token); in the browser.

Get an access token to Linkedin API using email and password

Is it possible to get an access token in order to use node-linkedin package by providing credentials - user email and password? What I'm trying to do is an command line app, that can make an api calls to linkedin and write results in a text file. Thus, I'm not sending any api call results to the client.
I've been trying to do the same thing.
the simple-oauth2 module has a method for logging in via password, but I cannot seem to get it to work.
https://www.npmjs.com/package/simple-oauth2
// Set the configuration settings
const credentials = {
client: {
id: '<client-id>',
secret: '<client-secret>'
},
auth: {
tokenHost: 'https://api.linkedin.com',
authorizePath: 'https://api.linkedin.com/uas/oauth/requestToken',
tokenPath: 'https://api.linkedin.com/uas/oauth/accessToken'
}
};
// Initialize the OAuth2 Library
const oauth2 = require('simple-oauth2').create(credentials);
// Get the access token object.
const tokenConfig = {
username: 'username',
password: 'password'
};
// Callbacks
// Save the access token
oauth2.ownerPassword.getToken(tokenConfig, (error, result) => {
if (error) {
return console.log('Access Token Error', error.message);
}
const token = oauth2.accessToken.create(result);
});
I am not sure these endpoints are correct:
auth: {
tokenHost: 'https://api.linkedin.com',
authorizePath: 'https://api.linkedin.com/uas/oauth/requestToken',
tokenPath: 'https://api.linkedin.com/uas/oauth/accessToken'
}
I get a 400 bad request.

Authentication with hapi-auth-cookie not setting session

I'm trying to set up a simple authentication with Hapijs and its plugin hapi-auth-cookie, but even though the login seems to be successful (right now it's a mock login), when I try to access other endpoints of the API, I'm still getting unauthorized exception.
Here's my server:
server.register([inert, auth], function(err){
server.auth.strategy('base', 'cookie', {
password: 'supersecretpassword', // cookie secret
cookie: 'app-cookie', // Cookie name
ttl: 24 * 60 * 60 * 1000 // Set session to 1 day
});
server.auth.default({
strategy: 'base'
});
server.route(routes.endpoints);
//Start the server
server.start(function () {
console.log('Server running at:', server.info.uri);
});
});
And here are my login and logout functions:
exports.login = {
auth: false,
validate: {
payload: {
email: joi.string().email().required(),
password: joi.string().min(2).max(200).required()
}
},
handler: function(request, reply) {
if(request.payload.email === 'guest#guest.com' && request.payload.password === 'password') {
request.auth.session.set({id: 123, email: 'guest#guest.com'});
return reply('Login Successful');
} else {
return reply(boom.unauthorized('Bad email or password'));
}
}
};
exports.logout = {
auth: false,
handler: function(request, reply) {
request.auth.session.clear();
return reply('Logout Successful!');
}
};
When I hit the login endpoint, it replies with the "Login Successful" message but, as I said, can't access other endpoints that don't have "auth: false" within its config.
Any help will be deeply appreciated.
First check if the cookie is created on the browser. After this try to set the auth object like this:
auth: {mode:'required',strategy:'base'}
Other modes are: try, optional. Set optional if it doesn't matters if user is authenticated or not. Set required to the endpoints you want only to be accessed by authenticated users.
If you want to secure routes by user roles, you will need to set a scope attribute to the user object set on the session:
request.auth.session.set({id: 123, email: 'guest#guest.com', scope:'admin'});
later on the auth object of the routes you set the scopes:
auth: {scope: ['admin']}
also set isSecure: false when you create the strategy. This way the cookie is sent to the client.

Resources