JWT /token endpoint should return a JSON object whose only key, "token", stores the JWT built by the builder.
323583
public String extractJwtFromTokenEndpointResponse(Page response) throws Exception {
        JsonReader reader = Json.createReader(new StringReader(WebResponseUtils.getResponseText(response)));
        JsonObject jsonResponse = reader.readObject();
        return jsonResponse.getString("token");
    }
433929
def token_getter(provider, token=None):
        
        session_key = provider + '_token'
        if token is None:
            token = session.get(session_key)
        return token
423263
def info(self, token):
        
        verifier = JWT(key_jar=self.key_jar, allowed_sign_algs=[self.alg])
        _payload = verifier.unpack(token)
        if is_expired(_payload['exp']):
            raise ToOld('Token has expired')
        return _payload['sid'], _payload['ttype']
1017069
private String build(Map<String, Object> claims, Date expireTime) {
        return Jwts.builder()
                .setClaims(claims)
                .setExpiration(expireTime)
                .signWith(SignatureAlgorithm.HS512, jwtProperties.getSecret())
                .compact();
    }
256482
@POST
    @Produces(MediaType.TEXT_PLAIN)
    @ApiOperation(
            value = "Assert login credentials",
            notes = "Upon a successful login, a JWT will be returned in the response. This functionality requires authentication to be enabled.",
            response = String.class
    )
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "Success"),
            @ApiResponse(code = 401, message = "Unauthorized")
    })
    @AuthenticationNotRequired
    public Response validateCredentials(@FormParam("username") String username, @FormParam("password") String password) {
        final Authenticator auth = new Authenticator(username, password);
        try {
            final Principal principal = auth.authenticate();
            if (principal != null) {
                LOGGER.info(SecurityMarkers.SECURITY_AUDIT, "Login succeeded (username: " + username
                        + " / ip address: " + super.getRemoteAddress()
                        + " / agent: " + super.getUserAgent() + ")");

                final JsonWebToken jwt = new JsonWebToken();
                final String token = jwt.createToken(principal);
                return Response.ok(token).build();
            }
        } catch (AuthenticationException e) {
            LOGGER.warn(SecurityMarkers.SECURITY_AUDIT, "Unauthorized login attempt (username: "
                    + username + " / ip address: " + super.getRemoteAddress()
                    + " / agent: " + super.getUserAgent() + ")");
        }
        return Response.status(Response.Status.UNAUTHORIZED).build();
    }
1234087
def create_token(key, payload):
  
  token = hmac.new(key)
  token.update(json.dumps(payload))
  return token.hexdigest()
1066720
def get_JWT(url, address=None):
    
    jwt_txt = None
    jwt = None

    log.debug("Try {}".format(url))

    # special case: handle file://
    urlinfo = urllib2.urlparse.urlparse(url)
    if urlinfo.scheme == 'file':
        # points to a path on disk
        try:
            with open(urlinfo.path, 'r') as f:
                jwt_txt = f.read()

        except Exception as e:
            if BLOCKSTACK_TEST:
                log.exception(e)

            log.warning("Failed to read {}".format(url))
            return None

    else:
        # http(s) URL or similar
        try:
            resp = requests.get(url)
            assert resp.status_code == 200, 'Bad status code on {}: {}'.format(url, resp.status_code)
            jwt_txt = resp.text

        except Exception as e:
            if BLOCKSTACK_TEST:
                log.exception(e)

            log.warning("Unable to resolve {}".format(url))
            return None

    try:
        # one of two things are possible:
        # * this is a JWT string
        # * this is a serialized JSON string whose first item is a dict that has 'token' as key,
        # and that key is a JWT string.
        try:
            jwt_txt = json.loads(jwt_txt)[0]['token']
        except:
            pass

        jwt = jsontokens.decode_token(jwt_txt)
    except Exception as e:
        if BLOCKSTACK_TEST:
            log.exception(e)

        log.warning("Unable to decode token at {}".format(url))
        return None

    try:
        # must be well-formed
        assert isinstance(jwt, dict)
        assert 'payload' in jwt, jwt
        assert isinstance(jwt['payload'], dict)
        assert 'issuer' in jwt['payload'], jwt
        assert isinstance(jwt['payload']['issuer'], dict)
        assert 'publicKey' in jwt['payload']['issuer'], jwt
        assert virtualchain.ecdsalib.ecdsa_public_key(str(jwt['payload']['issuer']['publicKey']))

    except AssertionError as ae:
        if BLOCKSTACK_TEST or BLOCKSTACK_DEBUG:
            log.exception(ae)

        log.warning("JWT at {} is malformed".format(url))
        return None

    if address is not None:
        public_key = str(jwt['payload']['issuer']['publicKey'])
        addrs = [virtualchain.address_reencode(virtualchain.ecdsalib.ecdsa_public_key(keylib.key_formatting.decompress(public_key)).address()),
                 virtualchain.address_reencode(virtualchain.ecdsalib.ecdsa_public_key(keylib.key_formatting.compress(public_key)).address())]

        if virtualchain.address_reencode(address) not in addrs:
            # got a JWT, but it doesn't match the address
            log.warning("Found JWT at {}, but its public key has addresses {} and {} (expected {})".format(url, addrs[0], addrs[1], address))
            return None

        verifier = jsontokens.TokenVerifier()
        if not verifier.verify(jwt_txt, public_key):
            # got a JWT, and the address matches, but the signature does not
            log.warning("Found JWT at {}, but it was not signed by {} ({})".format(url, public_key, address))
            return None

    return jwt
