Server Side: how to refresh expired tokens? - amazon-cognito

I'm working on a nuxt.js application with amplify providing the backend, more specifically: Cognito for user/identity management and AppSync for the API.
AppSync uses IAM as authorization on the client side and API KEY on the server side.
When the initial request is made to the server, I can parse the tokens included in the cookie and check if they are valid.
If the token is valid, everything is great: I can grab the user from my database and update my Vuex store before the initial page is sent back to the client.
If the token is expired however, I have a problem because the client/browser then receives an initial page where no user is logged in. On the client side, when the web app is initialized, the amplify library "kicks-in", sees the expired tokens and proceeds to automatically refresh them in the background. When I hit refresh, the new tokens are sent to the server and this time, are valid. Not a great experience.
Therefore, my question is how do I refresh the token on the server-side the first time when the parsed token is expired ?
nuxtServerInit(store, context) {
const cookie = context.req.headers.cookie
if (!cookie) { return console.log("no cookie received") }
const parsedCookie = cookieParser.parse(cookie)
var idToken = ""
var refreshToken = ""
var userData: Object | null = null
Object.keys(parsedCookie).forEach((key, index) => {
if (key.includes("idToken")) idToken = parsedCookie[key]
if (key.includes("refreshToken")) refreshToken = parsedCookie[key]
if (key.includes("userData")) userData = JSON.parse(parsedCookie[key])
}
return context.$axios
// validate token against cognito
.get("https://cognito-idp.us-east-1.amazonaws.com/us-east-xxx/.well-known/jwks.json")
.then(res => jwt.verify(idToken, jwkToPem(res.data.keys[0]), { algorithms: ["RS256"] }))
.then(decodedToken => {
// token is valid, proceed to grab user data
var user = { attributes: {} }
;(userData!["UserAttributes"] as Array<any>).forEach(element => {
user.attributes[element.Name] = element.Value
})
const sub = user.attributes["sub"]
return sub
})
.then(sub => {
// fetch user data from API
})
.then(res => {
// update store with user data
})
.catch(e => {
// TODO: CASE WHERE TOKEN IS INVALID OR EXPIRED
// THIS IS WHERE I WOULD NEED TO REFRESH THE TOKEN
console.log("[nuxtServerInit] error", e.message)
})
}

Related

Why isn't NextAuth jwt automatically saved in cookies?

I have two simple authentication callback functions "jwt" and "session" which check if the user object exists and create the session if so.
callbacks: {
jwt: async ({ token, user }) => {
if(user) {
token.id = user.id
}
return token
},
session: ({ session, token }) => {
if(token) {
session.id = token.id
}
return session
},
}
My issue is, and I have been searching a lot to find information concerning this, why isn't this jwt automatically saved to cookies?
I find that my session is created and I am successfully "logged in", however if I look into my local storage there are no jwt cookies saved.
Do I have to manually save the jwt to my cookies in the jwt callback? Or is the jwt cookie not even required in the case of jwt session strategy? I need jwt cookies because from what I've read about middleware most solutions use cookies and decrypt the jwt to see if the user is logged in, instead of checking the getSession() hook.
You might need to to explain your problem in more detail since I canĀ“t really tell what you already implemented and left out for simplicity sake. I hope this helps you anyway:
The steps to add the cookie look roughly like this:
Create / sign a jwt with a npm package like jose or jsonwebtoken
Set the header of your response and add your signed jwt to it; return it to the client
import { SignJWT, jwtVerify, JWTVerifyResult } from "jose";
async function setCookie(response, user: {id: number}) {
const token = await generateJwtToken(user);
response.setHeader("Set-Cookie", [
`user=${token};` +
"expires=" + new Date(new Date().getTime() + 1 * 86409000).toUTCString() + ";"
]);
response.status(200).json({message: "Successfully set cookie"})
}
async function generateJwtToken(user: { id: number }) {
return await new SignJWT({id: user.id})
.setProtectedHeader({ alg: "HS256" })
.setIssuedAt()
.setExpirationTime("24h")
.sign(new TextEncoder().encode(process.env.YOUR_JWT_TOKEN_ENV_VAR));
}
Verify the jwt on further requests with the same package as in 1.
export async function verifyJwt(request) {
const token = request.cookies["yourCustomUser"];
const verified: JWTVerifyResult = await jwtVerify(
token,
new TextEncoder().encode(process.env.YOUR_JWT_TOKEN_ENV_VAR),
);
verified.payload.status = 200;
return verified.payload;
}
In addition to that you might wanna add sameSite=Strict, secure or path=/. For further information you should have a look at developers.mozilla
Also make sure to add error handling for expired Jwts etc.

ExpressJS authorization with JWT - Is this correct?

I have a small ExpressJS server with a login feature. Some pages are secured with self-written authenticate middleware that checks if your Json WebToken is correct.
I read that just one Json WebToken isn't secure enough and that you need a refresh token as well. So I added a Refresh Token. This is all verified on the server.
Now when the token is expired, I check if the user has a refreshToken and if so I create a new token and set it as a cookie. Like this:
const jwt = require('jsonwebtoken');
// Simple array holding the issued refreshTokens
const { refreshTokens } = require('../lib/auth.js');
module.exports.authenticateToken = function(req, res, next) {
const token = req.cookies.token;
const refreshToken = req.cookies.refreshToken;
if(token === null) return res.redirect('/login');
try {
const verified = jwt.verify(token, process.env.TOKEN_SECRET);
if(verified) return next();
} catch(err) {
try {
const refreshInDb = refreshTokens.find(token => token === refreshToken);
const refreshVerified = refreshInDb && jwt.verify(refreshToken, process.env.REFRESHTOKEN_SECRET);
const newToken = jwt.sign({ email: refreshVerified.email }, process.env.TOKEN_SECRET, { expiresIn: 20 });
res.cookie('token', newToken, { maxAge: 900000, httpOnly: true });
return next();
} catch(err) {
return res.redirect('/login');
}
}
};
Now is this code correct & secure enough for a small webapplication? Am I missing stuff? It feels so... easy?
Seems like you are veryfing both tokens at the same endpoint. This approach is wrong.
In your login endpoint, validate the user and password against database. If credentials are correct we respond with an access token and a refresh token
router.post('/login',
asyncWrap(async (req, res, next) => {
const { username, password } = req.body
await validateUser(username, password)
return res.json({
access_token: generateAccessToken(), // expires in 1 hour
refresh_token: generateRefreshToken(), // expires in 1 month
})
})
)
In your authenticated routes, you should validate only the access token (the user should send ONLY this one)
// middleware to validate the access token
export const validateToken = asyncWrap(async (req, res, next) => {
const data = await verifyAccessToken(req.headers.authorization)
req.auth = data
next()
})
If the access token expires, the user should refresh its token. In this endpoint we will validate the refresh token and respond with two new tokens:
router.post('/refresh',
asyncWrap(async (req, res, next) => {
const { refresh_token } = req.body
await verifyRefreshToken(refresh_token)
return res.json({
access_token: generateAccessToken(), // expires in 1 hour
refresh_token: generateRefreshToken(), // expires in 1 month
})
})
)
I read that just one Json WebToken isn't secure enough and that you need a refresh token as well. So I added a Refresh Token. This is all verified on the server.
Using refresh tokens has nothing to do with security of the JWT or access token. Refresh tokens are just a UX feature. They allow you to get new access tokens without asking the user to authorize again. Having a refresh token in your app doesn't automatically make it more secure.
Now when the token is expired, I check if the user has a refreshToken and if so I create a new token and set it as a cookie. Like this:
When implemented this way the refresh token doesn't grant any more security to your application. You could as well keep the access tokens in the db and refresh them when they are expired.
Are you sure that you need JWTs at all? It looks like you're using them as you would use a session based on cookies. It should be simpler to deal with sessions. You are using http-only cookies for your tokens so you already use it pretty much like a session.
Now is this code correct & secure enough for a small webapplication?
Secure enough is a concept that depends on the data that your application has access to. If it's nothing sensitive, and you know that your app can't really be abused by an attacker, then it is fine to have only some basic security in place.

Excessive number of api calls for refresh token

After reading through multiple JWT refresh token tutorials I am still unclear on how the flow of API calls is supposed to work.
Here is my understanding:
1) Client is in posession of access token and refresh token. It submits the access token to api/getCustomerData.
2) Let's say the access token is expired. Server responds with a 401.
3) Client responds to the 401 request with the refresh token to api/token.
4) Server responds with new access token since the refresh token is still valid.
5) Client then makes a new request to api/getCustomerData with the new access token.
My impression is that this is an excessive number of API calls, but I am not seeing any tutorial that clarifies a way to do this more efficiently. As it stands it seems like if I am following this pattern, each API request will look like this:
const getCustomers = async () => {
const config = {
data: body,
withCredentials: true,
method: 'POST' as 'POST',
}
await axios(address + '/api/getCustomerData', config)
.then((response) => {
...
})
.catch((error: any) => {
const response = error.response;
if (response) {
if (response.status === 401) {
if (!failcount){
failcount++;
getCustomers();
}
else {
history.push('/login')
}
}
}
})
}
What you can do is pre-emptively get a new access token using a refresh token shortly before you know the current access token is about to expire, using the token's "exp (expiration time)" claim. That at least removes one API call - the call with the access token that causes a 401.

