Giter Club home page Giter Club logo

jwt-decode's Introduction

Browser library that helps decoding JWT tokens which are Base64Url encoded

IMPORTANT: This library doesn't validate the token, any well-formed JWT can be decoded. You should validate the token in your server-side logic by using something like express-jwt, koa-jwt, Microsoft.AspNetCore.Authentication.JwtBearer, etc.

Release Downloads License CircleCI

📚 Documentation - 🚀 Getting Started - 💬 Feedback

Documentation

  • Docs site - explore our docs site and learn more about Auth0.

Getting started

Installation

Install with NPM or Yarn.

Run npm install jwt-decode or yarn add jwt-decode to install the library.

Usage

import { jwtDecode } from "jwt-decode";

const token = "eyJ0eXAiO.../// jwt token";
const decoded = jwtDecode(token);

console.log(decoded);

/* prints:
 * { 
 *   foo: "bar",
 *   exp: 1393286893,
 *   iat: 1393268893  
 * }
 */

// decode header by passing in options (useful for when you need `kid` to verify a JWT):
const decodedHeader = jwtDecode(token, { header: true });
console.log(decodedHeader);

/* prints:
 * { 
 *   typ: "JWT",
 *   alg: "HS256" 
 * }
 */

Note: A falsy or malformed token will throw an InvalidTokenError error; see below for more information on specific errors.

Polyfilling atob

This library relies on atob(), which is a global function available on all modern browsers as well as every supported node environment.

In order to use jwt-decode in an environment that has no access to atob() (e.g. React Native), ensure to provide the corresponding polyfill in your application by using core-js/stable/atob:

import "core-js/stable/atob";

Alternatively, you can also use base-64 and polyfill global.atob yourself:

import { decode } from "base-64";
global.atob = decode;

Errors

This library works with valid JSON web tokens. The basic format of these token is

[part1].[part2].[part3]

All parts are supposed to be valid base64 (url) encoded json. Depending on the { header: <option> } option it will decode part 1 (only if header: true is specified) or part 2 (default)

Not adhering to the format will result in a InvalidTokenError with one of the following messages:

  • Invalid token specified: must be a string => the token passed was not a string, this library only works on strings.
  • Invalid token specified: missing part # => this probably means you are missing a dot (.) in the token
  • Invalid token specified: invalid base64 for part # => the part could not be base64 decoded (the message should contain the error the base64 decoder gave)
  • Invalid token specified: invalid json for part # => the part was correctly base64 decoded, however, the decoded value was not valid JSON (the message should contain the error the JSON parser gave)

Use with TypeScript

The return type of the jwtDecode function is determined by the header property of the object passed as the second argument. If omitted (or set to false), it'll use JwtPayload, when true it will use JwtHeader. If needed, you can specify what the expected return type should be by passing a type argument to the jwtDecode function.

You can extend both JwtHeader and JwtPayload to include non-standard claims or properties.

import { jwtDecode } from "jwt-decode";

const token = "eyJhsw5c";
const decoded = jwtDecode<JwtPayload>(token); // Returns with the JwtPayload type

Use as a CommonJS package

const { jwtDecode } = require('jwt-decode');
...

Include with a script tag

Copy the file jwt-decode.js from the root of the build/esm folder to your project somewhere, then import jwtDecode from it inside a script tag that's marked with type="module":

<script type="module">
  import { jwtDecode } from "/path/to/jwt-decode.js";

  const token = "eyJhsw5c";
  const decoded = jwtDecode(token);
</script>

Feedback

Contributing

We appreciate feedback and contribution to this repo! Before you get started, please see the following:

Raise an issue

To provide feedback or report a bug, please raise an issue on our issue tracker.

Vulnerability Reporting

Please do not report security vulnerabilities on the public GitHub issue tracker. The Responsible Disclosure Program details the procedure for disclosing security issues.


Auth0 Logo

Auth0 is an easy to implement, adaptable authentication and authorization platform. To learn more checkout Why Auth0?

This project is licensed under the MIT license. See the LICENSE file for more info.

jwt-decode's People

Contributors

ategart avatar cristobal avatar damieng avatar dependabot[bot] avatar evansims avatar fossabot avatar frederikprijck avatar gurbraj avatar ivan-st avatar jfromaniello avatar jonkoops avatar joshcanhelp avatar kkirsche avatar lbalmaceda avatar ls-sn avatar mattkrick avatar mkazlauskas avatar ntotten avatar okko avatar remcohaszing avatar sambego avatar sdoxsee avatar stevehobbsdev avatar tlvince avatar tschaub avatar vvakame avatar widcket avatar xmlmxmlmx avatar zackharley avatar zeh avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

