Generates a new JWT token.
@param user a User object belonging to the app
@param app the app object
@return a new JWT or null
974478
public static SignedJWT generateJWToken(User user, App app) {
		if (app != null) {
			try {
				Date now = new Date();
				JWTClaimsSet.Builder claimsSet = new JWTClaimsSet.Builder();
				String userSecret = "";
				claimsSet.issueTime(now);
				claimsSet.expirationTime(new Date(now.getTime() + (app.getTokenValiditySec() * 1000)));
				claimsSet.notBeforeTime(now);
				claimsSet.claim("refresh", getNextRefresh(app.getTokenValiditySec()));
				claimsSet.claim(Config._APPID, app.getId());
				if (user != null) {
					claimsSet.subject(user.getId());
					userSecret = user.getTokenSecret();
				}
				JWSSigner signer = new MACSigner(app.getSecret() + userSecret);
				SignedJWT signedJWT = new SignedJWT(new JWSHeader(JWSAlgorithm.HS256), claimsSet.build());
				signedJWT.sign(signer);
				return signedJWT;
			} catch (JOSEException e) {
				logger.warn("Unable to sign JWT: {}.", e.getMessage());
			}
		}
		return null;
	}
516724
private static HttpRequest createTokenVerificationRequest(String apptentiveAppKey, String apptentiveAppSignature, String token, HttpRequest.Listener<HttpJsonRequest> listener) {
		// TODO: move this logic to ApptentiveHttpClient
		String URL = Constants.CONFIG_DEFAULT_SERVER_URL + "/debug_token/verify";
		HttpRequest request = new HttpJsonRequest(URL, createVerityRequestObject(token));
		request.setTag(TAG_VERIFICATION_REQUEST);
		request.setMethod(HttpRequestMethod.POST);
		request.setRequestManager(HttpRequestManager.sharedManager());
		request.setRequestProperty("X-API-Version", Constants.API_VERSION);
		request.setRequestProperty("APPTENTIVE-KEY", apptentiveAppKey);
		request.setRequestProperty("APPTENTIVE-SIGNATURE", apptentiveAppSignature);
		request.setRequestProperty("Content-Type", "application/json");
		request.setRequestProperty("Accept", "application/json");
		request.setRequestProperty("User-Agent", String.format(USER_AGENT_STRING, Constants.getApptentiveSdkVersion()));
		request.setRetryPolicy(createVerityRequestRetryPolicy());
		request.addListener(listener);
		return request;
	}
890792
def create_token(self, user):
        
        # The password is expected to be a secure hash but we hash it again
        # for additional safety. We default to MD5 to minimize the length of
        # the token. (Remember, if an attacker obtains the URL, he can already
        # log in. This isn't high security.)
        h = crypto.pbkdf2(
            self.get_revocation_key(user),
            self.salt,
            self.iterations,
            digest=self.digest,
        )
        return self.sign(self.packer.pack_pk(user.pk) + h)
504489
private static Token<EsTokenIdentifier> getAuthToken(ClusterName clusterName, User user) {
        EsToken esToken = getEsAuthToken(clusterName, user);
        if (esToken == null) {
            return null;
        } else {
            return EsTokenIdentifier.createTokenFrom(esToken);
        }
    }
933443
@SuppressWarnings("deprecation")
  private Credential newCredential(String userId) {
    Credential.Builder builder = new Credential.Builder(method).setTransport(transport)
        .setJsonFactory(jsonFactory)
        .setTokenServerEncodedUrl(tokenServerEncodedUrl)
        .setClientAuthentication(clientAuthentication)
        .setRequestInitializer(requestInitializer)
        .setClock(clock);
    if (credentialDataStore != null) {
      builder.addRefreshListener(
          new DataStoreCredentialRefreshListener(userId, credentialDataStore));
    } else if (credentialStore != null) {
      builder.addRefreshListener(new CredentialStoreRefreshListener(userId, credentialStore));
    }
    builder.getRefreshListeners().addAll(refreshListeners);
    return builder.build();
  }
1306709
@Beta
  public GoogleCredential createDelegated(String user) {
    if (serviceAccountPrivateKey == null) {
      return this;
    }
    return toBuilder()
        .setServiceAccountUser(user)
        .build();
  }
575176
@Override
    public User createUser(User user) throws UnauthorizedException, NameConflictException {
        try {
            return userDao.createUser(user);
        } catch (DuplicateKeyException e) {
            throw new NameConflictException("User name is already in use", e);
        }
    }
704554
public JwtToken build(JwtAuth userDetails) {
        Date expireTime = generateExpirationDate();
        Map<String, Object> claims = new HashMap<>(16);
        claims.put(CLAIM_KEY_LOGIN_NAME, userDetails.getLoginName());
        claims.put(CLAIM_KEY_ID, userDetails.getId());
        claims.put(CLAIM_KEY_MICK_NAME, userDetails.getNickName());
        claims.put(CLAIM_KEY_CREATED, expireTime.getTime());
        claims.put(CLAIM_KEY_ROLE, userDetails.getRoles());
        claims.put(CLAIM_KEY_AVATAR,userDetails.getAvatar());
        return new JwtToken(build(claims, expireTime), expireTime.getTime());
    }
359812
function login(updatedUser, jwt) {
        storage.set('jwt', 'Bearer ' + jwt);    // set the token in local storage
        removeUserVals();                       // remove old user values
        _.extend(user, updatedUser);            // add new user values
        eventBus.emit('user.init');             // let everyone else know there is a new user in town
    }
