'How to extract token string from Bearer token?

For example I have following Bearer JWT in my header, what's a elegant way to extract the token itself? Basically anything after Bearer. Since this could be in other formats, I don't want to assume it always starts with Bearer. I'm using node-jsonwebtoken and I didn't find such method.

Authorization: Bearer eyJhbGciOiJIUzI1NiIXVCJ9...TJVA95OrM7E20RMHrHDcEfxjoYZgeFONFh7HgQ



Solution 1:[1]

You can split with space using

TokenArray = jwttoken.split(" ");

it will store in an array form where the 2nd index ( 1 as first index is 0) TokenArray[1] will be the token and use

Jwt.decode(TokenArray[1])

to decode the token JWT is a token standard which you can use in many ones and one of the most used case of this is for authorization and it can be done in many ways too but the prefered standard way is sending it in a bearer authorisation header You can userefresh_token instead to bearer token but you have to store the token somewhere which will somehow reduced the effeciency of the term stateless token . So the bearer approch is completly stateless and a prefered approach

Solution 2:[2]

For security reasons you should make sure that the Authorization header has the expected content. You simply should not accept a header that does not start with Bearer if you are expecting it ("Bearer" is a recommendation in the RFC, it is not mandatory) ".

if (authHeader.startsWith("Bearer ")){
     token = authHeader.substring(7, authHeader.length);
} else {
   //Error
}

Solution 3:[3]

I wrote a function for extracting the token from the request header or the query. I post it here. Hope it helps someone.

function extractToken (req) {
    if (req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Bearer') {
        return req.headers.authorization.split(' ')[1];
    } else if (req.query && req.query.token) {
        return req.query.token;
    }
    return null;
}

Solution 4:[4]

For typescript, nodejs, import jwt-decode.

import jwtDecode from 'jwt-decode';

    const authHeader = String(req.headers['authorization'] || '');
    if (authHeader.startsWith('Bearer ')) {
      const token = authHeader.substring(7, authHeader.length);
      const payload = jwtDecode(token) as JwtPayload;
    }

JwtPayload is an interface or a class.

export interface JwtPayload {
  id: string;
  username: string;
  email: string;
  role: string;
  expire: number;
}

Solution 5:[5]

Simple utility function which returns token

function getToken(req) {
  if (
    req.headers.authorization &&
    req.headers.authorization.split(" ")[0] === "Bearer"
  ) {
    return req.headers.authorization.split(" ")[1];
  } 
  return null;
}

Then the token can be passed to other methods. For example, verifying the signature.


  const token = getToken(req);

  if (!token) {
    throw new Error("Authorization token is required");
  } 
 jwt.verify(token, secret, function (err, decoded) {
    if (err) {
      throw new Error("Error : " + err);
    }
    console.log(decoded);
  });

Solution 6:[6]

since your authorization header is always preceded with "Bearer " you can use try this :

 String token = authorizationHeader.substring("Bearer ".length);

this would return the rest of the content of Authorization header , i hope this would be helpful.

Solution 7:[7]

if you have get this error spring boot rest aplication you can try this sample:

probably you post your token => "Authorization" :"eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJqYXZhaW51c2UiLCJleHAiOjE1Njc3ODkxOTcsImlhdCI6MTU2Nzc3MTE5N30.PQZQ4q4orAUs-vScyJVguIlVC0BloTbmqz_i7d36Ij9kBZrdAfkyI9iy_8Roh6TaMS8hfzjz-lDUsQnSt1OD4g"

so you add the "Bearer [space]" string your token string sample : "Authorization" :"Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJqYXZhaW51c2UiLCJleHAiOjE1Njc3ODkxOTcsImlhdCI6MTU2Nzc3MTE5N30.PQZQ4q4orAUs-vScyJVguIlVC0BloTbmqz_i7d36Ij9kBZrdAfkyI9iy_8Roh6TaMS8hfzjz-lDUsQnSt1OD4g"

Solution 8:[8]

The most universal solution that I came up with (you can adjust 'needle' according to your needs):

const authHeader = 'Bearer mytokengoeshere OtherThing...';
const needle = 'Bearer ';
const bearerAt = authHeader.indexOf(needle);
const spaceAfterTokenAt = authHeader.indexOf(' ', needle.length);
const token = authHeader.slice(
    bearerAt + needle.length,
    spaceAfterTokenAt > -1 ? spaceAfterTokenAt : authHeader.length
);

You can drop spaceAfterTokenAt logic at all in case if you sure that you authorization header would be just as simple as 'Bearer mytokengoeshere' string.

Solution 9:[9]

You can do something like this in TypeScript which is way cleaner than most of the answers I saw here.

export const parseBearer = (bearer: string) => {
  const [_, token] = bearer.trim().split(" ");
  return token;
};

Basically truncating the bearer string, splitting by space and then getting the element(token) at the index of one.

To handle the token all you will have to do is to verify it using a package such as jsonwebtoken. Final result will look something like this:

import jwt from "jsonwebtoken"

const authorizationHeader = req.headers["Authorization"];
const token = parseBearer(authorizationHeader);

try {
    const decoded = jwt.verify(token, secret);
    return res.json(decoded);
} catch (error: any) {
    return res.status(403).json({ error: "Invalid token" });
}

Solution 10:[10]

//When token is String, i saw that have " before and end of string, so i have to remove " from token as below // Add the Authorization header with the AccessToken.

            token = token.Substring(1, token.Length-2);
                client.DefaultRequestHeaders.Authorization =  new AuthenticationHeaderValue("Bearer", token);
              

Solution 11:[11]

this is my version for safe and clean code for typescript to parse bearer.

        // parse token bearer
        const tokenBearer = req?.headers?.authorization ? (() => {
            const authHeader = <string>req?.headers?.authorization || ``
            const [code,token] = authHeader.trim().split(` `)
            if (code !== `Bearer`)
                return void 0
            else
                return token
        })() : void 0