This guide looks at common ways to create the active user within your Kinvey app. We’ll examine several key examples to help you get started.
When you are getting started with Kinvey, generally the first thing you want to do is just grab some data from a collection. You set up your collection, fill it with data and use the default permissions that give all users read capability.
After including the Kinvey HTML5 SDK, you begin writing code like this to pull some data from the collection:
But, lo and behold, rather than data, you get a NoActiveUserError error that says:
There is not an active user. Please login a user and retry the request.
The key thing to remember is that every Kinvey app has an active user—whether that user is explicit (i.e. they logged in with a username/password or social identity) or implicit (i.e. they are effectively “anonymous” users, as I discussed in my recent post).
The goal of this guide is to look at some of the common ways that you create the active user within your Kinvey app. We’ll look at the following examples:
To make all of this easier to understand, I’ve created a simple example app. The example app demonstrates all the topics that we’ll be discussing in this article. It allows the user to continue without logging in (i.e. implicit/anonymous login), to sign up and log in using Kinvey authentication, to sign up or log in using Google authentication, and, finally, to assign themselves a user role.
As a bonus topic, the example even relies upon some simple custom endpoints in Kinvey that we’ll discuss as well.
You can see the code and try the app via the JSFiddle below.
Note that if you want to recreate the project for your own Kinvey instance, replace appKey and appSecret values within the scripts.js file in the GitHub project.
Within Kinvey, the demo app has three collections.
There are also three roles.
Each collection has different permissions that correspond to these roles (i.e. all users can access ordinary-people, heroes can access heroes and villains can access villains), which we’ll discuss in more detail in the roles section below.
In this tutorial, we’ll discuss three types of users:
It’s important to note that there are other types of authentication available in Kinvey such as LDAP or Active Directory that I won’t be covering in this article.
All users (whether implicit, Kinvey, Google) are stored in our users collection in Kinvey, as you can see below.
Since our sample app doesn’t collect any additional user data, you can distinguish between them by the fact that the Kinvey authentication user has a username (in our case, an email), the social authentication user has additional data in the _socialidentity column and the implicit user has neither of those things.
Let’s go back to that collection I showed earlier—the one with the default permissions that give all users read capability. I don’t want anyone to have to log in to view this data. How would we create a user that has access to this data without requiring authentication?
In our example app there is the option to “Continue without signing in” that implements this. Keep in mind that although this is triggered by user interaction in the example, this could also happen transparently (without user interaction)—see my prior post for an example of doing that.
The first thing we have to do, as always, is initialize the Kinvey library.
Now let’s look at what happens when you click the “Continue without signing in” link.
The first two lines of code here essentially just handle transitions and styles. The key portion is this:
Calling the signup() method will create an implicit user and, assuming it is successful, load the data. In this case, we’ll load data from the ordinary-people collection as our implicit user only has the default “All Users” permissions.
Attempting to access data from the heroes or villains collections will result in an InsufficientCredentialsError due to the lack of the proper role.
So I’ll have tons of implicit/anonymous users in my Kinvey users collection?
Yes. The strategy we use above would create a new implicit user for every device or browser. The user ID will be cached in local storage but will be removed whenever we call the Kinvey.User.logout() method (note that this is called on every reload of our sample app, something not recommended for a typical production app). There’s no restriction on the number of users you can create, however it’s something to keep in mind—especially if you plan on manually managing user permissions via the Kinvey Console. An alternative strategy would be to create a service account for your web application and run all anonymous calls through this account
Most applications need some form of user authentication. Of course, you can roll your own, but using the Kinvey authentication can help speed up your development. Let’s look at how.
Our sample app has very simple registration requirements, requiring only a username and password. In most cases, you’ll require more information than this, but the system supports adding any additional user attributes when signing up.
Here’s the basic sign up code from our sample app.
To register a new user, we simply call the same signup() method we used for the implicit user, but this time we are passing a username and password combination. It’s important to note that, for simplicity’s sake since this is a sample app and not a real-world app, we are not doing any client-side validation on the username and password.
In our sample app, we are just passing back any errors we may receive in the sign up process. While this isn’t necessarily recommended for a real application, thankfully the messages are pretty clear. For instance, here’s what happens if I try to register using an email that already exists in the system:
A preferable way of handling this in a real-world application might be to rely upon the built-in username existence check prior to calling the signup() method.
Logging in an already registered user is as easy as passing the username and password to the login() method.
Again, for the sake of simplicity, we are only passing back any login errors we may receive.
You may be wondering what the big deal is? This isn’t difficult to implement on your own. However, now that we have built the sign up and login most applications would require the following additional features:
The good news—as you can see from the links above—is that all of these features are already baked in for you with Kinvey authentication. There’s no need to reinvent the wheel, as they say.
Social identity authentication like those offered by Google, Facebook, Twitter and LinkedIn can be a useful tool to make it easy for users to sign up for your app using an account that they already possess. It can turn the sign up and login process into just one-click—and the easier it is to sign up the less likely users will abandon the process.
Each authentication provider (Google, Facebook, etc) have their own requirements and documentation. On the Kinvey side these are all managed via the Mobile Identity Connect (MIC) service. Let’s look at an example of how to set up MIC to allow us to enable users to sign up and log in using their Google account.
The hardest part about setting up the credentials in Google APIs is knowing where to look—the rest is easy.
Go to the Google API Console. The link you want is the “Credentials” option under “API & Services” in the left-hand menu. On your first visit this may take you to a API Library list (don’t ask me why)—if so, just click back and re-click Credentials link.
Next click the “Create credentials” button, which will reveal a dropdown where you can choose “OAuth client ID”. This will bring you to a page where you can choose the application type. Since our demo app is a web application, choose that option.
You can see an example of my completed Google credentials settings below.
Once you are done, take note of the “Client ID” and “Client secret” (which I have intentionally blurred out) as we’ll need them in an moment.
Now that our Google credentials are all set up, let’s set up Mobile Identity Connect inside the Kinvey Console.
Start by clicking the “Mobile Identity Connect” option under the “Identity” submenu on the left-hand navigation. Next click the button that reads “Add Auth Service” and choose “OAuth2”.
There are a lot of settings on this form, but let’s look at what is relevant to us.
You can see my complete settings below:
Now that we’re set up on Google and Kinvey, let’s look at the code that runs when you click the sign in with Google button on the demo.
Yup, there’s not a lot of code involved. Just call the Kinvey.User.loginWithMIC() method and pass the callback URL. In the demo code we’re just passing the current URL, which just means that we don’t need to change the code from localhost to JSFiddle. Once again, this code just posts the text of the error within the form, but a real-world application would need better error handling should the login fail.
At this point, all of our demo app’s users can log in with Kinvey authentication or Google Sign-In or bypass the login as an anonymous user. Obviously all of our users have the default “All Users” permissions and, by default, collections give “All Users” have some degree read and write permissions. Below are the default collection permissions.
You can read more about the specifics what each of these access types mean, but, for all intents and purposes, by default All users have create and read capability. However, this can be restricted by roles and, obviously, the default All users permissions can be modified or removed.
Roles are easy to create from within the Kinvey Console. Simply click the “Roles” option under the “Identity” sub-navigation, create a new role and give it a name. For example, in our sample app, we have three roles:
You can assign users to roles via the Kinvey Console as well. Open your users collection, select a user and assign roles via the sidebar on the right.
To set permissions for a collection, open the collection’s settings and choose “Permissions”. From here we can remove or change any existing permissions or add permissions for any roles we’ve created. For instance, the Heroes collection in our sample app should only give access to other people who are assigned the role of “Hero”. A “Villain” should obviously be denied access. (We wouldn’t want anyone figuring out the secret identities of our heroes would we?)
Technically, we could get away with not specifically denying the “Villain” role access here since we removed the “All users” permissions—thus any user not in a Hero role would be denied access.
The next step is to allow our users to be assigned to either a hero or villain role (or neither if they choose to bypass the login). Let’s get to coding…
But first, there’s a bit of good news/bad news here.
The net result is that we can definitely do what we want to do here—and it’s not even that difficult. We just have to do it slightly differently than we may have expected.
Kinvey offers multiple options that allow us to customize requests to our backend—from things like collection hooks to Flex Services. Each of these solutions offer the ability to run server-side business logic, but in this case we’ll use custom endpoints that we can call via REST requests.
To do this, click the “Custom Endpoints” option under the “Business Logic” option on the left-hand menu in the Kinvey Console. Click the “Add an Endpoint” button, give it a name (the first one we’ll create is called “addRole”) and, finally, choose the “Code Editor” option before continuing.
This will bring you into the web-based code editor. Here’s the code for our first custom endpoint—we’ll walk through it in a moment.
The first portion sets a ton of variables, so let’s look at the important ones to understand:
Finally, we use the request module to do a PUT request to the REST API to add a role.
The code for our next custom endpoint (deleteRole) to remove a role from a user is nearly identical to the prior code. Can you spot the difference?
The only real difference is that the request is a DELETE request to the REST API so it uses the modules.request.del() method. You may have noticed that the response body of the DELETE request is empty, so we’ve modified that as well.
Let’s look at how we call these custom endpoints in code.
When we click the “I’m a hero” button, we’ll first call the deleteRole endpoint to remove the villain role from the user, if it exists. We invoke the custom endpoint with Kinvey.CustomEndpoint.execute(). We specify the name of the endpoint that we are calling (i.e. deleteRole) and then specify the body (this is where the request.body variables we populate within the custom endpoint code come from). The code for the “I’m a villain” button is basically the same, simply passing different values to add and remove.
Note that instead of hardcoding the role IDs, in a real-world app we might get a list of roles to populate the options. This would also require the help of a custom endpoint as it requires the master credentials as well.
The setRole() method that we call in the above code calls our other custom endpoint (i.e. addRole).
Now that our users can choose a hero or villain role (or choose to remain in the all users role by bypassing the login), we’ll see that when trying to access a collection that they do not have rights to (ex. a villain accessing the heroes collection) causes the request to return an InsufficientCredentialsError denying them access.
Obviously our demo app is intentionally contrived, but hopefully it illustrated some of the core concepts around users within Kinvey. If we wanted to expand upon the authentication, we could add support for logging in via Facebook, LinkedIn or Twitter using Mobile Identity Connect and following a very similar course as we did for Google Log-In. We could also enable people to connect the login to our enterprise authentication using LDAP or Active Directory. The tools are all available to you within Kinvey.
Let our experts teach you how to use Sitefinity's best-in-class features to deliver compelling digital experiences.Learn More
Subscribe to get all the news, info and tutorials you need to build better business apps and sites
You can also ask us not to share your Personal Information to third parties here: Do Not Sell or Share My Info
We see that you have already chosen to receive marketing materials from us. If you wish to change this at any time you may do so by clicking here.
Thank you for your continued interest in Progress. Based on either your previous activity on our websites or our ongoing relationship, we will keep you updated on our products, solutions, services, company news and events. If you decide that you want to be removed from our mailing lists at any time, you can change your contact preferences by clicking here.