Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract token string from Bearer token?

Tags:

node.js

jwt

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

like image 284
ycshao Avatar asked May 11 '18 04:05

ycshao


People also ask

How do I get access token from Bearer Token?

The API bearer token's properties include an access_token / refresh_token pair and expiration dates. Tokens can be generated in one of two ways: If Active Directory LDAP or a local administrator account is enabled, then send a 'POST /login HTTP/1.1' API request to retrieve the bearer token.

Is a Bearer Token a string?

A Bearer Token is an opaque string, not intended to have any meaning to clients using it. Some servers will issue tokens that are a short string of hexadecimal characters, while others may use structured tokens such as JSON Web Tokens.

Is Bearer Token and JWT same?

In essence, a JSON Web Token (JWT) is a bearer token. It's a particular implementation which has been specified and standardised. JWT in particular uses cryptography to encode a timestamp and some other parameters.


2 Answers

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 } 
like image 117
pedrofb Avatar answered Sep 20 '22 16:09

pedrofb


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

like image 21
Aniketh Saha Avatar answered Sep 17 '22 16:09

Aniketh Saha