1108632
public String sign(JWTCreator.Builder builder) {
        // use the strongest algorithm;
        return builder.sign(Algorithm.ECDSA512(ecPublicKey, ecPrivateKey));
    }
433417
public JwtToken refreshToken(String token) {
        String refreshedToken;
        Date expireTime = generateExpirationDate();
        try {
            final Claims claims = getClaimsFromToken(token);
            claims.put(CLAIM_KEY_CREATED, expireTime.getTime());
            refreshedToken = build(claims, expireTime);
        } catch (Exception e) {
            log.error("refreshedToken jwt token error : {}", e.getMessage());
            refreshedToken = null;
        }
        return new JwtToken(refreshedToken, expireTime.getTime());
    }
511981
def read_session_token(secret_key, token):
    
    return jwt.decode(token.encode('utf-8'), secret_key,
        algorithms=[token_encryption_algorithm()]
    )
152659
function get_jwt_token(ctx)
{
	// Parses "Authorization: Bearer ${token}"
	if (ctx.header.authorization)
	{
		const match = ctx.header.authorization.match(/^Bearer (.+)$/i)

		if (match)
		{
			return match[1]
		}
	}

	// (doesn't read cookies anymore to protect users from CSRF attacks)
	// // Tries the "authentication" cookie
	// if (ctx.cookies.get('authentication'))
	// {
	// 	return ctx.cookies.get('authentication')
	// }
}
1338976
def post(self):
        
        res = {"success": False}
        #1.
        token = request.cookies.get("token") or request.headers.get("authentication")
        if not token:
            return res
        #2.
        try:
            self.jwt.verifyJWT(token)
        except JWTException as e:
            self.logger.exception(e, exc_info=True)
        else:
            res.update(success=True)
        return res
799934
public String getJwtTokenUsingBuilder(String testName, LibertyServer server, String builderId, List<NameValuePair> extraClaims) throws Exception {

        String jwtBuilderUrl = SecurityFatHttpUtils.getServerUrlBase(server) + "/jwtbuilder/build";

        List<NameValuePair> requestParams = setRequestParms(builderId, extraClaims);

        WebClient webClient = new WebClient();
        Page response = invokeUrlWithParameters(testName, webClient, jwtBuilderUrl, requestParams);
        Log.info(thisClass, testName, "JWT builder app response: " + WebResponseUtils.getResponseText(response));

        Cookie jwtCookie = webClient.getCookieManager().getCookie("JWT");
        Log.info(thisClass, testName, "Built JWT cookie: " + jwtCookie);
        Log.info(thisClass, testName, "Cookie value: " + jwtCookie.getValue());
        return jwtCookie.getValue();

    }
530729
private Optional<JsonWebKeySet> buildJsonWebKeySet() {
        try {
            LOGGER.debug("Loading default JSON web key from [{}]", this.jwksFile);
            if (this.jwksFile != null) {
                LOGGER.debug("Retrieving default JSON web key from [{}]", this.jwksFile);
                val jsonWebKeySet = buildJsonWebKeySet(this.jwksFile);

                if (jsonWebKeySet == null || jsonWebKeySet.getJsonWebKeys().isEmpty()) {
                    LOGGER.warn("No JSON web keys could be found");
                    return Optional.empty();
                }
                val badKeysCount = jsonWebKeySet.getJsonWebKeys().stream().filter(k ->
                    StringUtils.isBlank(k.getAlgorithm())
                        && StringUtils.isBlank(k.getKeyId())
                        && StringUtils.isBlank(k.getKeyType())).count();

                if (badKeysCount == jsonWebKeySet.getJsonWebKeys().size()) {
                    LOGGER.warn("No valid JSON web keys could be found");
                    return Optional.empty();
                }

                val webKey = getJsonSigningWebKeyFromJwks(jsonWebKeySet);
                if (webKey.getPrivateKey() == null) {
                    LOGGER.warn("JSON web key retrieved [{}] has no associated private key", webKey.getKeyId());
                    return Optional.empty();
                }
                return Optional.of(jsonWebKeySet);
            }
        } catch (final Exception e) {
            LOGGER.debug(e.getMessage(), e);
        }
        return Optional.empty();
    }
1285112
def token_data
      return @token_data if @token_data
      return {} unless @auth_header

      json_hashes = Base64.decode64(@auth_header.split(" ", 2).last)
      data_json = json_hashes.sub(JSON_HASH, "")[JSON_HASH]
      return {} unless data_json

      @token_data = MultiJson.load data_json, :symbolize_keys => true
    rescue MultiJson::DecodeError
      {}
    end
1129084
def jwt_proccessor():
    """"""
    def jwt():
        """Context processor function to generate jwt."""
        token = current_accounts.jwt_creation_factory()
        return Markup(
            render_template(
                current_app.config['ACCOUNTS_JWT_DOM_TOKEN_TEMPLATE'],
                token=token
            )
        )

    def jwt_token():
        """Context processor function to generate jwt."""
        return current_accounts.jwt_creation_factory()

    return {
        'jwt': jwt,
        'jwt_token': jwt_token,
    }
481711
def VerifyGitkitToken(self, jwt):
    
    certs = self.rpc_helper.GetPublicCert()
    crypt.MAX_TOKEN_LIFETIME_SECS = 30 * 86400  # 30 days
    parsed = None
    for aud in filter(lambda x: x is not None, [self.project_id, self.client_id]):
      try:
        parsed = crypt.verify_signed_jwt_with_certs(jwt, certs, aud)
      except crypt.AppIdentityError as e:
        if "Wrong recipient" not in e.message:
          return None
      if parsed:
        return GitkitUser.FromToken(parsed)
    return None