當前位置: 首頁>>代碼示例>>TypeScript>>正文


TypeScript jsontokens.decodeToken函數代碼示例

本文整理匯總了TypeScript中jsontokens.decodeToken函數的典型用法代碼示例。如果您正苦於以下問題:TypeScript decodeToken函數的具體用法?TypeScript decodeToken怎麽用?TypeScript decodeToken使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。


在下文中一共展示了decodeToken函數的10個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的TypeScript代碼示例。

示例1: decodeToken

  return Promise.resolve().then(() => {
    const payload = decodeToken(token).payload

    if (!payload.username) {
      return true
    }

    if (payload.username === null) {
      return true
    }

    if (nameLookupURL === null) {
      return false
    }

    const username = payload.username
    const url = `${nameLookupURL.replace(/\/$/, '')}/${username}`
    return fetch(url)
      .then(response => response.text())
      .then((responseText) => {
        const responseJSON = JSON.parse(responseText)
        if (responseJSON.hasOwnProperty('address')) {
          const nameOwningAddress = responseJSON.address
          const addressFromIssuer = getAddressFromDID(payload.iss)
          if (nameOwningAddress === addressFromIssuer) {
            return true
          } else {
            return false
          }
        } else {
          return false
        }
      })
  }).catch(() => false)
開發者ID:blockstack,項目名稱:blockstack-cli,代碼行數:34,代碼來源:authVerification.ts

示例2: getAuthenticationScopes

  /*
   * Get the authentication token's association token's scopes.
   * Does not validate the authentication token or the association token
   * (do that with isAuthenticationValid first).
   *
   * Returns the scopes, if there are any given.
   * Returns [] if there is no association token, or if the association token has no scopes
   */
  getAuthenticationScopes(): Array<AuthScopeType> {
    let decodedToken: TokenType
    try {
      decodedToken = decodeToken(this.token)
    } catch (e) {
      logger.error(this.token)
      logger.error('getAuthenticationScopes')
      throw new ValidationError('Failed to decode authentication JWT')
    }

    if (!decodedToken.payload.hasOwnProperty('scopes')) {
      // not given
      return []
    }

    // unambiguously convert to AuthScope
    const scopes = decodedToken.payload.scopes.map((s) => {
      const r = {
        scope: String(s.scope),
        domain: String(s.domain)
      }
      return r
    })

    return scopes
  }
開發者ID:blockstack,項目名稱:blockstack-registrar,代碼行數:34,代碼來源:authentication.ts

示例3: verifyProfileToken

export function verifyProfileToken(token: string, publicKeyOrAddress: string) {
  const decodedToken = decodeToken(token)
  const payload = decodedToken.payload

  // Inspect and verify the subject
  if (payload.hasOwnProperty('subject')) {
    if (!payload.subject.hasOwnProperty('publicKey')) {
      throw new Error('Token doesn\'t have a subject public key')
    }
  } else {
    throw new Error('Token doesn\'t have a subject')
  }

  // Inspect and verify the issuer
  if (payload.hasOwnProperty('issuer')) {
    if (!payload.issuer.hasOwnProperty('publicKey')) {
      throw new Error('Token doesn\'t have an issuer public key')
    }
  } else {
    throw new Error('Token doesn\'t have an issuer')
  }

  // Inspect and verify the claim
  if (!payload.hasOwnProperty('claim')) {
    throw new Error('Token doesn\'t have a claim')
  }

  const issuerPublicKey = payload.issuer.publicKey
  const publicKeyBuffer = Buffer.from(issuerPublicKey, 'hex')

  const compressedKeyPair =  ECPair.fromPublicKey(publicKeyBuffer, { compressed: true })
  const compressedAddress = ecPairToAddress(compressedKeyPair)
  const uncompressedKeyPair = ECPair.fromPublicKey(publicKeyBuffer, { compressed: false })
  const uncompressedAddress = ecPairToAddress(uncompressedKeyPair)

  if (publicKeyOrAddress === issuerPublicKey) {
    // pass
  } else if (publicKeyOrAddress === compressedAddress) {
    // pass
  } else if (publicKeyOrAddress === uncompressedAddress) {
    // pass
  } else {
    throw new Error('Token issuer public key does not match the verifying value')
  }

  const tokenVerifier = new TokenVerifier(decodedToken.header.alg, issuerPublicKey)
  if (!tokenVerifier) {
    throw new Error('Invalid token verifier')
  }

  const tokenVerified = tokenVerifier.verify(token)
  if (!tokenVerified) {
    throw new Error('Token verification failed')
  }

  return decodedToken
}
開發者ID:blockstack,項目名稱:blockstack-cli,代碼行數:57,代碼來源:profileTokens.ts