Express auth middleware not liking the JWT Token it receives from client side React Native AsyncStorage

I'm working on login authentication with a react native app. I have login working as someone logs in for the first time through the login form. At this initial login step, I'm sending my JWT web token to my secure routes in my express server as a string and this works fine. NOTE: I have a middleware setup that my token goes through before my routes will fire completely.
The problem is when the app refreshes it needs to go to my "local storage". My express middleware doesn't like the token I'm pulling from my "local storage (I retrieve it through AsyncStorate.getItem('UserToken'). When I look at the item being stored in the header, it seems like it's the exact item I was sending it at the initial login, but I think it's my middleware on the server that doesn't like the value when it's coming from the " local storage" header. Below is my middlware.js code.
I've tried looking at the JWT value being sent in both scenarios, and it seems like it's the exact item being sent to the server in both situations.
module.exports = function(req, res, next) {
//Get Token from header
const token = req.header('x-auth-token');
// Check if no token
if(!token) {
return res.status(401).json({ msg: 'No token, authorization denied'})
}
//Verify token
try {
var decoded = jwt.verify(token, global.gConfig.jwtSecret);
req.user = decoded.user;
next();
}catch(err){
res.status(401).json({ msg: 'Token is not valid'});
}
}
This is the function I'm using to retrieve the token from AsyncStorage
export const getAsyncStorage = async () => {
try {
// pulling from header to get x-auth-token here
Value = await AsyncStorage.getItem('Usertoken');
//setting x-auth-token here
axios.defaults.headers.common['x-auth-token'] = Value;
} catch (error) {
// Error retrieving data
}
};

