Custom Authentication

By default, all applications allow anonymous users to connect and do not have any authentication mechanism. Photon provides the option to implement custom authentication for Photon applications.

Custom Authentication with Photon is flexible. It supports well known third-party authentication providers as well as fully personalized solutions for that matter.

  • Facebook Authentication Provider, hosted by Exit Games. Check out the tutorial
  • Custom Authentication Provider, built - and maybe hosted by you. We provide sample implementations of authentication providers via a Git repository. Feel free to fork the repository and send us your pull requests. You find the sources on GitHub.

Content

Authentication Flow

The following steps describe the general flow of the authentication process.

Photon Cloud: Custom Authentication Flow Diagram
Custom authentication flow diagram

  1. Your client passes info about which authentication provider to use and the necessary authentication data to the Photon server with Connect().
  2. The Photon server gets the desired authentication provider for your application and takes one of these steps
    • The authentication provider configuration is found -> the authentication proceeds with step 3.
    • The authentication provider configuration is not found -> the client will be either allowed to connect or rejected, depending on a setting of your application
  3. The Photon server calls the authentication provider with the authentication info passed with Connect().
    • The authentication provider is online -> the authentication proceeds with step 4.
    • The authentication provider is offline -> the client will be either allowed to connect or rejected, depending on the corresponding provider setting.
  4. The authentication provider processes the authentication information and returns the result to the Photon Server
  5. Depending on the authentication result, the client will be either successfully authenticated or rejected

Setup for Photon Cloud

You can setup all authentication providers from your Photon Applications' Dashboard. Go to the details page of an application and open the custom authentication section.

When configuring custom authentication, keep in mind that changes may take a moment to propagate.

Add an Authentication Provider

Configuring a custom authentication provider is easy and it could be done in few seconds from your Photon Applications' Dashboard.

Photon Cloud: Custom Authentication Creation
Creating a custom authentication provider

As shown in the screenshot, you can enter your authentication URL and decide, whether clients should be rejected if your authentication service is not online or not working for any other reason. In addition, you can optionally add key/value pairs that will be sent to the authentication service with each request as query string parameters.

A best practice is to set from the dashboard only "sensitive" and static key/value pairs that should be "invisible" to the client. Examples:
  • API public key to make sure that the request is really coming from one of Photon servers.
  • API version of custom authentication to better handle future changes.

Also, there is a possibility to allow or reject anonymous clients that try to connect to your application, regardless of any configured authentication providers. By default this is enabled, meaning initially all clients are authorized to connect to your application whether authenticated or not. You can check this in the authentication section on the application details page from your Photon Applications' Dashboard.

Photon Cloud: Custom Authentication, Allow Anonymous Clients
Allow Anonymous Clients Using Custom Authentication

Update or Delete an Authentication Provider

Also from the application details page you can select to edit an existing authentication provider. On the edit form, you can update all settings or delete the authentication provider altogether.

Photon Cloud: Custom Authentication Editing
Updating or deleting an existing custom authentication provider

Implementation

If you use facebook authentication with Photon Cloud you can skip this part.

Client Side

On the client side, the LoadBalancing API will handle custom authentication - you only set the relevant parameters and the target custom authentication service once. Once setup, connect and handle eventual errors.

The Custom Authentication values are part of the LoadBalancingClient. Create and set AuthValues like this:

In this snippet, to simplify things we chose a very basic password based authentication credentials. This will result in the following query string: ?user={user}&pass={pass}. Generally those credentials are a pair of values, the first value is a unique identifier (userId, username, e-mail, etc.) and the other one is "a proof of authenticity" (hashed password, key, secret, token, etc.). For security reasons it is not recommended to send plain text passwords.

If the authentication fails, you get disconnected with LoadBalancingClient.DisconnectedCause set to DisconnectCause.CustomAuthenticationFailed. In this case, please make sure to handle each failure cause separately according to the OperationResponse.ReturnCode in the OnOperationResponse callback. The expected values are discussed in the server part.

Authenticate Operation

The Authenticate operation is where the authentication values are actually sent to the server. It's usually used by our APIs and not by your client code directly.

What's important to notice is: Connecting to a server always includes an authentication step. The first time, the operation sends the actual authentication values as encrypted operation. For subsequent server switches, Photon provides it's own Token, which is encrypted and used automatically.

The LoadBalancing API handles this workflow for you. However, in case of authentication failure client is switched to a disconnected state with the proper DisconnectCause.

Server Side

Once the web server receives the authentication request, the query parameters should be checked and validated. As an example, credentials could be compared to existing ones stored in a database.

If the received parameters are missing or are invalid the returned results should be {'ResultCode': 3}

After finishing the validation the outcome should be returned as follow:

  • Success: {'ResultCode': 1, 'UserId': <userId>}
  • Failure: {'ResultCode': 2}

Advanced Features

Other than authenticating users, extra information can be returned from the authentication provider. In order to do so, the user should establish some kind of protocol between client and the web service who plays the role of the "authenticator".

Sending Data to Server

The easiest and simplest thing to do is an "all or nothing" strategy: chose whether or not to return a static number of variables to the client. But some use cases require a more complex approach where the web service returns data "on-demand" based on what the client has requested. This subsection explains how the client can send data to the web service. The data can be the credentials necessary for authentication plus any extra parameters. The extra parameters are what could be used, among other things, to request piece of data available from server side to be returned within the authentication response. This is pretty useful as it saves extra API calls and simplifies the login workflow.

