Store token to disk be used in later program executions.

@param {Object} credentials The authorization client credentials.
@param {Object} token The token to store to disk.
165674
function storeToken(credentials, token) {
    fs.writeFile(TOKEN_PATH, JSON.stringify(token));
    console.log('Token stored to ' + TOKEN_PATH);

    console.log('Add the following json block to your .juttle/config.{js,json} file:');
    var juttle_config = {
        adapters: {
            "gmail": {
                "client-credentials": credentials,
                "oauth2-token": token,
            }
        }
    };

    console.log(JSON.stringify(juttle_config, null, 4));

    console.log("If you already have a \"adapters\" section, add the \"gmail\" section under the existing \"adapters\" section.");
}
769644
function (token) {
    var tokens = token;
    if (!_.isArray(tokens)) {
      tokens = [tokens];
    }

    tokens = tokens.map(function (token) {
      // Allow passing stores straight and we grab the dispatcherToken
      return token.dispatcherToken || token;
    });

    return this.dispatcher.waitFor(tokens);
  }
939434
protected synchronized void cacheToken(final Token token) {

		log.debug("OAuthTokenManager.cacheToken");

		// Parse token expires in seconds.
		int tokenExpiresInSecs;
		try {
			tokenExpiresInSecs = Integer.parseInt(token.getExpires_in());
		} catch (NumberFormatException exception) {
			tokenExpiresInSecs = 0;
		}

		// Parse token expiration time
		long tokenExpirationTime;
		try {
			tokenExpirationTime = Long.parseLong(token.getExpiration());
		} catch (NumberFormatException exception) {
			tokenExpirationTime = 0;
		}

		// Calculate token refresh time based on lifespan percentage offset.
		long refreshBeforeExpirySecs = (long) (tokenExpiresInSecs * this.iamRefreshOffset);
		long tokenRefreshTime = tokenExpirationTime - refreshBeforeExpirySecs;

		token.setRefreshTime(tokenRefreshTime);
		token.setExpirationTime(tokenExpirationTime);

		setTokenCache(token);
	}
832482
function createToken (client) {
  return ask([
    {"type": "input",     "message": "Username", "name": "user"},
    {"type": "password",  "message": "Password", "name": "password"}
  ]).then(function (answers) {
    return client.createToken(answers.username, answers.password)
      .then(saveToken)
      .then(function (token) {
        // Authorize client…
        client.setToken(token);
        // …and send it back to connect()
        return client;
      });
  });
}
1257450
public void saveCredentials(@NonNull Credentials credentials) {
        if ((isEmpty(credentials.getAccessToken()) && isEmpty(credentials.getIdToken())) || credentials.getExpiresAt() == null) {
            throw new CredentialsManagerException("Credentials must have a valid date of expiration and a valid access_token or id_token value.");
        }
        storage.store(KEY_ACCESS_TOKEN, credentials.getAccessToken());
        storage.store(KEY_REFRESH_TOKEN, credentials.getRefreshToken());
        storage.store(KEY_ID_TOKEN, credentials.getIdToken());
        storage.store(KEY_TOKEN_TYPE, credentials.getType());
        storage.store(KEY_EXPIRES_AT, credentials.getExpiresAt().getTime());
        storage.store(KEY_SCOPE, credentials.getScope());
    }
489659
public function setAuthToken($token, $secret) {
		$this->authToken = $token;
		$this->authSecret = $secret;
		$this->f3->set('SESSION.dropbox.authToken', $this->authToken);
		$this->f3->set('SESSION.dropbox.authSecret', $this->authSecret);
	}
904527
def set_token(self):
        
        super(ServicePrincipalCredentials, self).set_token()
        try:
            token = self._context.acquire_token_with_client_credentials(
                self.resource,
                self.id,
                self.secret
            )
            self.token = self._convert_token(token)
        except adal.AdalError as err:
            raise_with_traceback(AuthenticationError, "", err)
