Many people ask about how to authenticate users with Angular and DreamFactory’s user management REST API.
One easy way to do this (as well as user registration) is to use our Angular module on GitHub. There’s also a three-part tutorial below about how to use the module:
- The Authenticated App With AngularJS + DreamFactory User Management Part One
- The Authenticated App With AngularJS + DreamFactory User Management Part Two
- The Authenticated App With AngularJS + DreamFactory User Management Part Three
You don’t have to use this module though. Logging users in with an Angular app is pretty straightforward.
First, make sure to set your API key in your app.js file. The API key is just the name of the app you’ve created in DreamFactory (so DreamFactory knows whether the user logging in has permission to access the app).
angular.module(‘yourAwesomeApp', [])
// set a constant
.constant(‘DSP_API_KEY’, YOUR_APP_NAME_HERE)
// Create a config block. Inject $httpProvider. Set default header for $http service calls
.config(['$httpProvider', 'DSP_API_KEY', function ($httpProvider, DSP_API_KEY) {
// Set default headers for http requests
$httpProvider.defaults.headers.common["X-DreamFactory-Application-Name"] = DSP_API_KEY;
}])
Then create controllers for login and logout. The session header we set for Angular’s $http will persist for all calls until we delete on logout.
// Store user info from html form
scope.email = USER_EMAIL;
scope.password = USER_PASSWORD;
// This function makes the login request
scope.getSession = function (emailStr, passwordStr) {
return $http({
method: “POST”,
url: https://YOUR_DSP_URL/rest/user/session,
data: {
email: emailStr
password: passwordStr
}
});
}
// This function makes the logout request
scope.deleteSession = function () {
return $http({
method: “DELETE”,
url: https://YOUR_DSP_URL/rest/user/session
});
}
// attach this to a UI button or form submit
scope.login = function () {
// Call our login function and handle its returned promise
scope.getSession(scope.email, scope.password).then(
// Handle successful login
function (result) {
// set header for future $http service calls to dreamfactory
$http.defaults.headers.common[‘X-DreamFactory-Session-Token’] = result.data.session_id;
// Do whatever else you want to do for app setup after login
},
// handle login failure
function (reject) {
throw reject;
});
}
// handle logout
scope.logout = function () {
// Call delete function and handle response
scope.deleteSession().then(
// handle success
function(result) {
// Don’t forget to delete the session header on logout!
$http.defaults.headers.common[‘X-DreamFactory-Session-Header’] = '';
},
// handle failure
function(reject) {
throw reject;
})
}
Then just invoke your login and logout methods from your login and logout buttons in your html.
// Login & Logout buttons html
<button type=“button” data-ng-click=“login()”>Login Button</button>
<button type=“button” data-ng-click=“logout()”>Logout Button</button>