/*
client-side generation of credential token
490577
private String randomSecret() {
        byte[] r = new byte[32];
        new Random().nextBytes(r);
        return Base64.encodeToString(r, Base64.URL_SAFE | Base64.NO_WRAP | Base64.NO_PADDING);
    }
1011588
private String generateLockToken(HttpServletRequest req, CmsRepositoryLockInfo lock) {

        String lockTokenStr = req.getServletPath()
            + "-"
            + req.getUserPrincipal()
            + "-"
            + lock.getOwner()
            + "-"
            + lock.getPath()
            + "-"
            + m_secret;

        return MD5_ENCODER.encode(m_md5Helper.digest(lockTokenStr.getBytes()));
    }
401162
private String createSignature(Credentials credentials, String secretKey) {
        return new SignatureGenerator().generate(
                secretKey,
                credentials.getMethod(),
                credentials.getTimestamp(),
                credentials.getPath(),
                credentials.getContent());
    }
661211
function tokenCredentials (authorization, secret, done) {
  var strategy = this
  var provider = strategy.provider
  var endpoint = strategy.endpoints.token
  var client = strategy.client
  var method = endpoint.method && endpoint.method.toLowerCase()
  var url = endpoint.url
  var header = endpoint.header || 'Authorization'
  var scheme = endpoint.scheme || 'OAuth'
  var accept = endpoint.accept || 'application/x-www-form-urlencoded'
  var key = client.oauth_consumer_key
  var signer = provider.oauth_signature_method || 'PLAINTEXT'
  var verifier = authorization.oauth_verifier || null
  var token = authorization.oauth_token
  var params = {}

  // Initialize request
  var req = request[method || 'post'](url)

  // Build request parameters
  params.oauth_consumer_key = key
  params.oauth_signature_method = signer
  params.oauth_timestamp = timestamp()
  params.oauth_nonce = nonce(32)
  params.oauth_token = token
  params.oauth_verifier = verifier
  params.oauth_version = '1.0'

  var input = signatureBaseString(method, url, normalizeParameters(params))
  params.oauth_signature = sign(signer, input, secret)

  // Set Authorization header
  req.set(header, scheme + ' ' + authorizationHeaderParams(params))

  // Set other headers
  req.set('Accept', accept)
  req.set('User-Agent', agent)

  // Execute request
  return req.end(function (err, res) {
    if (err) { return done(err) }
    var response = qs.parse(res.text)

    if (res.statusCode !== 200) {
      return done(new Error("Couldn't obtain token credentials"))
    }

    done(null, response)
  })
}
1248032
private AuthenticationData createAuthenticationData(HttpServletRequest req, HttpServletResponse res, String token, String oid) {
        AuthenticationData authenticationData = new WSAuthenticationData();
        authenticationData.set(AuthenticationData.HTTP_SERVLET_REQUEST, req);
        authenticationData.set(AuthenticationData.HTTP_SERVLET_RESPONSE, res);
        if (oid.equals(LTPA_OID)) {
            authenticationData.set(AuthenticationData.TOKEN64, token);
        } else {
            authenticationData.set(AuthenticationData.JWT_TOKEN, token);
        }

        authenticationData.set(AuthenticationData.AUTHENTICATION_MECH_OID, oid);
        return authenticationData;
    }
762635
def CredentialsFromFile(path, client_info, oauth2client_args=None):
    """"""
    user_agent = client_info['user_agent']
    scope_key = client_info['scope']
    if not isinstance(scope_key, six.string_types):
        scope_key = ':'.join(scope_key)
    storage_key = client_info['client_id'] + user_agent + scope_key

    if _NEW_FILESTORE:
        credential_store = multiprocess_file_storage.MultiprocessFileStorage(
            path, storage_key)
    else:
        credential_store = multistore_file.get_credential_storage_custom_string_key(  # noqa
            path, storage_key)
    if hasattr(FLAGS, 'auth_local_webserver'):
        FLAGS.auth_local_webserver = False
    credentials = credential_store.get()
    if credentials is None or credentials.invalid:
        print('Generating new OAuth credentials ...')
        for _ in range(20):
            # If authorization fails, we want to retry, rather than let this
            # cascade up and get caught elsewhere. If users want out of the
            # retry loop, they can ^C.
            try:
                flow = oauth2client.client.OAuth2WebServerFlow(**client_info)
                flags = _GetRunFlowFlags(args=oauth2client_args)
                credentials = tools.run_flow(flow, credential_store, flags)
                break
            except (oauth2client.client.FlowExchangeError, SystemExit) as e:
                # Here SystemExit is "no credential at all", and the
                # FlowExchangeError is "invalid" -- usually because
                # you reused a token.
                print('Invalid authorization: %s' % (e,))
            except httplib2.HttpLib2Error as e:
                print('Communication error: %s' % (e,))
                raise exceptions.CredentialsError(
                    'Communication error creating credentials: %s' % e)
    return credentials
793888
function getAccessToken(callback){

    console.log("Requesting access token from server...");

    var credentials = {
            scope: "messaging:push",
            grant_type: "client_credentials",
            client_id: CLIENT_ID,
            client_secret: CLIENT_SECRET
    }

    var post_data = querystring.stringify(credentials);

    var post_options = {
      host: "api.amazon.com",
      port: "443",
      path: "/auth/O2/token",
      method: "POST",
      headers: {
          "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"
      }
    };

    var req = https.request(post_options, function(res) {

        var data = "";

        res.on("data", function (chunk) {
            data += chunk;
        });

        res.on("end", function() {
            console.log("\nAccess token response:", data);
            var accessToken = JSON.parse(data).access_token;
            callback(accessToken);
        });

    });

    req.on("error", function(e) {
      console.log("\nProblem with access token request: ", e.message);
    });

    req.write(post_data);
    req.end();

}
790410
public static Credential credential(
      AccessTokenProvider accessTokenProvider, Collection<String> scopes)
      throws IOException, GeneralSecurityException {
    return getCredentialFromAccessTokenProvider(accessTokenProvider, scopes);
  }
710333
function generateAccessToken(req, res, next) {
        /**
         * TODO:
         * https://github.com/jaredhanson/oauth2orize/issues/182
         * oauth2orize only offers the option to forward request information via authInfo object
         *
         * Important: only used for resetting the brute count (access to req.ip)
         */
        req.authInfo = {
            ip: req.ip,
            accessToken: authUtils.getBearerAutorizationToken(req)
        };

        return oauthServer.token()(req, res, function (err) {
            if (err && err.status === 400) {
                err = new common.errors.BadRequestError({err: err, message: err.message});
            }

            next(err);
        });
    }