示例4: checkAssociationToken

  checkAssociationToken(token: string, bearerAddress: string) {
    // a JWT can have an `associationToken` that was signed by one of the
    // whitelisted addresses on this server.  This method checks a given
    // associationToken and verifies that it authorizes the "outer"
    // JWT's address (`bearerAddress`)

    let associationToken: TokenType
    try {
      associationToken = decodeToken(token)
    } catch (e) {
      throw new ValidationError('Failed to decode association token in JWT')
    }

    // publicKey (the issuer of the association token)
    // will be the whitelisted address (i.e. the identity address)
    const publicKey = associationToken.payload.iss
    const childPublicKey = associationToken.payload.childToAssociate
    const expiresAt = associationToken.payload.exp

    if (! publicKey) {
      throw new ValidationError('Must provide `iss` claim in association JWT.')
    }

    if (! childPublicKey) {
      throw new ValidationError('Must provide `childToAssociate` claim in association JWT.')
    }

    if (! expiresAt) {
      throw new ValidationError('Must provide `exp` claim in association JWT.')
    }

    const verified = new TokenVerifier('ES256K', publicKey).verify(token)
    if (!verified) {
      throw new ValidationError('Failed to verify association JWT: invalid issuer')
    }

    if (expiresAt < (Date.now()/1000)) {
      throw new ValidationError(
        `Expired association token: expire time of ${expiresAt} (secs since epoch)`)
    }

    // the bearer of the association token must have authorized the bearer
    const childAddress = ecPairToAddress(pubkeyHexToECPair(childPublicKey))
    if (childAddress !== bearerAddress) {
      throw new ValidationError(
        `Association token child key ${childPublicKey} does not match ${bearerAddress}`)
    }

    const signerAddress = ecPairToAddress(pubkeyHexToECPair(publicKey))
    return signerAddress

  }
開發者ID:blockstack,項目名稱:blockstack-registrar,代碼行數:52,代碼來源:authentication.ts

示例5: isExpirationDateValid

export function isExpirationDateValid(token: string) {
  const payload = decodeToken(token).payload
  if (payload.exp) {
    if (typeof payload.exp !== 'number') {
      return false
    }
    const expiresAt = new Date(payload.exp * 1000) // JWT times are in seconds
    if (new Date().getTime() > expiresAt.getTime()) {
      return false
    } else {
      return true
    }
  } else {
    return true
  }
}
開發者ID:blockstack,項目名稱:blockstack-cli,代碼行數:16,代碼來源:authVerification.ts

示例6: doPublicKeysMatchIssuer

export function doPublicKeysMatchIssuer(token: string) {
  const payload = decodeToken(token).payload
  const publicKeys = payload.public_keys
  const addressFromIssuer = getAddressFromDID(payload.iss)

  if (publicKeys.length === 1) {
    const addressFromPublicKeys = publicKeyToAddress(publicKeys[0])
    if (addressFromPublicKeys === addressFromIssuer) {
      return true
    }
  } else {
    throw new Error('Multiple public keys are not supported')
  }

  return false
}
開發者ID:blockstack,項目名稱:blockstack-cli,代碼行數:16,代碼來源:authVerification.ts

示例7: isIssuanceDateValid

export function isIssuanceDateValid(token: string) {
  const payload = decodeToken(token).payload
  if (payload.iat) {
    if (typeof payload.iat !== 'number') {
      return false
    }
    const issuedAt = new Date(payload.iat * 1000) // JWT times are in seconds
    if (new Date().getTime() < issuedAt.getTime()) {
      return false
    } else {
      return true
    }
  } else {
    return true
  }
}
開發者ID:blockstack,項目名稱:blockstack-cli,代碼行數:16,代碼來源:authVerification.ts

示例8: extractProfile

export function extractProfile(token: string, publicKeyOrAddress: string | null = null) {
  let decodedToken
  if (publicKeyOrAddress) {
    decodedToken = verifyProfileToken(token, publicKeyOrAddress)
  } else {
    decodedToken = decodeToken(token)
  }

  let profile = {}
  if (decodedToken.hasOwnProperty('payload')) {
    const payload = decodedToken.payload
    if (payload.hasOwnProperty('claim')) {
      profile = decodedToken.payload.claim
    }
  }

  return profile
}
開發者ID:blockstack,項目名稱:blockstack-cli,代碼行數:18,代碼來源:profileTokens.ts

示例9: doSignaturesMatchPublicKeys

export function doSignaturesMatchPublicKeys(token: string) {
  const payload = decodeToken(token).payload
  const publicKeys = payload.public_keys
  if (publicKeys.length === 1) {
    const publicKey = publicKeys[0]
    try {
      const tokenVerifier = new TokenVerifier('ES256k', publicKey)
      const signatureVerified = tokenVerifier.verify(token)
      if (signatureVerified) {
        return true
      } else {
        return false
      }
    } catch (e) {
      return false
    }
  } else {
    throw new Error('Multiple public keys are not supported')
  }
}
開發者ID:blockstack,項目名稱:blockstack-cli,代碼行數:20,代碼來源:authVerification.ts

示例10: getCoreSession

export function getCoreSession(coreHost: string,
                               corePort: number,
                               apiPassword: string,
                               appPrivateKey: string,
                               blockchainId: string = null,
                               authRequest: string = null,
                               deviceId: string = '0') {
  if (!authRequest) {
    return Promise.reject('No authRequest provided')
  }

  let payload = null
  let authRequestObject = null
  try {
    authRequestObject = decodeToken(authRequest)
    if (!authRequestObject) {
      return Promise.reject('Invalid authRequest in URL query string')
    }
    if (!authRequestObject.payload) {
      return Promise.reject('Invalid authRequest in URL query string')
    }
    payload = authRequestObject.payload
  } catch (e) {
    console.error(e.stack)
    return Promise.reject('Failed to parse authRequest in URL')
  }

  const appDomain = payload.domain_name
  if (!appDomain) {
    return Promise.reject('No domain_name in authRequest')
  }
  const appMethods = payload.scopes

  const coreAuthRequest = makeCoreSessionRequest(
    appDomain, appMethods, appPrivateKey, blockchainId, deviceId
  )

  return sendCoreSessionRequest(
    coreHost, corePort, coreAuthRequest, apiPassword
  )
}
開發者ID:blockstack,項目名稱:blockstack-cli,代碼行數:41,代碼來源:authSession.ts


注:本文中的jsontokens.decodeToken函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。