Simple AngularJS Authentication with JWT

Setting up an Angular App with Login and Registration

Set up a base AngularJS application with an authentication form

Before we dive in, let's start with some scaffolding for our example. Create two new files -- index.html and app.js -- in an empty directory and add the following code:

Create index.html
    <title>Simple Angular Auth</title>
    <script src=""></script>
        <script src="app.js"></script>
    <body ng-app="app" ng-controller="Main as main">
    <h1>Simple Angular Auth - Thinkster</h1>

    <input type="text" ng-model="main.username" placeholder="username"><br>
    <input type="password" ng-model="main.password" placeholder="password"><br>

    <button ng-click="main.register()">Register</button>
    <button ng-click="main.login()">Login</button>
    <button ng-click="main.logout()" ng-show="main.isAuthed()">Logout</button>

    <button ng-click="main.getQuote()">get quote</button>

    <a href="">shameless plug</a>
Create app.js
function authInterceptor(API, auth) {
  return {
    // automatically attach Authorization header
    request: function(config) {
      return config;

    // If a token was sent back, save it
    response: function(res) {
      return res;

function authService($window) {
  var self = this;

  // Add JWT methods here

function userService($http, API, auth) {
  var self = this;
  self.getQuote = function() {
    return $http.get(API + '/auth/quote')

  // add authentication methods here


// We won't touch anything in here
function MainCtrl(user, auth) {
  var self = this;

  function handleRequest(res) {
    var token = ? : null;
    if(token) { console.log('JWT:', token); }
    self.message =;

  self.login = function() {
    user.login(self.username, self.password)
      .then(handleRequest, handleRequest)
  self.register = function() {
    user.register(self.username, self.password)
      .then(handleRequest, handleRequest)
  self.getQuote = function() {
      .then(handleRequest, handleRequest)
  self.logout = function() {
    auth.logout && auth.logout()
  self.isAuthed = function() {
    return auth.isAuthed ? auth.isAuthed() : false

angular.module('app', [])
.factory('authInterceptor', authInterceptor)
.service('user', userService)
.service('auth', authService)
.constant('API', '')
.config(function($httpProvider) {
.controller('Main', MainCtrl)

For simplicities sake we'll be working out of these two files for the remainder of this tutorial.

Because we'll be making cross-origin requests to the test API, make sure you're serving these files from a local webserver and NOT from the file system. I recommend using Browsersync (npm install -g browser-sync)