Java Web Tokens

From bibbleWiki
Jump to navigation Jump to search

Introduction

Java Web Tokens are used for Authorisation and Information Exchange. They consist of three parts, a header, Payload and a Signature. For example

Format

Header

{
  "alg": "HS256",
  "typ": "JWT"
}

Payload

{
  "sub": "1234567890",
  "name": "John Doe",
  "admin": true
}

Signature

HMACSHA256(
  base64UrlEncode(header) + "." +
  base64UrlEncode(payload),
  secret)

Example

Refresh Tokens

When the use authenticates they are provided with an access token. The user can then request a new access token with a refresh token. The access token typically has a much shorter lifespan.
The key question when working on this was where to store the refresh token. After all it enables you to get an access token. In the NodeJS example I use HttpOnly cookie which seemed to be ok. https://owasp.org/www-community/HttpOnly

NodeJS Example

This is not production code and should not be used as such

End Points

Login

Here is the code for logging in. The use is stored in an array. The access token and refresh token are created.

// Login user 
server.post('/login', async (req,res) => {

    const {email, password} = req.body

    try {

        // Check if user exists
        const user = fakeDB.find(user => user.email === email) 
        if(!user) throw new Error('User does not exists')

        const valid = await compare(password, user.password)
        if(!valid) throw new Error('Password or user incorrect')

        // Create Access and Refresh token
        const accessToken = createAccessToken(user.id)
        const refreshAccessToken = createRefreshAccessToken(user.id)

        // Puts the refresh access token in database
        user.refreshAccessToken = refreshAccessToken
        console.log(fakeDB)

        // Sends refresh access token as a cookie
        // Sends access token in header
        sendRefreshAccessToken(res,refreshAccessToken)
        sendAccessToken(req,res,accessToken)

    }
    catch(exp) {
        res.send({error: exp.message})
    }
})

Logout

The cookie is cleared

server.post('/logout', async (req,res) => {
    res.clearCookie('refreshtoken',{ path: '/refresh_token'})
    return res.send(
        {
            'message': 'User has logged out',
        })
})