The Techies' pub

Angular 2 – Authentication

Hope you are all well. This post is a response to several people asking me how to implement authentication in an angular 2 app. To answer you guys its simple and in this post I will show you exactly how to do it.

Prerequisites:

Please clone my ionic-authentication backend repo from here. We will be using this backend written in nodejs and uses express and mongoose(for connecting with the db).

Here I have a publicRoutes variable in which I am storing the routes that don’t require authentication. In our case only login.

Then I have an activate method which first checks the url. If the url is not present in the public routes and if there is no local storage item with the key (‘auth_key) then it simply redirects the user back to login page.

If the url is not present in the public route and there exists an item in the localStorage with the authkey then the navigation happens., i.e., the user is authenticated.

Save the file and try navigating to dashboard now. You will see that you are redirected back to the login page.

This is how authentication can be done in angular2 apps. For a tutorial on how to do it in mobile apps please click here.