The default HTTP method used in authentication is GET. So, parameters can be sent as key/value pairs in the query string. The final URL will include the "union" of the key/value pairs set from client and those set from the dashboard. In case, a key is used in both places, this will result in an unpredictable behavior depending on the web server used. That is why, a best practice is to set from the dashboard any "sensitive" static values that should be "invisible" to the client; e.g.: API key, API version.

In some rare cases, authentication may require a lot of data, a really very heavy payload. On the other hand, most web servers have a limit for the number of characters used in the query string or a threshold for the length of the URL. That is why Photon offers the possibility of changing the HTTP method to POST from the client by explicitly setting the AuthenticationValues.AuthPostData field to a value. The latter can be of type string or byte[]. The AuthenticationValues class offers respectively two setters per type.

Since this could be a requirement or a constraint, the POST method option is also available for anyone who opts for receiving authentication requests as POST method from web service.

In other words, to send authentication parameters you are free to use query string or POST data or both. The following table gives the possible combinations.

AuthPostData AuthGetParameters HTTP method
null * GET
empty string * GET
string (not null, not empty) * POST
byte[] (not null, can be empty) * POST

Returning Data to Client

Since Photon server is a proxy between the client and the web service, you should take note of the variables that could be handled by Photon servers.

Like all HTTP incoming responses received by Photon server, the web server should return a JSON object that includes a ResultCode and an optional Message. Additionally, here is a list of what Photon servers can expect from the web service during authentication.

  • UserId: this could be used as a parameter of the authentication itself or it could be requested from client side. This is always forwarded to the client when received by Photon servers. Otherwise, if AuthenticationValues.UserId was not initially set a randomly generated UserId will be sent back to client. This will override the value of UserId in client and cannot be changed after that.
  • Nickname: this could be used as a parameter of the authentication itself or it could be requested from client side. When returned from web service this will override the value of Nickname in client. The Nickname can still be updated after that from client side.
  • AuthCookie: also called secure data, is a JSON object returned by the web service but will not be accessible from client side as it will be embedded in the encrypted token received. It could be sent later with Webhook or WebRPC HTTP requests.
  • Data: JSON object that contains any extra values that should be returned to the client. Please keep in mind that nested arrays or objects are not supported.

The ResultCode is the only required return variable, anything else is optional. The following table summarizes what could be returned by the web server.

ResultCode Description UserId Nickname Data AuthCookie
0 Authentication incomplete, only Data returned.* x x x
1 Authentication successful. ✓ (optional) ✓ (optional) ✓ (optional) ✓ (optional)
2 Authentication failed. Wrong credentials. x x x x
3 Invalid parameters. x x x x

*: This may be useful for implementing OAuth 2.0 for instance or two-step verification.

Reading Data from Client

Here is a code snippet of how to get the returned values from the response:

Data Types Conversion

In this section, only the type of data exchanged between Photon server and the web service is explained. For more information about data types between clients and Photon servers please refer to serialization in Photon page.

Photon Server -> Web Service

C# / .Net (Photon supported types) JavaScript / JSON
byte number
short
int
long
double
bool bool
string string
byte array (length < short.MaxValue) string (Base64 encoded)
array ([] of supported type, length < short.MaxValue) array
Hashtable (of supported types, count < short.MaxValue, preferably Photon implementation) object
Dictionary (keys and values of supported types, count < short.MaxValue) object
null null

Sample request data (types are concatenated)

As sent from Photon Server:

As read by Web Service:

Web Service -> Photon Server

Here is a table that matches each JavaScript/JSON type to its equivalent one in C#/.Net :

JavaScript / JSON C# / .Net
object Dictionary<string, object>
array object[]
number (integral) long
number (floating) double
string string
boolean bool
null (not a type) null
undefined (when sent) null

Sample response data (types are concatenated)

As sent from Web Service:

As read from Photon Server:

Troubleshooting

The following ReturnCode values represent respective authentication operation failures.

  • ErrorCode.InternalServerError = -1: This is probably caused by a problem parsing data received by Photon servers. Make sure you are using the allowed data types.
  • ErrorCode.CustomAuthenticationFailed = 32755: Check the OperationResponse.DebugMessage. Possible causes are the web server not reachable, returned a ResultCode other than 0 or 1 or the returned response indicates HTTP error code.

In case the authentication URL you configured in your dashboard returns some HTTP error, the Photon server pauses the authentication calls for a short time to avoid some overhead. Take this "backoff" time into consideration when configuring or testing your URLs.

Best Practices

  • From dashboard, set static key/value pairs that should not be set from client side. This will prevent duplicate keys in the resulting query string.
  • For security reasons, do not send plain text passwords as authentication parameter.
  • It is recommended to set query string parameters from Photon dashboard. That way you can check the origin of the request.
  • Make use of the AuthenticationValues methods to set parameters and do not affect a value directly to AuthGetParameters. This will prevent malformed query string.
  • The returned result from the authentication provider should contain a readable Message especially in case of failure. This will save you a lot of debugging pain.

Use Case Example: Block Old Client Versions

You can use custom authentication to refuse connections incoming from clients using old versions (or unexpected versions) and return a specific error so you can ask the user to update. To do this you need to send the version in the custom authentication request. It is up to you to decide if you want to do it as query string parameter or a POST data argument. In the example below we will use query string parameter:

If your custom authentication URL is https://example.com then the request will be sent as https://example.com?version={version}. From your authentication provider implementation you should get and compare the version received. If the version is allowed return {ResultCode:1}. If not you should return a ResultCode with a custom value of your choice (different than 1), preferably with a message. Example: {ResultCode:5, Message: 'Version not allowed.'}.

 To Document Top