507534
static ClientAssertion buildJwt(final AsymmetricKeyCredential credential,
            final String jwtAudience) throws AuthenticationException {
        if (credential == null) {
            throw new IllegalArgumentException("credential is null");
        }

        final long time = System.currentTimeMillis();

        final JWTClaimsSet claimsSet = new JWTClaimsSet.Builder()
                .audience(Collections.singletonList(jwtAudience))
                .issuer(credential.getClientId())
                .jwtID(UUID.randomUUID().toString())
                .notBeforeTime(new Date(time))
                .expirationTime(new Date(time
                                + AuthenticationConstants.AAD_JWT_TOKEN_LIFETIME_SECONDS
                                * 1000))
                .subject(credential.getClientId())
                .build();

        SignedJWT jwt;
        try {
            JWSHeader.Builder builder = new Builder(JWSAlgorithm.RS256);
            List<Base64> certs = new ArrayList<Base64>();
            certs.add(new Base64(credential.getPublicCertificate()));
            builder.x509CertChain(certs);
            builder.x509CertThumbprint(new Base64URL(credential
                    .getPublicCertificateHash()));
            jwt = new SignedJWT(builder.build(), claimsSet);
            final RSASSASigner signer = new RSASSASigner(credential.getKey());

            jwt.sign(signer);
        }
        catch (final Exception e) {
            throw new AuthenticationException(e);
        }

        return new ClientAssertion(jwt.serialize());
    }
579537
def token_gen_call(username, password):
    """"""
    secret_key = 'super-secret-key-please-change'
    mockusername = 'User2'
    mockpassword = 'Mypassword'
    if mockpassword == password and mockusername == username: # This is an example. Don't do that.
        return {"token" : jwt.encode({'user': username, 'data': 'mydata'}, secret_key, algorithm='HS256')}
    return 'Invalid username and/or password for user: {0}'.format(username)
