Authenticating Users

How did we do?

HiveMP Sessions provides you with a cross-platform way to sign users into your game or application.

Before you can authenticate users, you need to create a project for your game or application, and create a public API key to be used with the PUT /authenticate endpoint.

Creating a project

We'll be creating a new project to use for the rest of this How-to Guide.

  1. Sign into the Admin Console.
  2. Under Projects, click Create Project.
  3. Type a name for your new project in the Name field.
  4. Optionally fill in the Public Name, Developer Name and other fields. You won't be able to set a Website URL until after you've saved the project.
  5. Click Create.
  6. Switch to the new project using the project switcher in the top-right of the Admin Console.

Creating a public API key

  1. Under API Keys, click Create Public API Key.
  2. Type a comment that describes what you'll be using this API key for. For example: "User Authentication for Basic Testing".
  3. Click Create.
  4. In the list of API keys, click Reveal next to the API key you just created and copy the API key.

Creating a session

To authenticate users and create sessions, you'll need to send a request to the PUT /authenticate endpoint with the user's credentials. Sending requests to this endpoint works on all non-web platforms. If your application runs in a web browser, see Authenticating on the Web.

As an example to get started, we can use a provided test account to demonstrate session creation:

read -r -d '' _request_body << EOM
{
  "emailAddress": "[email protected]",
  "marketingPreferenceOptIn": false,
  "metered": true,
  "passwordHash": "e72919d00bd0e67c796192a601d21b805cf92dfe3ecf019be57a182cb320a25a",
  "projectId": null,
  "promptForProject": null,
  "requestedRole": "builtin:user",
  "tokens": {
    "deviceTestTokens": [],
    "discordTokens": [],
    "itchIoTokens": [],
    "oAuthTokens": [],
    "steamTokens": []
  },
  "twoFactor": null
}
EOM
curl -s \
  -H "X-API-Key: $apiKey" \
  -H "Accept: application/json" \
  -H "Content-Type: application/json" \
  --data "$_request_body" \
  -X PUT \
  "https://user-session-api.hivemp.com/v1/authenticate"

After you run the above command, you should receive a new session with a response like this:

{
  "authenticatedSession": {
    "accountId": "u-5705148370255872",
    "apiKey": "...",
    "billedMinutes": 0,
    "expiry": 1533535836,
    "id": "us-...",
    "metered": true,
    "profile": {
      "allowDiscoveryByEmailAddress": false,
      "allowPublicVisibility": false,
      "avatarUrl": null,
      "canSendVerificationEmail": true,
      "descriptionHtml": null,
      "descriptionUnsafeMarkdown": null,
      "displayName": null,
      "emailVerificationPending": true,
      "handle": null,
      "id": "u-5705148370255872",
      "locationCity": null,
      "locationCountry": null,
      "locationState": null,
      "locationText": null,
      "passwordResetPending": false,
      "realName": null,
      "relationship": "self"
    },
    "projectId": "p-...",
    "secretKey": "...",
    "start": 1533532236
  },
  "availableProjects": null,
  "intent": "login",
  "passwordResetEmailSent": false,
  "promptForEmailAddress": false,
  "promptForMarketingPreferenceOptIn": false,
  "promptForPassword": false,
  "promptForProject": false,
  "promptForTwoFactor": false
}

Congratulations! You've just created your first user session in HiveMP. Using the API key provided in the response, you can call other HiveMP APIs.

The request-response model

HiveMP Sessions uses an iterative request-response model for authentication.

That is, you send a request to the authentication endpoint with all of the current information you have, and HiveMP Sessions will either return a new session, or tell you what additional information is required.

If the provided information was enough to create a session, you'll receive the new session in the authenticatedSession field.

If more information is required, one or more of the following fields will be true:

  • promptForEmailAddress
  • promptForPassword
  • promptForMarketingPreferenceOptIn
  • promptForTwoFactor
  • promptForProject

In some circumstances where users have registered using OAuth or implicit tokens, they might not have a password set against their account. If passwordResetEmailSent is true, then HiveMP Sessions has sent an email to the user and they need to follow the instructions in the email to continue logging in.

How to choose: Metered or unmetered?

When you authenticate with HiveMP Sessions, you can choose to create metered or unmetered sessions.

If you don't provide a true or false value for the metered value on the authentication request, then metering depends on the requested role. For user-based roles, sessions are metered by default. For admin-based roles, sessions are unmetered by default.

When sessions are metered, you are billed based on the total number of minutes the session exists.

When sessions are unmetered, you are billed based on API requests or other metrics as outlined in pricing overviews.

