I assume you have:
angular app placed in a different repo/directory than your backend API,
no devise gem in your Gemfile yet (devise_token_auth have it as a dependency),
Rails app created using rails new generator.
What You Will Use:
Devise_token_auth gem - Rails side authentication,
Ng-token-auth library - Angular side authentication,
Rack-cors gem - Cross-Origin Resource Sharing.
easy to use,
not a custom solution - it’s always the same,
allows OmniAuth authentication.
- some edge cases can be harder to handle because of the library choice.
Add the following gems to your Gemfile on the backend side:
And run bundle install.
Setup User model using:
$ rails g devise_token_auth:install User api/auth
This will create:
A basic user model with a corresponding migration (you should check both the migration and the model to remove/rename stuff you don't need).
Routes for authentication controllers where the angular library will make its calls.
Setup CORS in config/application.rb:
IMPORTANT: Those are the settings for dev environment!
For production and staging environments, you should change them to be more restricting (point origins to the frontend address and limit the resource access).
This is most of the stuff you need to do on the backend side. Of course, there may be some more things to configure, e.g. setting protect_from_forgery :null_session for XHR requests. It depends on the architecture you'll implement - most likely, it should be for API::BaseController.
On the angular side (if you don't have a frontend app yet, using generator-gulp-angular is not a bad choice), you need to install ng-token-auth. This tutorial expects you to use Bower, and if you do, all you have to do is run:
$ bower install --save ng-token-auth
This will install the library and save it as a dependency in bower.json file inside your project.
Now, angular needs to know to use ng-token-auth in your application, so you have to add it as a dependency for the angular module.
Next, you need to configure ng-token-auth by calling .config() on the module. There are many options you can adjust there, so I highly advise you to check out the documentation. Here's an example of a simple configuration where you only change API url to where the angular app will make its calls:
apiUrl points to your localhost rails server. Normally, this variable should be put inside a config file, but - for the sake of simplicity - in this tutorial, we will just leave it like that.
Since you configured your library to make requests to the proper URL, you can finally use it in the app. All available methods can be found in ng-token-auth documentation.
During this tutorial you have learned:
how to setup rails for authentication using devise_token_auth gem,
how to setup CORS for requests to the backend,
how to setup angular app to handle authentication with a backend server using tokens.
Thanks for reading and happy coding!