JWT (JSON Web Token) automatic prolongation of expiration

后端 未结 12 2048
一向
一向 2020-11-22 10:56

I would like to implement JWT-based authentication to our new REST API. But since the expiration is set in the token, is it possible to automatically prolong it? I don\'t wa

12条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-22 11:39

    jwt-autorefresh

    If you are using node (React / Redux / Universal JS) you can install npm i -S jwt-autorefresh.

    This library schedules refresh of JWT tokens at a user calculated number of seconds prior to the access token expiring (based on the exp claim encoded in the token). It has an extensive test suite and checks for quite a few conditions to ensure any strange activity is accompanied by a descriptive message regarding misconfigurations from your environment.

    Full example implementation

    import autorefresh from 'jwt-autorefresh'
    
    /** Events in your app that are triggered when your user becomes authorized or deauthorized. */
    import { onAuthorize, onDeauthorize } from './events'
    
    /** Your refresh token mechanism, returning a promise that resolves to the new access tokenFunction (library does not care about your method of persisting tokens) */
    const refresh = () => {
      const init =  { method: 'POST'
                    , headers: { 'Content-Type': `application/x-www-form-urlencoded` }
                    , body: `refresh_token=${localStorage.refresh_token}&grant_type=refresh_token`
                    }
      return fetch('/oauth/token', init)
        .then(res => res.json())
        .then(({ token_type, access_token, expires_in, refresh_token }) => {
          localStorage.access_token = access_token
          localStorage.refresh_token = refresh_token
          return access_token
        })
    }
    
    /** You supply a leadSeconds number or function that generates a number of seconds that the refresh should occur prior to the access token expiring */
    const leadSeconds = () => {
      /** Generate random additional seconds (up to 30 in this case) to append to the lead time to ensure multiple clients dont schedule simultaneous refresh */
      const jitter = Math.floor(Math.random() * 30)
    
      /** Schedule autorefresh to occur 60 to 90 seconds prior to token expiration */
      return 60 + jitter
    }
    
    let start = autorefresh({ refresh, leadSeconds })
    let cancel = () => {}
    onAuthorize(access_token => {
      cancel()
      cancel = start(access_token)
    })
    
    onDeauthorize(() => cancel())
    

    disclaimer: I am the maintainer

提交回复
热议问题