1138236
@Override
	public Response createApplication( Application app ) {

		this.logger.fine( "Request: create application " + app + "." );
		Response result;
		try {
			String tplName = app.getTemplate() == null ? null : app.getTemplate().getName();
			String tplQualifier = app.getTemplate() == null ? null : app.getTemplate().getVersion();
			String appName = app.getDisplayName() != null ? app.getDisplayName() : app.getName();
			ManagedApplication ma = this.manager.applicationMngr().createApplication( appName, app.getDescription(), tplName, tplQualifier );
			result = Response.ok().entity( ma.getApplication()).build();

		} catch( InvalidApplicationException e ) {
			result = handleError(
					Status.NOT_FOUND,
					new RestError( REST_MNGMT_INVALID_TPL, e, application( app )),
					lang( this.manager )).build();

		} catch( AlreadyExistingException e ) {
			result = handleError(
					Status.FORBIDDEN,
					new RestError( REST_MNGMT_CONFLICT, e, application( app )),
					lang( this.manager )).build();

		} catch( IOException e ) {
			result = handleError(
					Status.UNAUTHORIZED,
					new RestError( REST_SAVE_ERROR, e, application( app )),
					lang( this.manager )).build();
		}

		return result;
	}
233795
protected UserApiKey createApiKeyInternal(final String name) {
    final StitchAuthDocRequest.Builder reqBuilder = new StitchAuthDocRequest.Builder();
    reqBuilder
            .withMethod(Method.POST)
            .withPath(this.getBaseRoute())
            .withDocument(new Document(ApiKeyFields.NAME, name))
            .withRefreshToken();
    return getRequestClient().doAuthenticatedRequest(
            reqBuilder.build(),
            new UserApiKeyDecoder()
    );
  }
726068
public void updateUser(User user){
        ProtocolHeader header = new ProtocolHeader();
        header.setType(ProtocolType.UpdateUser);

        UpdateUserProtocol p = new UpdateUserProtocol(user);

        connection.submitRequest(header, p, null);
    }
1181716
@Override
	// @FFDCIgnore(Exception.class)
	public void createJwtSSOToken(Subject subject) throws WSLoginFailedException {
		// TODO Auto-generated method stub
		if (subject != null) {
			if (isSubjectUnauthenticated(subject) || subjectHasJwtPrincipal(subject)) {
				return;
			}
			JwtSsoTokenUtils tokenUtil = getJwtSsoTokenBuilderUtils();
			if (tokenUtil != null) {
				JsonWebToken ssotoken = null;
				try {
					ssotoken = tokenUtil.buildTokenFromSecuritySubject(subject);
				} catch (Exception e) {
					// TODO ffdc
					throw new WSLoginFailedException(e.getLocalizedMessage());
				}
				updateSubject(subject, ssotoken);
			} else {
				String msg = Tr.formatMessage(tc, "JWTSSO_CONFIG_INVALID", new Object[] {});				
				throw new WSLoginFailedException(msg);
			}
		}
	}
1373040
public function authenticateToken(TokenInterface $token, UserProviderInterface $userProvider, $providerKey)
    {
        // The user provider should implement JWTUserProviderInterface
        if (!$userProvider instanceof JWTUserProviderInterface) {
            throw new InvalidArgumentException('Argument must implement interface Auth0\JWTAuthBundle\Security\Core\JWTUserProviderInterface');
        }

        if ($token->getCredentials() === null) {
            $user = $userProvider->getAnonymousUser();
        } else {
            // Get the user for the injected UserProvider
            $user = $userProvider->loadUserByJWT($token->getCredentials());

            if (!$user) {
                throw new AuthenticationException(sprintf('Invalid JWT.'));
            }
        }

        return new PreAuthenticatedToken(
            $user,
            $token,
            $providerKey,
            $user->getRoles()
        );
    }
563682
private function generateTokenForUser(UserInterface $user)
    {
        // if a token was already requested within the request interval time frame
        if (null !== $user->getPasswordResetToken()
            && $this->dateIsInRequestFrame($user->getPasswordResetTokenExpiresAt())) {
            throw new TokenAlreadyRequestedException(self::getRequestInterval());
        }
        $em = $this->getDoctrine()->getManager();

        $user->setPasswordResetToken($this->getToken());
        $expireDateTime = (new \DateTime())->add(self::getResetInterval());
        $user->setPasswordResetTokenExpiresAt($expireDateTime);
        $user->setPasswordResetTokenEmailsSent(0);

        $em->persist($user);
        $em->flush();
    }
648258
def create_token(self, request, refresh_token=False):
        """"""

        if callable(self.expires_in):
            expires_in = self.expires_in(request)
        else:
            expires_in = self.expires_in

        request.expires_in = expires_in

        return self.request_validator.get_jwt_bearer_token(None, None, request)
639276
@Override
    public Builder create() throws InvalidBuilderException {
        if (!active) {
            // Tr.error(tc, "JWT_BUILDER_NOT_ACTIVE", new Object[] {
            // "defaultJWT" });
            // return null;
            String err = Tr.formatMessage(tc, "JWT_BUILDER_NOT_ACTIVE", new Object[] { "defaultJWT" });
            throw new InvalidBuilderException(err);
        }
        return create("defaultJWT");
    }