Please note that some APIs induce billing on API requests or other metrics even if the session is metered. This is most commonly the case for APIs that are not intended to be used in games (such as our financial and analytical APIs).

When choosing whether or not to use metered sessions, you should consider what the API usage for your game or application will look like. If you're making infrequent API calls after authentication (or only using HiveMP for authentication), it can be cheaper to use unmetered sessions. However, for most games you'll be better off with metered sessions, which offer more predictable and consistent costs.

Implementing a login screen

To authenticate users in your game, you'll need to implement a login screen.

Before you prompt the user with any fields or input, you should make an initial request to the authentication endpoint. In some cases, the SDK will automatically attach implicit tokens to the request, and you'll be able to sign the user in without prompting them at all.

However, if the initial request comes back without a session, you'll need your login screen to be able to ask for following information:

  • Email Address
    • Show only if promptForEmailAddress is true.
  • Password
    • Show only if promptForPassword is true.
    • The input value should be prefixed with HiveMPv1 and hashed with the SHA256 algorithm before sending the hash in lowercase hexadecimal format as passwordHash.
  • Marketing Preference
    • Show only if promptForMarketingPreferenceOptIn is true.
    • Instead of showing a field for this value, you can always provide a value of false for marketingPreferenceOptIn in requests.
    • Otherwise, this field should be represented as a checkbox with the label "Allow to send you emails with news and announcements". The field must be unchecked by default.
  • Two-Factor Code
    • Show only if promptForTwoFactor is true.

If your requesting administrative sessions in your application, you might also need to handle the following field:

  • Project
    • Show only if promptForProject is true.
    • This should be shown as a dropdown or select field populated by availableProjects in the previous response. The ID of the project should then be sent as projectId in the next request.

Your login screen should present the fields as indicated, and provide a Submit or Login button the user can use to indicate that the next authentication request should be sent.

You can improve the usability of your login screen by allowing the Enter key to submit the authentication request, and the Tab key to move to the next field. When an authentication response comes back and an input field is shown for the first time (i.e. the corresponding prompt... field becomes true where it was previously false), you can focus the new input field.

Working with implicit tokens

Platforms such as Steam and itch.io provide games with "implicit tokens". These tokens are provided by the platform and can be used to authenticate users without requiring user interaction.

Implicit tokens are passed in the tokens field in the authentication request.

Each platform provides implicit tokens in a different way, and some require configuration in the Admin Console first before they can be used.

The HiveMP SDK automatically obtains implicit tokens and sends them along with authentication requests. This is why you should send an initial authentication request before presenting a login screen with input fields; HiveMP can automatically sign users in with implicit tokens without requiring input.

Working with OAuth flows

You can enable users to sign into HiveMP Sessions through OAuth servers, such as those provided by Discord and Twitch, using HiveMP Sessions "OAuth flows".

To use OAuth flows, you need to be able to embed a web browser in your game or application, or be comfortable launching a web browser in a separate window as part of the login process.

The steps required to use OAuth flows in your game or application are as follows:

  • Create a flow session with the PUT /flowSession endpoint.
  • Obtain the URL to show in the embedded or external web browser with the GET /startingUrl endpoint. This requires an OAuth provider name to be passed; you can obtain a list of available OAuth providers with the GET /providers endpoint.
  • Show the URL in a web view to the user. While the web view is shown, periodically poll the GET /flowSession/status endpoint to detect when the user has completed the authentication flow.
  • If the flow session is in a non-error status, attach the flow session ID as part of tokens to the next authentication request you send to HiveMP Sessions.

Renewing a session

HiveMP sessions automatically expire 60 minutes after they were created, or 60 minutes after they were last renewed. Sessions require explicit renewal to prevent metered sessions being left open and inducing billing costs.

In your game or application, you should renew the sessions when there's less than 30 minutes left for the session. Periodically check the expiry value of the session, and if it needs renewal, send a request with the session's API key such as the following:

curl -s \
  -H "X-API-Key: $apiKey" \
  -H "Accept: application/json" \
  -H "Content-Length: 0" \
  -X POST \
  "https://user-session-api.hivemp.com/v1/session"\
"?id=us-5705148370255872"

Deleting a session

For metered sessions, HiveMP bills based on the number of minutes elapsed between the it's creation and when it expired or was deleted.

You can reduce your costs by explicitly deleting a session when your game or application exits instead of letting the session naturally expiring:

curl -s \
  -H "X-API-Key: $apiKey" \
  -H "Accept: application/json" \
  -H "Content-Length: 0" \
  -X DELETE \
  "https://user-session-api.hivemp.com/v1/session"\
"?id=us-5705148370255872"