Custom Authentication with Third-Party Services #
When authenticating users, sometimes their credentials and metadata may be stored in a third-party service. In these situations you can hook in to an existing third-party API to both validate the user and retrieve their metadata. This metadata can then be used to create an associated user in Nakama, effectively linking their external User ID / Username to a Nakama user.
This guide will demonstrate two scenarios in which Nakama’s Custom Authentication feature is used to enable the authentication of users stored in a third-party service.
Bespoke token exchange authentication #
In this example our user’s details are stored in a third-party service that exposes a RESTful API to which we can pass an ID and retrieve user metadata in response. The Nakama server will receive an ID as part of the Custom Authentication flow, pass this along to the third-party API and then extract the user’s ID and username from the response, creating and/or authenticating the Nakama user with this information.
We will achieve this by defining a beforeAuthenticateCustom
hook. The function will use configured runtime environment variables to retrieve the hostname of the third-party API and post the incoming in.Account.Id
to the API for verification. Once done, the new user ID and username will be used to associate the Nakama user with their third-party user account details.
|
|
|
|
The above code (when run against an appropriate third-party API) will create/authenticate a Nakama user given their third-party ID. This ID will be used to retrieve their User ID and Username from the third-party service which will be saved to their Nakama user account. Their third-party User ID will be linked to their Nakama Custom Authentication ID property.
JWT authentication #
JSON Web Tokens (JWTs) are a common way of transmitting user metadata and associated user claims/permissions. These JWTs can be verified by any receiver who knows the secret key used to sign them. This can be extremely useful as it means any service can verify the identity and permissions of a particular user, providing they trust the third-party service that created the JWT.
In this example our beforeAuthenticateCustom
function will received and verify the JWT from the client using a secret key specified in a runtime environment variable. Then extract the claims from the JWT and use it to authenticate the user in Nakama, associating the Nakama user with their third-party user ID and username as before. You can use your favorite JWT library to verify the signature of the JWT as well as extract the data from it’s body. For example, the jwt-go library.
|
|
|
|
As you can see from the two examples above, integrating third-party authentication services with Nakama is a straightforward and highly flexible process that will allow you to successfully authenticate your users in Nakama no matter where their information is stored.