Basic authentification with AngularJs and Laravel
Written by Bastien Donjon, Posted in Javascript, PHP
Here’s a simple solution to install basic authentication system with AngularJs.
This is a subject that is not much developed. Probably because of the different authentication methods and functional needs.
For me I needed:
– Authentication Required
– To authenticate the user on my RESTful API
– Not to send the user name and password to each request
– Not to make cross-domain
– To have a persistent connection (F5 or close browser window)
– To block access to the application if the authentication server is lost
Laravel configuration
route.php
1234567891011121314151617181920212223// Route with basic authentification and custom method
Route::group(
[
'before'
=>
'auth.basicCustom'
],
function
() {
// User authenticate with sesssion
Route::post(
'authenticate'
,
function
(){
echo
'ok'
;
});
}
);
// Logout current user
Route::get(
'/logout'
,
function
(){
Auth::logout();
});
// Check state of current user authentification
Route::get(
'/guest'
,
function
(){
if
(Auth::guest()){
throw
new
\Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException(
'x-Basic'
)
}
else
{
echo
'ok'
;
}
});
filters.php
1234567891011Route::filter(
'auth.basicCustom'
,
function
() {
$credentials
= [
'email'
=> Request::getUser(),
'password'
=> Request::getPassword() ];
if
(!Auth::check()) {
if
(!Auth::once(
$credentials
)) {
throw
new
\Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException(
'x-Basic'
);
}
}
}
);
Configuration AngularJs
app.js
12345678910111213angular.module(
'App'
, [
'LocalStorageModule'
,
'authServices'
])
.config([
'$httpProvider'
,
function
($httpProvider) {
/* -- Add your routes or states -- */
// Authentification provider
$httpProvider.interceptors.push(
'authInterceptor'
);
}]);
authInterceptor.js
123456789101112131415161718192021222324252627282930313233343536373839404142434445'use strict'
;
/**
* Authentification Services
*/
angular.module(
'authServices'
, [])
/**
* Add callback after/befor http request
*/
.factory(
'authInterceptor'
, [
'$rootScope'
,
'$q'
,
'$window'
,
'localStorageService'
,
function
($rootScope, $q, $window, localStorageService) {
return
{
/**
* Before request
* @param config
* @returns {*}
*/
request:
function
(config) {
config.headers = config.headers || {};
return
config;
},
/**
* After success request
* @param response
* @returns {*|Promise}
*/
response:
function
(response) {
return
response || $q.when(response);
},
/**
* After error request
* @param rejection
* @returns {Promise}
*/
responseError:
function
(rejection) {
localStorageService.add(
'authenticate'
,
false
);
$rootScope.authenticate =
false
;
return
$q.reject(rejection);
}
};
}]);
userController.js
123456789101112131415161718192021222324angular.module(
'App'
)
.controller(
'UserCtrl'
, [
'$rootScope'
,
'$scope'
,
'$http'
,
'$window'
,
'localStorageService'
,
function
($rootScope, $scope, $http, $window, localStorageService) {
$scope.submit =
function
() {
$http
.post(
'/api/authenticate'
, {}, {
// Forcage du type d'authentification
headers: {
Authorization : 'Basic
' + btoa($scope.user.username + ":" + $scope.user.password)
}
})
.success(function (data, status, headers, config) {
localStorageService.add('
authenticate
', true);
$rootScope.authenticate = true;
// Suppression des informations utilisation pour ne pas les garder en claire dans le scope
delete $scope.user;
})
.error(function (data, status, headers, config) {
localStorageService.add('
authenticate',
false
);
$rootScope.authenticate =
false
;
});
};
}]);
directives.js
123456789'use strict'
;
angular.module(
'App'
)
.directive(
'ngLogin'
,
function
() {
return
{
restrict:
'E'
,
templateUrl:
'partials/login.html'
};
});
login.html
123456789101112131415161718192021<
div
id
=
"login-wrapper"
>
<
table
>
<
tbody
>
<
tr
>
<
td
>
<
form
id
=
"login-form"
role
=
"form"
>
<
div
class
=
"form-group"
><
a
id
=
"login-logo"
href
=
"#/"
><
img
alt
=
"Chilican"
src
=
"/images/logo.png"
/></
a
></
div
>
<
div
class
=
"form-group"
>
<
label
for
=
"userEmail"
>Adresse email</
label
>
<
input
class
=
"form-control"
id
=
"userEmail"
type
=
"email"
name
=
"user"
placeholder
=
"ex : email@domain.com"
/>
</
div
>
<
div
class
=
"form-group"
>
<
label
for
=
"userPassword"
>Mot de passe</
label
>
<
input
class
=
"form-control"
id
=
"userPassword"
type
=
"password"
name
=
"pass"
/>
</
div
>
<
button
class
=
"btn btn-default"
type
=
"submit"
>Se connecter</
button
></
form
>
</
td
>
</
tr
>
</
tbody
>
</
table
>
</
div
>
sources :
- http://stackoverflow.com/questions/18449516/angularjs-menu-login-logout-loading
- http://blog.brunoscopelliti.com/deal-with-users-authentication-in-an-angularjs-web-app
- http://blog.brunoscopelliti.com/authentication-to-a-restful-web-service-in-an-angularjs-web-app
- http://blog.auth0.com/2014/01/07/angularjs-authentication-with-cookies-vs-token/
- http://www.youtube.com/watch?v=VxuN6WO3tIA