jwt-decode's Issues

Doesn't return anything when not a JWT token

I want to validate if the given string is a JWT or not. So basically I do

if (!jwtDecode(AccessIDv)){
//Show error
}
else{
//Verify
}
  • It throws an object when I have valid JWT but whenever I put a random string it returns nothing hence !jwtDecode(AccessIDv) the loop doesn't work and throws an HTTP 500 error. Please add a return object when string is not JWT

Cannot find module using browserify

I recently worked on 'browserifying' all the things.
So I wanted to use this jwt-decode script from npm.

I used the following syntax global.jwt_decode = require('jwt-decode');
But every time i run gulp it fails Error: Cannot find module 'jwt-decode' from '{{path_to_my_file}}'

I have googled the complete day now and I couldn't find a solution for the problem.

What I already tested:

  • Ran npm install --save-dev jwt-decode multiple times.
  • Verified that the jwt-decode directory does exist inside the node_modules directory.
  • Tested to select the build file directly using ... require('jwt-decode/build/jwt-deocde')
  • Tested to select the minified build file directly using ... require('jwt-decode/build/jwt-deocde.min')
  • Tested to select the lib file directly using ... require('jwt-decode/lib/index')

I have no idea why this isn't working.
Also on the same setup requiring jQuery works fine.

Add method to verify jwt-token

It will useful to add some method to validate that all three segments of jwt is valid and can be decoded successfully, or additional check can be integrated into the main method, raising error if some of segments not valid

Is it secure to decode the jwt token on client side ?

Query 1:

You decode the jwt-token on client-side on the below example
https://github.com/auth0/angularjs-jwt-authentication-tutorial
Because to decode i need the secret-key and if I put the secret-key on client side it definitely not secure.

Query 2:

Also I am try to copy the jwt-token and open the url on another browser and pasted the jwt-token and wallah ...I got authentication. So if someone can get to my browser and copy that token s/he will get the access.

Update of Testem version

On OS X I've been getting:

grunt test
Running "clean:build" (clean) task
Cleaning build/...OK

....
Running "exec:test-phantom" (exec) task
>> (node:3885) DeprecationWarning: process.EventEmitter is deprecated. Use require('events') instead.

and no outputs.

This can be fixed just by updating Testem deps:

grunt test    

Running "clean:build" (clean) task
Cleaning build/...OK

Running "browserify:dist" (browserify) task
>> Bundle build/jwt-decode.js created.

Running "browserify:dist" (browserify) task
>> Bundle build/jwt-decode.js created.

Running "uglify:min" (uglify) task
File "build/jwt-decode.min.js" created.

Running "exec:test-phantom" (exec) task
ok 1 PhantomJS 2.1 - jwt-decode should fail to construct without a clientID
ok 2 PhantomJS 2.1 - jwt-decode should return header information
ok 3 PhantomJS 2.1 - jwt-decode should work with utf8 tokens
ok 4 PhantomJS 2.1 - jwt-decode should work with binary tokens

1..4
# tests 4
# pass  4
# skip  0
# fail  0

# ok

Done, without errors.
diff --git a/package.json b/package.json
index 050f0d7..03d6167 100644
--- a/package.json
+++ b/package.json
@@ -31,7 +31,7 @@
     "grunt-s3": "~0.2.0-alpha.3",
     "mocha": "~1.13.0",
     "rimraf": "~2.2.2",
-    "testem": "~0.5.8",
+    "testem": "~1.14.3",
     "uglify-js": "~2.4.0"
   }
 }

Is it OK to go with PR? (note the change in semver is major one).

jwt-decode does not work with requirejs

I have attempted:

 require([ 'jwt-decode' ], function(jwt_decode) {
     var token = ...;
     var decoded = jwt_decode(token);
 });

I also attempted without assigning jwt_decode in the function (hoping for the global jwt_decode function to be available).

In both cases, jwt_decode is undefined, although the library is definitely being loaded.

I ended up working around this by just including the library directly before doing anything with requirejs.

Can't install anymore, npm base64 seems to be obsolete now

jwt-decode has it's own dependency to npm base64 -and with latest node.js you can't build the base64 packages anymore. It generates a flood of syntax errors in the base64 package codebase and it seems that this is caused by breaking changes in V8.

Now quite interesting, as stated on the base64 package page (https://github.com/pkrumins/node-base64)

Update: this module may no longer be necessary as nodejs includes its own
base64 encoding/decoding functions.

Is an update of jwt-decode planned somehow? I think best would be to change to native base64 functionality and remove the dependency fully. I didn't knew about those changes and googled around a bit, seems that basic Buffer objects can handle that already pretty well, or do i miss something that would break the current "base64_url_decode" implementation of the jwt-decode package?

http://stackoverflow.com/a/6182519/1214508

what i try for the moment is to create my own common class which tries to replicate the functionality of jwt-decode with basic base64 impl of node.js

Webpack AMD build missing - jwt-decode not working with angular 2

Tried to load jwt-decode in an angular 2 project however it always returns jwt-decode is not a module. Can you please add a webpack build?

install in ng2 cli project with npm install jwt_decode. Then load in module through_

import {jwt_decode} from "jwt_decode";

results in error:

Uncaught Error: Cannot find module "jwt_decode"

For now, I'm using the following script instead:

wt_decode (token) {
  var base64Url = token.split('.')[1];
  var base64 = base64Url.replace('-', '+').replace('_', '/');
  return JSON.parse(window.atob(base64));
};

Importing via Jest/Webpack/Babel doesn't work

I'm using Babel and Webpack, with Jest set up for testing to use Babel too. Both the browser and the specs show this error when I try to use the library:

InvalidTokenError
    at Object.<anonymous> (/Users/matthewgibson/code/prodmin/node_modules/jwt-decode/lib/index.js:9:31)
    at Runtime._execModule (/Users/matthewgibson/code/prodmin/node_modules/jest-runtime/build/index.js:448:13)
    at Runtime.requireModule (/Users/matthewgibson/code/prodmin/node_modules/jest-runtime/build/index.js:265:14)
    at Runtime.requireModuleOrMock (/Users/matthewgibson/code/prodmin/node_modules/jest-runtime/build/index.js:337:19)
    at Object.<anonymous> (/Users/matthewgibson/code/prodmin/src/redux/selectors/authenticationSelectors.js:2:18)

This is line 2 from authenticationSelectors.js:

import jwtDecoder from 'jwt-decode';

It seems that Jest is trying to run the function that is assigned to module.exports when importing it, rather than just pulling it out as-is. The error is because no arguments are supplied, so the token is undefined.

ESM Support

I was looking for ESM support and couldn't get it to work so I rewrote with ESM support (jrgleason#1) I would say using this then using webpack to make an ES5 version in dist would be the right way to go.

QUESTION: Does this work with React-Native

Hi,

This is not an issue but a query. Does JWT-decode work with React-Native? I'm building an app with authentication and this library keeps getting recommended by other developers, but I'm unsure if it works with React-Native.

Would appreciate any input

Thanks,

Alex

Invalid token specified: Cannot read property 'replace' of undefined

I get Invalid token specified: Cannot read property 'replace' of undefined:

Object.<anonymous> ../node_modules/jwt-decode/lib/index.js 9:0
Showing original source content from sourcemap
'use strict';
 var base64_url_decode = require('./base64_url_decode');
 function InvalidTokenError(message) {
  this.message = message;
}
 InvalidTokenError.prototype = new Error();
InvalidTokenError.prototype.name = 'InvalidTokenError';
 
module.exports = function(token, options) {
    if (typeof token !== 'string') {
      throw new InvalidTokenError('Invalid token specified');
    }

Can i get any help ASAP please?!

Discussion: Provide Pipe for Angular

I use this in all my Angular projects, so you might want to include it:

jwtdecode.pipe.ts

import { Pipe, PipeTransform } from "@angular/core";
import * as jwtDecode from "jwt-decode";

@Pipe({ name: "jwtdecode" })
export class JwtDecode implements PipeTransform {
  transform(token: string): any {
    if (!token) return token;
    return jwtDecode(token);
  }
}

app.module

import { JwtDecode } from './pipes/jwtdecode.pipe';

@NgModule({
  declarations: [ JwtDecode, /* ... */ ]
  // ...
})
export class AppModule {
  // ...
}

usage

<pre>{{IdToken | jwtdecode | json}}</pre>
<pre>{{accessToken | jwtdecode | json}}</pre>

Thank you so much!~

I just wanted to express my intense gratitude for this elegant project. It's really helped me in a major project of mine.

Sorry for the out of context, but I have no idea how else to communicate via GitHub.

Feature request: Verify token

I think it would be worth it for this library to provide verification as well as the regular decode functionality. You wouldn't want to do this with symmetric key signing, but it'd work well with asymmetric auth.

I think you could probably pull the verify method from node-jsonwebtoken into this codebase without a lot of fuss. What do you guys think? For my use case, I'll need this and I"ll likely fork the library. I could submit a pull request.

Add package to bower

It looks like this package isn't being found in the bower repositories. Any chance that can be fixed? :)

Broken using require('jwt-decode')

lines 131-132-133-134
const token = this.getJWTFromCookies();
console.log(token);
const jwtDecode = require('jwt-decode');
const decoded = jwtDecode(token);

Traceback:

core.js:1671 ERROR Error: Uncaught (in promise): InvalidTokenError: Invalid token specified: Cannot read property 'replace' of undefined
InvalidTokenError
at Object../node_modules/jwt-decode/lib/index.js (index.js:9)
at webpack_require (bootstrap:76)
at Object../src/app/_services/authentication.service.ts (appointments.service.ts:39)
at webpack_require (bootstrap:76)
at Object../src/app/appointments/update-appointment/update-appointment.component.ts (main.js:11191)
at webpack_require (bootstrap:76)
at Object../src/app/app.module.ts (app.config.ts:8)
at webpack_require (bootstrap:76)
at Object../src/main.ts (environment.ts:8)
at webpack_require (bootstrap:76)
at Object../node_modules/jwt-decode/lib/index.js (index.js:9)
at webpack_require (bootstrap:76)
at Object../src/app/_services/authentication.service.ts (appointments.service.ts:39)
at webpack_require (bootstrap:76)
at Object../src/app/appointments/update-appointment/update-appointment.component.ts (main.js:11191)
at webpack_require (bootstrap:76)
at Object../src/app/app.module.ts (app.config.ts:8)
at webpack_require (bootstrap:76)
at Object../src/main.ts (environment.ts:8)
at webpack_require (bootstrap:76)
at resolvePromise (zone.js:814)
at new ZoneAwarePromise (zone.js:894)
at AuthenticationService.push../src/app/_services/authentication.service.ts.AuthenticationService.resolveRouting (authentication.service.ts:96)
at authentication.service.ts:70
at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke (zone.js:388)
at Object.onInvoke (core.js:3825)
at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke (zone.js:387)
at Zone.push../node_modules/zone.js/dist/zone.js.Zone.run (zone.js:138)
at zone.js:872
at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:421)
defaultErrorLogger @ core.js:1671
push../node_modules/@angular/core/fesm5/core.js.ErrorHandler.handleError @ core.js:1717
next @ core.js:4320
schedulerFn @ core.js:3556
push../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.__tryOrUnsub @ Subscriber.js:195
push../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.next @ Subscriber.js:133
push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber._next @ Subscriber.js:77
push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next @ Subscriber.js:54
push../node_modules/rxjs/_esm5/internal/Subject.js.Subject.next @ Subject.js:47
push../node_modules/@angular/core/fesm5/core.js.EventEmitter.emit @ core.js:3540
(anonymous) @ core.js:3847
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke @ zone.js:388
push../node_modules/zone.js/dist/zone.js.Zone.run @ zone.js:138
push../node_modules/@angular/core/fesm5/core.js.NgZone.runOutsideAngular @ core.js:3784
onHandleError @ core.js:3847
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.handleError @ zone.js:392
push../node_modules/zone.js/dist/zone.js.Zone.runGuarded @ zone.js:154
_loop_1 @ zone.js:677
api.microtaskDrainDone @ zone.js:686
drainMicroTaskQueue @ zone.js:602
push../node_modules/zone.js/dist/zone.js.ZoneTask.invokeTask @ zone.js:500
invokeTask @ zone.js:1540
globalZoneAwareCallback @ zone.js:1566
error (async)
customScheduleGlobal @ zone.js:1666
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.scheduleTask @ zone.js:407
onScheduleTask @ zone.js:297
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.scheduleTask @ zone.js:401
push../node_modules/zone.js/dist/zone.js.Zone.scheduleTask @ zone.js:232
push../node_modules/zone.js/dist/zone.js.Zone.scheduleEventTask @ zone.js:258
(anonymous) @ zone.js:1831
(anonymous) @ http.js:1628
push../node_modules/rxjs/_esm5/internal/Observable.js.Observable._trySubscribe @ Observable.js:42
push../node_modules/rxjs/_esm5/internal/Observable.js.Observable.subscribe @ Observable.js:28
(anonymous) @ subscribeTo.js:21
subscribeToResult @ subscribeToResult.js:6
push../node_modules/rxjs/_esm5/internal/operators/mergeMap.js.MergeMapSubscriber._innerSub @ mergeMap.js:70
push../node_modules/rxjs/_esm5/internal/operators/mergeMap.js.MergeMapSubscriber._tryNext @ mergeMap.js:67
push../node_modules/rxjs/_esm5/internal/operators/mergeMap.js.MergeMapSubscriber._next @ mergeMap.js:50
push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next @ Subscriber.js:54
(anonymous) @ scalar.js:5
push../node_modules/rxjs/_esm5/internal/Observable.js.Observable._trySubscribe @ Observable.js:42
push../node_modules/rxjs/_esm5/internal/Observable.js.Observable.subscribe @ Observable.js:28
push../node_modules/rxjs/_esm5/internal/operators/mergeMap.js.MergeMapOperator.call @ mergeMap.js:28
push../node_modules/rxjs/_esm5/internal/Observable.js.Observable.subscribe @ Observable.js:23
push../node_modules/rxjs/_esm5/internal/operators/filter.js.FilterOperator.call @ filter.js:15
push../node_modules/rxjs/_esm5/internal/Observable.js.Observable.subscribe @ Observable.js:23
push../node_modules/rxjs/_esm5/internal/operators/map.js.MapOperator.call @ map.js:18
push../node_modules/rxjs/_esm5/internal/Observable.js.Observable.subscribe @ Observable.js:23
push../src/app/_services/authentication.service.ts.AuthenticationService.tokenConfiguration @ authentication.service.ts:64
push../src/app/_services/authentication.service.ts.AuthenticationService.login @ authentication.service.ts:59
push../src/app/auth/login/login.component.ts.LoginComponent.onSubmit @ login.component.ts:62
(anonymous) @ LoginComponent.html:9
handleEvent @ core.js:10259
callWithDebugContext @ core.js:11352
debugHandleEvent @ core.js:11055
dispatchEvent @ core.js:7718
(anonymous) @ core.js:9198
schedulerFn @ core.js:3568
push../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.__tryOrUnsub @ Subscriber.js:195
push../node_modules/rxjs/_esm5/internal/Subscriber.js.SafeSubscriber.next @ Subscriber.js:133
push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber._next @ Subscriber.js:77
push../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.next @ Subscriber.js:54
push../node_modules/rxjs/_esm5/internal/Subject.js.Subject.next @ Subject.js:47
push../node_modules/@angular/core/fesm5/core.js.EventEmitter.emit @ core.js:3540
push../node_modules/@angular/forms/fesm5/forms.js.NgForm.onSubmit @ forms.js:3801
(anonymous) @ LoginComponent.html:8
handleEvent @ core.js:10259
callWithDebugContext @ core.js:11352
debugHandleEvent @ core.js:11055
dispatchEvent @ core.js:7718
(anonymous) @ core.js:8162
(anonymous) @ platform-browser.js:995
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask @ zone.js:421
onInvokeTask @ core.js:3816
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask @ zone.js:420
push../node_modules/zone.js/dist/zone.js.Zone.runTask @ zone.js:188
push../node_modules/zone.js/dist/zone.js.ZoneTask.invokeTask @ zone.js:496
invokeTask @ zone.js:1540
globalZoneAwareCallback @ zone.js:1566

This broke yesterday

Can i get any help ASAP please?!

React Native Invalid Token Specified

Hi, I'm struggling with jwt-decode in my react native app, whenever I start expo i get Invalid Token Specified error, what am i missing? Here is my code:

var jwt_decode = require('jwt-decode');
import { AsyncStorage } from 'react-native';
const initialState = {
  user: null
};
if (AsyncStorage.getItem('jwtToken')) {
  const decodedToken = jwt_decode(AsyncStorage.getItem('jwtToken'));

  if (decodedToken.exp * 1000 < Date.now()) {
    AsyncStorage.removeItem('jwtToken');
  } else {
    initialState.user = decodedToken;
  }
}

const AuthContext = createContext({
  user: null,
  login: (userData) => {},
  logout: () => {}
});

function authReducer(state, action) {
  switch (action.type) {
    case 'LOGIN':
      return {
        ...state,
        user: action.payload
      };
    case 'LOGOUT':
      return {
        ...state,
        user: null
      };
    default:
      return state;
  }
}

function AuthProvider(props) {
  const [state, dispatch] = useReducer(authReducer, initialState);

  login = async (userData) => {
    try{
      await AsyncStorage.setItem('jwtToken', userData.token);
      dispatch({
      type: 'LOGIN',
      payload: userData
    });
  } catch(e) {
    // save error
  }
  }

  logout = async () => {
    try{
    await AsyncStorage.removeItem('jwtToken');
    dispatch({ type: 'LOGOUT' });
    } catch(e) {
      // save error
    }
  }

  return (
    <AuthContext.Provider
      value={{ user: state.user, login, logout }}
      {...props}
    />
  );
}

export { AuthContext, AuthProvider };`

can't find variable jwt_decode

I am following your Code as usually ,

Firstly i installed this npm install jwt-decode --save

after that

var logindata = " token"

var token = logindata;
var decoded = jwt_decode(token);
alert(":"+decoded);

getting Error

InvalidTokenError: Invalid token specified

InvalidTokenError
    at Object../node_modules/jwt-decode/lib/index.js (http://localhost:5004/static/js/0.chunk.js:10866:31)
    at __webpack_require__ (http://localhost:5004/static/js/bundle.js:782:30)
    at fn (http://localhost:5004/static/js/bundle.js:150:20)
    at Module../src/actions/authActions.js (http://localhost:5004/static/js/main.chunk.js:3231:68)
    at __webpack_require__ (http://localhost:5004/static/js/bundle.js:782:30)
    at fn (http://localhost:5004/static/js/bundle.js:150:20)
    at Module../src/components/Login/Login.js (http://localhost:5004/static/js/main.chunk.js:6290:78)
    at __webpack_require__ (http://localhost:5004/static/js/bundle.js:782:30)
    at fn (http://localhost:5004/static/js/bundle.js:150:20)
    at Module../src/App.js (http://localhost:5004/static/js/main.chunk.js:135:81)
    at __webpack_require__ (http://localhost:5004/static/js/bundle.js:782:30)
    at fn (http://localhost:5004/static/js/bundle.js:150:20)
    at Module../src/index.js (http://localhost:5004/static/js/main.chunk.js:20498:62)
    at __webpack_require__ (http://localhost:5004/static/js/bundle.js:782:30)
    at fn (http://localhost:5004/static/js/bundle.js:150:20)
    at Object.0 (http://localhost:5004/static/js/main.chunk.js:21412:18)
    at __webpack_require__ (http://localhost:5004/static/js/bundle.js:782:30)
    at checkDeferredModules (http://localhost:5004/static/js/bundle.js:46:23)
    at Array.webpackJsonpCallback [as push] (http://localhost:5004/static/js/bundle.js:33:19)
    at http://localhost:5004/static/js/main.chunk.js:1:57

IE 11: Invalid calling object

I'm seeing a 'Invalid calling object' exception in IE 11 when calling jwtDecode with my token. Other browsers seem to all be working.

It looks like this may be related to not binding window.atob in lib/atob.js when the polyfill isn't used.

Stack:

{exception} :
  description: "Invalid calling object",
  message: "Invalid calling object",
  name: "TypeError",
  number: -2147418113,
  stack "TypeError: Invalid calling object\n   at b64DecodeUnicode (eval code:4:3)\n   at module.exports (eval code:29:5)\n   at module.exports (eval code:10:3)\n   at updateAuthToken (eval code:34:3)\n   at auth (eval code:96:7)\n   at combination (eval code:117:7)\n   at dispatch (eval code:179:7)\n   at Anonymous function (eval code:208:13)\n   at Anonymous function (eval code:14:9)\n   at Anonymous function (eval code:140:9)"

Manual checks via debugger in b64DecodeUnicode:

window.atob('test')
"µë-"
atob('test')
Invalid calling object
atob
function atob() { [native code] }
atob === window.atob
True
var bound_atob = window.atob.bind(window);
undefined
bound_atob('test')
"µë-"

Checking expiration

As far as I could understand, jwt-decode doesn't check if the token expired, does it?
If yes, how can I check if the token expired?
If not, is there any way to do that easily?
Thanks

Token decode error

Some of our users have randomly been getting errors like and Invalid token specified: e is undefined thrown when their token is decoded. The odd thing is, I've checked all of their tokens and they all look fine. Does anybody know where I should start looking to figure out what the issue might be here?

For what it's worth, I'm logging out the token before I run it through jwt_decode() and all of our logs get recorded so I know that the token is there and that it's a valid token. Also, I think this has only ever come up in Firefox.

No GZIP support?

It appears this package doesn't support GZIP support. Any chance that is being looked at as JWT supports GZIP.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.