Tutorial: Anonymous login

Step by stepAuthentication Anonymous login

Anonymous login makes it possible to authenticate users for the duration of their session without requiring any credentials. It can be useful to allow a guest user to modify the data s/he created while providing other users read-only access to the same data. Think for example to a blog (with comments) service where users can edit their posts. Another example could be a guest user on a chat service: the user doesn't need to log in, but the service is able to securely identify her/his messages.

A new (temporary) account identifier (uid) is generated when a user authenticates with anonymous login. It remains valid until her/his session ends (as configured in the [[console]]).

Anonymous login usage

To use anonymous login, it must first be enabled in the "authentication" tab of the [[console]].

Then, simply use the following snippet [[snippet]]:

// Create a connection to the back-end
var ref = new Webcom("[[baseUrl]]/base/<your-app>/");
// Log in anonymously
ref.authAnonymously(function(error, auth) {
  if (error == null) {
    console.log("Anonymously logged in with the following identity:" , auth);
  } else {
    console.log("Authentication error: ", error);        
  }
});
Webcom ref = new Webcom("[[baseUrl]]/base/<your-app>/");
final OnAuth listener = new OnAuth(){
    @Override
    public void onComplete(@Nullable AuthResponse authResponse) {
        Log.v(TAG,"onComplete");
        Log.v(TAG,"Anonymously logged in with the account:" + authResponse.getUid());
    }
    @Override
    public void onError(WebcomError webcomError) {
        Log.v(TAG,"onError");
        Log.v(TAG,"Error : " + webcomError.getMessage());
    }
ref.authAnonymously(listener);    
};

The auth parameter received by the authentication callback function is a JSON structure representing the identity used to log in. It doesn't include any specific field in addition to the generic ones (see authentication information details). The provider field here equals "anonymous".

In case of error, the onError method is called with an object describing the root cause of the error. Otherwise, the onComplete method is called with an authResponse representing the generated anonymous identity used to log in.

Security rules

The auth variable in security rules contains no more than the generic provider, providerUid and uid fields (see authentication token details).

Here is a typical example of security rules in the context of anonymous login:

{
  "rules": {
    "users": {
      "$userId":{
        // allow the user itself to edit its own profile
        ".write": "auth !== null && auth.uid === $userId",

        // allow only anonymously authenticated users to read
        ".read": "auth !== null && auth.provider === 'anonymous'"
      }
    }
  }
}