778942
public void store(Auth token) throws IOException {
        this.auths.put(token.getUser().getId(), token);
        this.authsByUser.put(token.getUser().getUsername(), token);

        String filename = token.getUser().getId() + ".auth";
        File outFile = new File(this.authStoreDir, filename);
        outFile.createNewFile();

        ObjectOutputStream authStream = new ObjectOutputStream(new FileOutputStream(outFile));
        authStream.writeObject(token);
        authStream.flush();
        authStream.close();
    }
998789
public void setCredentials(String username, String password) {
        this.username = username;
        this.password = password;
    	authorization = "Basic " + Base64.getEncoder().encodeToString(filesystem.getWorld().getSettings().bytes(username + ":" + password));
    }
362943
async function loadToken (url) {
  let tokens
  try {
    const data = await readFile(credentialsPath)
    tokens = JSON.parse(data)
  } catch (err) {}
  return tokens && tokens[url]
}
259032
public synchronized void initialiseFromAPIToken(final String token)
	{
		final String responseStr = authService.getToken(UserManagerOAuthService.GRANT_TYPE_TOKEN_EXCHANGE,
		                                                null,
		                                                getOwnCallbackUri().toString(),
		                                                clientId,
		                                                clientSecret,
		                                                null,
		                                                null,
		                                                null,
		                                                token);

		loadAuthResponse(responseStr);
	}
946398
async function authenticate({ options, keys, log })
{
	// A little helper which can be called from routes
	// as `ctx.role('administrator')`
	// which will throw if the user isn't administrator.
	// The `roles` are taken from JWT payload.
	this.role = (...roles) =>
	{
		if (!this.user)
		{
			throw new errors.Unauthenticated()
		}

		for (const role of roles)
		{
			for (const user_role of this.user.roles)
			{
				if (user_role === role)
				{
					return true
				}
			}
		}

		throw new errors.Unauthorized(`One of the following roles is required: ${roles}`)
	}

	// Get JWT token from incoming HTTP request
	let token = get_jwt_token(this)

	// If no JWT token was found, then done
	if (!token)
	{
		return
	}

	// JWT token (is now accessible from Koa's `ctx`)
	this.accessToken = token

	// Verify JWT token integrity
	// by checking its signature using the supplied `keys`

	let payload

	for (const secret of keys)
	{
		try
		{
			payload = jwt.verify(token, secret)
			break
		}
		catch (error)
		{
			// If authentication token expired
			if (error.name === 'TokenExpiredError')
			{
				if (options.refreshAccessToken)
				{
					// If refreshing an access token fails
					// then don't prevent the user from at least seeing a page
					// therefore catching an error here.
					try
					{
						token = await options.refreshAccessToken(this)
					}
					catch (error)
					{
						log.error(error)
					}

					if (token)
					{
						for (const secret of keys)
						{
							try
							{
								payload = jwt.verify(token, secret)
								break
							}
							catch (error)
							{
								// Try another `secret`
								if (error.name === 'JsonWebTokenError' && error.message === 'invalid signature')
								{
									continue
								}

								// Some other non-JWT-related error
								log.error(error)
								break
							}
						}
					}
				}

				if (payload)
				{
					break
				}

				throw new errors.Access_token_expired()
			}

			// Try another `secret`
			if (error.name === 'JsonWebTokenError' && error.message === 'invalid signature')
			{
				continue
			}

			// Some other non-JWT-related error.
			// Shouldn't prevent the user from at least seeing a page
			// therefore not rethrowing this error.
			log.error(error)
			break
		}
	}

	// If JWT token signature was unable to be verified, then exit
	if (!payload)
	{
		return
	}

	// If the access token isn't valid for access to this server
	// (e.g. it's a "refresh token") then exit.
	if (options.validateAccessToken)
	{
		if (!options.validateAccessToken(payload, this))
		{
			return
		}
	}

	// Token payload can be accessed through `ctx`
	this.accessTokenPayload = payload

	// Fire "on user request" hook
	if (options.onUserRequest)
	{
		options.onUserRequest(token, this)
	}

	// JWT token ID
	const jwt_id = payload.jti

	// `subject`
	// (which is a user id)
	const user_id = payload.sub

	// // Optional JWT token validation (by id)
	// // (for example, that it has not been revoked)
	// if (validateToken)
	// {
	// 	// Can validate the token via a request to a database, for example.
	// 	// Checks for `valid` property value inside the result object.
	// 	// (There can possibly be other properties such as `reason`)
	// 	const is_valid = (await validateToken(token, this)).valid
	//
	// 	// If the JWT token happens to be invalid
	// 	// (expired or revoked, for example), then exit.
	// 	if (!is_valid)
	// 	{
	// 		// this.authenticationError = new errors.Unauthenticated('AccessTokenRevoked')
	// 		return
	// 	}
	// }

	// JWT token ID is now accessible via Koa's `ctx`
	this.accessTokenId = jwt_id

	// Extracts user data (description) from JWT token payload
	// (`user` is now accessible via Koa's `ctx`)
	this.user = options.userInfo ? options.userInfo(payload) : {}

	// Sets user id
	this.user.id = user_id
	
	// Extra payload fields:
	//
	// 'iss' // Issuer
	// 'sub' // Subject
	// 'aud' // Audience
	// 'exp' // Expiration time
	// 'nbf' // Not before
	// 'iat' // Issued at 
	// 'jti' // JWT ID

	// JWT token payload is accessible via Koa's `ctx`
	this.accessTokenPayload = payload
}
232783
public void saveToken(CsrfToken t, HttpServletRequest request, HttpServletResponse response) {
		String ident = getIdentifierFromCookie(request);
		if (ident != null) {
			String key = ident.concat(parameterName);
			CsrfToken token = loadToken(request);
			if (token == null) {
				token = generateToken(null);
				if (Config.isCacheEnabled()) {
					cache.put(Config.getRootAppIdentifier(), key, token, (long) Config.SESSION_TIMEOUT_SEC);
				} else {
					localCache.put(key, new Object[]{token, System.currentTimeMillis()});
				}
			}
			storeTokenAsCookie(token, request, response);
		}
	}
751231
function init(ctx) {
        var server = ctx.server;

        if (!privateKey) {
            throw new Error('Please set config.security.token.privateKey');
        }

        server.ext('onPreAuth', validateToken);

        return new Q(ctx);
    }
1352365
private Auth constructAuth(String authToken, String tokenSecret, String username) throws IOException {

        Auth auth = new Auth();
        auth.setToken(authToken);
        auth.setTokenSecret(tokenSecret);

        // Prompt to ask what permission is needed: read, update or delete.
        auth.setPermission(Permission.fromString("delete"));

        User user = new User();
        // Later change the following 3. Either ask user to pass on command line or read
        // from saved file.
        user.setId(nsid);
        user.setUsername((username));
        user.setRealName("");
        auth.setUser(user);
        this.authStore.store(auth);
        return auth;
    }
65073
private void putCred(String key, EsToken token, Map<String, String> credentials) {
        FastByteArrayOutputStream stream = new FastByteArrayOutputStream();
        DataOutput output = new DataOutputStream(stream);
        try {
            token.writeOut(output);
        } catch (IOException e) {
            throw new EsHadoopException("Could not serialize EsToken", e);
        }
        String credential = new String(Base64.encodeBase64(stream.bytes().bytes()), StringUtils.UTF_8);
        credentials.put(key, credential);
    }
381619
public void saveResumeToken(String token) {
        SharedPreferences settings = mContext.getSharedPreferences(PREF_DDPINFO, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = settings.edit();
        //REVIEW: should token be encrypted?
        editor.putString(PREF_RESUMETOKEN, token);
        editor.apply();
    }