1294581
def _convert_credentials(token_url, username=None, password=None, refresh_token=None):
    
    if username and password:
        data = {'grant_type': 'password', 'username': username, 'password': password}
    elif refresh_token:
        data = {'grant_type': 'refresh_token', 'refresh_token': refresh_token}
    else:
        raise NotImplementedError()

    response = requests.post(token_url, data=data)
    if response.status_code == 401:
        raise Unauthorized('401 Client Error: Unauthorized')
    elif response.status_code == 200:
        d = response.json()
        expiry = datetime.utcnow() + timedelta(seconds=d['expires_in'])
        return Credentials(access_token=d['access_token'],
                           refresh_token=d['refresh_token'],
                           expiry=expiry)
    else:
        raise YamcsError('{} Server Error'.format(response.status_code))
1198317
private OAuthHmacCredential new10aCredential(String userId) {
        ClientParametersAuthentication clientAuthentication = (ClientParametersAuthentication) getClientAuthentication();
        OAuthHmacCredential.Builder builder =
                new OAuthHmacCredential.Builder(getMethod(), clientAuthentication.getClientId(),
                        clientAuthentication.getClientSecret())
                        .setTransport(getTransport())
                        .setJsonFactory(getJsonFactory())
                        .setTokenServerEncodedUrl(getTokenServerEncodedUrl())
                        .setClientAuthentication(getClientAuthentication())
                        .setRequestInitializer(getRequestInitializer())
                        .setClock(getClock());
        if (getCredentialStore() != null) {
            builder.addRefreshListener(
                    new CredentialStoreRefreshListener(userId, getCredentialStore()));
        }

        builder.getRefreshListeners().addAll(getRefreshListeners());

        return builder.build();
    }
644110
private void setSsoTokenCredential(Subject subject, String principalAccessId)
                    throws CredentialException {
        try {
            TokenManager tokenManager = tokenManagerRef.getService();
            SingleSignonToken ssoToken = null;
            Set<Token> tokens = subject.getPrivateCredentials(Token.class);
            if (tokens.isEmpty() == false) {
                Token ssoLtpaToken = tokens.iterator().next();
                subject.getPrivateCredentials().remove(ssoLtpaToken);
                ssoToken = tokenManager.createSSOToken(ssoLtpaToken);
            } else {
                Map<String, Object> tokenData = new HashMap<String, Object>();
                tokenData.put("unique_id", principalAccessId);
                ssoToken = tokenManager.createSSOToken(tokenData);
            }

            subject.getPrivateCredentials().add(ssoToken);
        } catch (TokenCreationFailedException e) {
            throw new CredentialException(e.getLocalizedMessage());
        }
    }
304057
private static Credential getSigningCredential(final Resource resource) {
        try (val inputStream = resource.getInputStream()) {
            val certificateFactory = CertificateFactory.getInstance("X.509");
            val certificate = (X509Certificate) certificateFactory.generateCertificate(inputStream);
            val publicCredential = new BasicX509Credential(certificate);
            LOGGER.debug("Signing credential key retrieved from [{}].", resource);
            return publicCredential;
        } catch (final Exception ex) {
            LOGGER.error(ex.getMessage(), ex);
        }
        return null;
    }
794641
def _generateForTokenSecurity(self):
        
        agolToken = self._agolSecurityHandler.token
        url = self._url + "/getProxyUserToken"
        params = {"token" : self._agolSecurityHandler.token,
                  "contributorUid" : self._contributionUID}
        res = self._post(url=url, param_dict=params,
                         additional_headers={ "Referer": self._agolSecurityHandler._referer_url},
                         proxy_port=self._proxy_port,
                         proxy_url=self._proxy_url)
        return res['token']
1269120
private static Credential authorize() throws Exception {
    OAuth2ClientCredentials.errorIfNotSpecified();
    // set up authorization code flow
    AuthorizationCodeFlow flow = new AuthorizationCodeFlow.Builder(BearerToken
        .authorizationHeaderAccessMethod(),
        HTTP_TRANSPORT,
        JSON_FACTORY,
        new GenericUrl(TOKEN_SERVER_URL),
        new ClientParametersAuthentication(
            OAuth2ClientCredentials.API_KEY, OAuth2ClientCredentials.API_SECRET),
        OAuth2ClientCredentials.API_KEY,
        AUTHORIZATION_SERVER_URL).setScopes(Arrays.asList(SCOPE))
        .setDataStoreFactory(DATA_STORE_FACTORY).build();
    // authorize
    LocalServerReceiver receiver = new LocalServerReceiver.Builder().setHost(
        OAuth2ClientCredentials.DOMAIN).setPort(OAuth2ClientCredentials.PORT).build();
    return new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");
  }