I am trying to intercept a request from apollo client to apollo server and return either a different typeDef field or an undefined one without the client resulting in an error.
This is to check the users refresh token if there access token is expired, and send a new access token instead of the nomral query they were expecting.
Here is my code:
Server:
const server = new ApolloServer({
typeDefs,
resolvers,
cors: {
origin: "http://localhost:3000",
credentials: true,
},
context: async ({ req, res }) => {
let isAuthenticated = false;
// get the user token from the headers
const authorization = req.get("Authorization");
if (authorization) {
let token = req.headers.authorization.replace(/\(/g, "");
let verifysomething = jwt.verify(
token,
process.env.JWT_SECRET,
(err, decoded) => {
console.log("access decoded");
console.log(decoded);
if (err) {
return err;
}
return decoded;
}
);
if (verifysomething.message == "jwt expired") {
let refreshToken = req.headers.cookie.replace(/^[^=]+=/, "");
let verifyRefresh = jwt.verify(
refreshToken,
process.env.JWT_SECRET,
(err, decoded) => {
if (err) return err;
const accessToken = jwt.sign(
{ userId: decoded.userId },
process.env.JWT_SECRET,
{
expiresIn: "20s",
}
);
isAuthenticated = "newAccess";
return accessToken;
}
);
//end return if now access token but has refresh token
return { isAuthenticated, res, verifyRefresh };
}
let user = await User.findOne({ _id: verifysomething.userId });
if (user) {
isAuthenticated = true;
return {
isAuthenticated,
user,
};
}
}
return { isAuthenticated, res };
},
});
Resolvers:
const resolvers = {
Query: {
getCartItems: authenticate(
async (_, { id }) =>
await cartItem.find({ user: id }).populate("user").populate("item")
),
}}
Authenticate:
function authenticate(resolver) {
return function (root, args, context, info) {
if (context.isAuthenticated == true) {
return resolver(root, args, context, info);
}
else if ((isAuthenticated = "newAccess")) {
return context.verifyRefresh;
}
throw new Error(`Access Denied!`);
};
}
To clarify, the issue is that a request going to getCartItems will be expecting a retun like:
type CartItemPayload {
item: Item
user: User
}
but if their access token is expired I would like to just send them a new one first instead.
Now one way I thought to solve this was by adding a new mutation query for refresh token and on each request from the client I can decode the access token jwt to see if it is expired and if so then I make a request to the refreshToken mutation instead of the getCartItems query for example, and that way I would be able to get the expected typeDef return and easily control the data I am receiving.
The problem I see with that is this just feels like a problem that is supposed to be solved on the serverside. I am new to apollo and graphql and am not using an express server for middleware nor am I using redux for middleware on the client side and not sure if what I am trying to achieve is possible this way.
I am open to any solutions or suggestions for this problem, thanks.
Related
I have function that just send data to database (my posts). I use private and public keys to sign and verify tokens. I can send this token in header from front-end to back-end, but has problem with verifying it. Here is how this flow looks like:
Front-end
router.post(`/p-p`, async (req, res) => {
try {
const data = await api.post(`/post-post`, req.body, {
headers: {
Authorization: 'Bearer ' + req.body.token
}
})
res.json(data.data)
} catch (e) {
res.status(e.response.status).json(e.response.data)
}
})
Back-end
router.post(
"/post-post",
auth,
wrapAsync(generalController.postPost)
)
Middleware auth
const jwtService = require('./../services/jwtService')
module.exports = async(req, res, next) => {
if (req.headers.authorization) {
const user = await jwtService.getUser(req.headers.authorization.split(' ')[1])
if (user) {
next();
} else {
res.status(401).json({
error: 'Unauthorized'
})
}
} else {
res.status(401).json({
error: 'Unauthorized'
})
}
}
And JWT service
const jwt = require('jsonwebtoken');
const fs = require("fs");
const path = require("path");
const pathToKeys = path.resolve(__dirname, "../../keys");
module.exports = {
sign(payload) {
const cert = fs.readFileSync(`${pathToKeys}/private.pem`);
return jwt.sign(
payload,
{
key: cert,
passphrase: process.env.JWT_PASSPHRASE
},
{
algorithm: "RS256",
expiresIn: "30m"
}
)
},
getUserPromise(token) {
return new Promise((resolve, reject) => {
jwt.verify(token, fs.readFileSync(`${pathToKeys}/public.pem`), (err, decoded) => {
if(!err) {
return resolve(decoded);
} else {
return reject(err);
}
})
})
},
async getUser (token) {
return await this.getUserPromise(token)
}
}
The problem starts after getUserPromise function. This function can get a token, but can't verify it and I have this problem:
UnhandledPromiseRejectionWarning: JsonWebTokenError: jwt malformed
Actually, I have no idea where problem is. I generated key pair, and sign function can sing and return token, which looks like this: 351e38a4bbc517b1c81e180479a221d404c724107988852c7768d813dd0510e6183306b1d837091b2cddaa07f2427b7a
So, what's the problem?
I have found the solution of this problem and it feels shame. In JWT service pay attention to this string:
algorithm: "RS256"
As you can see I use RS256, but I generated certificates in other format, so, because of this I got that error.
So, if you use RSA certificates, pay attention to algorithm!
EDIT:
Here is how you can generate pair for RS256:
Private
openssl genrsa -out private.pem -aes256 4096
Public from private
openssl rsa -in private.pem -pubout > public.pem
I want to protect my routes by adding a middleware 'checkAuth'.
This middleware checks the validity of a jwt token.
I'm using Express router.
But I don't understand how to do that.
My checkAuth middleware :
module.exports = (req, res, next) => {
let token = req.headers.authorization.split(" ")[1];
try {
jwt.verify(token)
console.log("ok")
}catch (e) {
res.status(403)
}
next();
}
Thank you !
Assuming you are using jsonwebtoken, you are missing the "secret" string.
According the documentation that's how you should do.
when creating token:
var jwt = require('jsonwebtoken');
var token = jwt.sign({ foo: 'bar' }, 'shhhhh');
You could also pass expiration time:
jwt.sign({
data: 'foobar'
}, 'secret', { expiresIn: 60 * 60 });
for validating:
There a couple of ways you could do it.
But you should need the same secret string to validate that you used for signing in.
Also you need to assign a variable to jwt.verify or call it with a callback in order to access the decoded data, such as user Id and so on.
// verify a token symmetric - synchronous
var decoded = jwt.verify(token, 'shhhhh');
console.log(decoded.foo) // bar
// verify a token symmetric
jwt.verify(token, 'shhhhh', function(err, decoded) {
console.log(decoded.foo) // bar
});
// invalid token - synchronous
try {
var decoded = jwt.verify(token, 'wrong-secret');
} catch(err) {
// err
}
// invalid token
jwt.verify(token, 'wrong-secret', function(err, decoded) {
// err
// decoded undefined
});
Create a new function called "verifyToken"
I suggest to promisfy it. So you can use it in an async function in combination with await
function verifyToken(token){
return new Promise((res, err) => {
jwt.verify(token, "secret key", (err) => {
if (err) rej(err)
res(true)
})
})
}
Its promise based. Now you just pass your token to the function it resolves to either true or false:
module.exports = async (req, res, next) => {
let token = req.headers.authorization.split(" ")[1];
try {
await verifyToken(token);
console.log("ok")
}catch (e) {
res.status(403)
}
next();
}
I followed a tutorial to add login and registration to my Node.js app using JWT token and I'm having a hard time logging in and redirecting to my 'logged in' admin page. User registration works great, but the login portion I can't figure out.
This is the tutorial I was following:
https://medium.freecodecamp.org/learn-how-to-handle-authentication-with-node-using-passport-js-4a56ed18e81e
My code for login looks like this:
router.post('/login', auth.optional, (req, res, next) => {
console.log(req.body);
var user = {
email: req.body.email,
password: req.body.password
}
if (!user.email) {
return res.status(422).json({
errors: {
email: 'is required',
},
});
}
if (!user.password) {
return res.status(422).json({
errors: {
password: 'is required',
},
});
}
return passport.authenticate('local', { session: false }, (err, passportUser, info) => {
if (err) {
return next(err);
}
if (passportUser) {
const user = passportUser;
user.token = passportUser.generateJWT();
console.log("TOKEN: " + user.token);
res.setHeader('Authorization', 'Token ' + user.token);
return res.json({ user: user.toAuthJSON() });
}
return res.status(400).json({
errors: {
message: info,
},
});
})(req, res, next);
});
My '/admin' "logged in" route looks like this:
router.get("/admin", auth.required, function(req, res) {
res.render('admin', {
user : req.user // get the user out of session and pass to template
});
});
I'm not sure how I can redirect to my '/admin' route while also passing the token because currently I am seeing the following error after logging in. Makes sense since I am not passing the token to the '/admin' route...but how do I do that? :)
UnauthorizedError: No authorization token was found at middleware
Thanks in advance for the help!
EDIT:
Still can't figure this out and don't really understand how this flow is supposed to work...where do the headers need to be set to the token and how do I redirect to my admin page once the login is successful.
Here is my middleware code if this helps:
const getTokenFromHeaders = (req) => {
console.log("REQ: " + JSON.stringify(req.headers));
const { headers: { authorization } } = req;
if(authorization && authorization.split(' ')[0] === 'Token') {
return authorization.split(' ')[1];
}
return null;
};
const auth = {
required: jwt({
secret: 'secret',
userProperty: 'payload',
getToken: getTokenFromHeaders,
}),
optional: jwt({
secret: 'secret',
userProperty: 'payload',
getToken: getTokenFromHeaders,
credentialsRequired: false,
}),
};
Your code does not have a problem. You seem to be confused with the login flow from server to client (Frontend/Web).
Let's first have a look the RESTFUL way of doing it. The article also refers to the same flow.
The RESTFUL API flow looks like this:
User requests for login:
POST: /api/v1/auth/login with username and password in request body.
If successful, user is returned with basic inforamtion and token.
If not, user is returned a 401 (Unauthorized) status code.
The login flow ends here.
The token provided earlier to the user is used to make subsequent calls to the backend, which a user can use to perform different operations on the sustem. In essence, it is the client which requests server for subsequent actions with the token provided in the login request.
So for your case, user after receiving the token should make a request for retrieving admin information from the backend.
But, I am assuming you are rendering views from your server-side and you want to render the admin view once the user is successfully logged in, and that's pretty straight forward.
Instead of your res.json() after successful login. You need to use res.render().
res.render('admin', {
user: user.toAuthJSON() // assuming your user contains the token already
})
Edit:
Since res.render() does not change the url in the browser. For that, you need to use res.redirect(). But the problem is, you can not send context in res.redirect().
To achieve that, you will need to pass in the user token as query paramter. See here.
TL;DR
// assuming you are using Node v7+
const querystring = require('querystring');
const query = querystring.stringify({
token: user.token,
});
const adminRoute = '/admin?' + query;
res.redirect(adminRoute)
And in your admin route, you need to slightly modify the code.
Verify the token belongs to a real user and get user information out of the token.
Render the admin template with user information retrieved from step 1.
router.get("/admin", function(req, res) {
// verify the token
const token = req.query.token;
const user = null;
jwt.verify(token, 'secret', function (err, decoded) {
if (err) {
res.status(401).send('Unauthorized user')
}
// decoded contains user
user = decoded.user
});
res.render('admin', {
user : user
});
});
I'm somewhat new to this as well, but I've got it working as follows.
In your server.js file:
const passport = require("passport");
const JwtStrategy = require("passport-jwt").Strategy;
const ExtractJwt = require("passport-jwt").ExtractJwt;
app.use(passport.initialize());
const opts = {};
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();
opts.secretOrKey = Keys.secretOrKey;
passport.use(
new JwtStrategy(opts, (jwt_payload, done) => {
// somefunction looks up the id in jwt payload and
// supplies passport the authenticated user via the "Done" function
somefunction.user(jwt_payload.id)
.then(user => {
if (user) {
return done(null, user);
}
return done(null, false);
});
})
);
In your API definitions
const jwt = require("jsonwebtoken");
router.post("/login", (req, res) => {
const { userInfo } = req.body;
// userInfo has username and password in it
// anotherFuction validates the user id and password combo
anotherFunction(userInfo.id, userInfo.password)
.then(isAuthenticated => {
if (isAuthenticated) {
const payload = {
id: user.sAMAccountName,
firstname: user.givenName,
lastname: user.sn
};
// Sign Token with the payload
jwt.sign(
payload,
Keys.secretOrKey,
{ expiresIn: 3600 },
(err, token) => {
res.json({
success: true,
token: "Bearer " + token
});
}
);
} else {
// don't mind the statuses ^_^'
return res.status(401).json({ error: "Login failed." });
}
})
.catch(err => {
return res.status(400).json(err);
});
});
After calling the API you want to set the auth token. The following lets you delete the token if nothing is passed in, effectively "Logging out".
const setAuthToken = token => {
if (token) {
// Apply to every request
axios.defaults.headers.common["Authorization"] = token;
} else {
// Delete Auth Header
delete axios.defaults.headers.common["Authorization"];
}
};
If you're trying to use it in the front end, you need to use jwt_decode to pull the values from the token and set it however you deem necessary. If using redux to store login data it should look something like this. As I feel that the discussion of using localstorage for jwtToken is outside of the scope of this, just know would need to check for the token.
if (localStorage.jwtToken) {
setAuthToken(localStorage.jwtToken);
const decoded = jwt_decode(localStorage.jwtToken);
store.dispatch({
type: USER_LOGIN,
payload: decoded
});
}
Hope this helped.
From one beginner in JWT to another. Good luck.
I'm not a pro in any way but I've started and ApolloServer/Express backend to host a site where I will have public parts and private parts for members. I am generating at JWT token in the login mutation and get's it delivered to the client.
With context I want to check if the token is set or not and based on this handle what GraphQL queries are allowed. My Express/Apollo server looks like this at the moment.
const server = new ApolloServer({
typeDefs,
resolvers,
context: async ({ req }) => {
// get the user token from the headers
const token = (await req.headers.authorization) || '';
if (token) {
member = await getMember(token);
}
}
});
The problem is that this locks down the GraphQL API from any queries and I want/need to reach signup/login mutations for example.
Could anyone spread some light on this to help me understand what I need to do to get this to work.
the way i am doing it is that i will construct auth middleware even before graphql server as sometimes is needed to have information about authenticated user also in other middlewares not just GraphQL schema. Will add some codes, that you need to get it done
const auth = (req, res, next) => {
if (typeof req.headers.authorization !== 'string') {
return next();
}
const header = req.headers.authorization;
const token = header.replace('Bearer ', '');
try {
const jwtData = jwt.verify(token, JWT_SECRET);
if (jwtData && jwtData.user) {
req.user = jwtData.user;
} else {
console.log('Token was not authorized');
}
} catch (err) {
console.log('Invalid token');
}
return next();
};
This way i am injecting the user into each request if the right token is set. Then in apollo server 2 you can do it as follows.
const initGraphQLserver = () => {
const graphQLConfig = {
context: ({ req, res }) => ({
user: req.user,
}),
rootValue: {},
schema,
};
const apolloServer = new ApolloServer(graphQLConfig);
return apolloServer;
};
This function will initiate ApolloServer and you will apply this middleware in the right place. We need to have auth middleware before applyin apollo server 2
app.use(auth);
initGraphQLserver().applyMiddleware({ app });
assuming the app is
const app = express();
Now you will have user from user jwtData injected into context for each resolver as "user", or in req.user in other middlewares and you can use it for example like this. This is me query for saying which user is authenticated or not
me: {
type: User,
resolve: async (source, args, ctx) => {
const id = get(ctx, 'user.id');
if (!id) return null;
const oneUser = await getOneUser({}, { id, isActive: true });
return oneUser;
},
},
I hope that everything make sense even with fractionized code. Feel free to ask any more questions. There is definitely more complex auth, but this basic example is usually enough for simple app.
Best David
In every request I send token, and check it in express middleware
app.use(async (req, res, next) => {
const authorization = req.headers.authorization;
let token = null;
let user;
if (authorization) {
try {
token = jwt.verify(authorization, config.secret);
} catch (e) {
// dont work
throw new GraphQLError({ message: 'token damaged' });
}
if (token) {
const { _id } = token;
user = await User.findOne({ _id });
}
if (user) {
req.user = user;
}
}
next();
});
Token can be damaged, and I do the check:
try {
token = jwt.verify(authorization, config.secret);
} catch (e) {
throw new GraphQLError({ message: 'token damaged' });
}
So I need to send to client application Express Error, but it dont work, as expected,
are there any options to create graphql middlewares which take request arguments before calling every resolver? Now if I want throw error of damaged token I need write check in every resolver?
You can simply respond and return, without calling the next middleware:
try {
token = jwt.verify(authorization, config.secret);
} catch (e) {
res.statusCode = 401;
return res.end('{"errors": [{"message": "token damaged"}]}');
}