AWS-amplify Including the cognito Authorization header in the request

I have create an AWS mobile hub project including the Cognito and Cloud logic. In my API gateway, I set the Cognito user pool for the Authorizers. I use React native as my client side app. How can I add the Authorization header to my API request.
const request = {
body: {
attr: value
}
};
API.post(apiName, path, request)
.then(response => {
// Add your code here
console.log(response);
})
.catch(error => {
console.log(error);
});
};
By default, the API module of aws-amplify will attempt to sig4 sign requests. This is great if your Authorizer type is AWS_IAM.
This is obviously not what you want when using a Cognito User Pool Authorizer. In this case, you need to pass the id_token in the Authorization header, instead of a sig4 signature.
Today, you can indeed pass an Authorization header to amplify, and it will no longer overwrite it with the sig4 signature.
In your case, you just need to add the headers object to your request object. For example:
async function callApi() {
// You may have saved off the JWT somewhere when the user logged in.
// If not, get the token from aws-amplify:
const user = await Auth.currentAuthenticatedUser();
const token = user.signInUserSession.idToken.jwtToken;
const request = {
body: {
attr: "value"
},
headers: {
Authorization: token
}
};
var response = await API.post(apiName, path, request)
.catch(error => {
console.log(error);
});
document.getElementById('output-container').innerHTML = JSON.stringify(response);
}
Tested using aws-amplify 0.4.1.