Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sean-hill/e2315762fdfb0d311547 to your computer and use it in GitHub Desktop.
Save sean-hill/e2315762fdfb0d311547 to your computer and use it in GitHub Desktop.
Auth Token Interceptor Service for AngularJS and Passport HTTP Bearer Strategy
angular.module('your-app')
.config(function($httpProvider){
$httpProvider.interceptors.push('AuthTokenInterceptor');
})
Auth Token Interceptor Service for AngularJS and Passport HTTP Bearer Strategy
.factory('AuthTokenInterceptor', function ($q, Storage) {
return {
request: function (config) {
var authToken = Storage.get("authToken");
config.headers = config.headers || {};
if (authToken) {
config.headers.Authorization = 'Bearer ' + authToken;
}
return config || $q.when(config);
}
};
})
// Used when an auth token is required for a route
var passport = require("passport");
var path = require('path');
var BearerStrategy = require("passport-http-bearer").Strategy;
var User = require('./models/user-model');
// Use Bearer Strategy as authentication
passport.use(new BearerStrategy(
function(token, done) {
User.findOne({ authToken: token }, function (err, user) {
if (err) { return done(err); }
if (!user) { return done(null, false); }
return done(null, user, { scope: 'all' });
});
}
));
module.exports = {
protect: passport.authenticate('bearer', { session: false })
}
// User Api
var express = require('express');
var userApi = express.Router();
var userRoute = require('./routes/user/base-user-route');
var RouteAuth = require('./util/route-auth');
userApi.post('/update-something', RouteAuth.protect, userRoute.updateSomething);
module.exports = userApi;
@sean-hill
Copy link
Author

Integration into an Ionic / NodeJS project can be found here. Happy coding 😄

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment