HTTP post with angular on a "before auth" laravel route - angularjs

I authenticate my user only through laravel, so angular does not know about it. But I need to do a $http.post on a "before auth" route with angular in order to get some profil info:
laravel route.php
Route::post('profile', array('before' => 'auth', function()
{
// Only authenticated users may enter...
}));
angular app.js
$http.post("/profile").success(function (data) {
$scope.profile = data;
});
For now I get an internal server error (500) with a "Illuminate\Session\TokenMismatchException" because laravel think I'm not logged in.
Could someone help me out with this?
Thanks in advance :)

My mistake, it was a csrf filter that was causing this error, not the auth filter...
For reference to my question:
AJAX Requests are identical with regular requests in regards to session data. Anything that depends on Session or Auth will work with an AJAX call.
link to thread

Related

authorisation and login control in an Angular app

So for the past few months I have been developing the 'login functionality' of my Angular apps like this. The user logs in and if the credentials are correct, the REST API returns a token. I take that token and store it as a cookie:
$cookies.put('authorisation', data['token']);
Whenever I call the $http service, I submit the authorisation cookie as a header and it authorises the http request. Then on the controller of each view I add:
if (!$cookies.get('authorisation')) {
$location.path('/login');
}
So if the cookie doesn't exist, the user is automatically kicked to the login screen.
This has worked for me just fine up until now but I can't help but feel that it is not the 'correct' way of doing things. Could anyone shed a little light on what the best practice method for this could be? And perhaps why what I'm doing is 'wrong'?
Are you familiar with Angular $http Interceptors:
https://docs.angularjs.org/api/ng/service/$http#interceptors
You could use the request interceptor to have your authorization checked before each $http request.
If you do this you also have to integrate a custom Flag on each $http config object (e.g. skipAuthorization) in order to allow the user to perform Requests without being logged in (useful for actually logging in ;-))
#AzzyDude to your comment:
I'm using ui-router to do the navigation inside of my Angular 1.6.X Application.
You can either integrate own config-properties on the states (isGuestState) or if its a closed application such as mine, hard-coded in a $stateChange event, like this:

Basic authentication in AngularJS

I have a RESTful back-end server with basic authentication. Currently I am implementing a front end page with AngularJS to interact with the server. Can anyone give me some hint about implementing the basic authentication in AngularJS? Do I need to use Interceptors?
Thanks
By basic authentication did you mean HTTP Auth? Anyway - if you need to send authenticated requests from Angular to your back-end server, then yes you would need to use HTTP interceptors.
I found this article very helpful when I was implementing token based auth w/ Angular before: https://auth0.com/blog/2014/01/07/angularjs-authentication-with-cookies-vs-token/ - but there are a lot of resources out there on this.
You can use post method and handle the result(i.e., if login Success set some flag success to true else set success to false).
backendURL = "http://someurl";
postData = { username: 'USERNAME', password: 'password' };
$scope.serverCall = $http.post(backendUrl, postData);
$scope.serverCall.success(function(result,status,header,config){ //handle your result })
$scope.serverCall.error(function(result,status,header,config){ //handle your Exceptions })
Note: Login fail or Success it will come to success callback only. In case Exceptions in the backend then only it will come to the error callback.
In the Backend Side
{ success: true } // If Login Success
{ success: false } // If Login Fail
Based on this flag you can handle it.
I Hope this will helpful.

How to redirect expired users with passport.js and Angular?

A bit of background:
I am using Passport.js to handle login from serverside.
Angular routing is used on the client side in a one-page-app
The issue:
In my server router i have middleware which ensure users are logged in when requesting certain content, namely:
function isLoggedIn(req,res,next){
if(req.isAuthenticated()){
return next();
}
res.render('index.ejs');
};
used in routes such as:
app.get('/SomethingForLoggedUsers', isLoggedIn, function(req,res){...
My problem is that if the user is on the website (on the part handled by Angular router) and their session is expired res.render('index.ejs'); does not work. My feeling is that angular routing has to do with the fact that index.ejs is not shown, but I don't manage to fix the problem. Any suggestions?
The problem with your solution is that with angular, it is possible that the user may be doing some client operations and not making a request on the server.
In angular, I have seen two common approaches to this problem:
Handle this fully on the client, there is an open source ng-idle directive that can help with this. When the user times out on the client, you can log them out of the application using passport
Handle this with support from the server, there is an open source angular-http-auth module that can help handle HTTP 401 / 403 from the server. This means your code would do:
function isLoggedIn(req,res,next){
if(req.isAuthenticated()){
return next();
}
res.writeHead(401);
res.end();
};
I hope this information helps you understand what is possible in Angular.
Here is how I solved the problem.
In my angular controller I have:
$http.get('/SomethingForLoggedUsers').success(function(data) {
if(!data.user)$window.location.href="/login";
and in the server I return user:null everytime the user is not logged, namely:
function isLoggedIn(req,res,next){
if(req.isAuthenticated()){
return next();
}
res.json({user:null});
};

Angular ui-router using resolve validate authentication

I'm trying to see what's the best way to validate if a user is authenticated into the application.
Right now I'm using the following:
The user log in into the application
On Server Side a Token is created and send it back to the browser
On Log In Success, AngularJS stores the Token: $http.defaults.headers.common['RequestVerificationToken'] = token || $cookies.token;
On every http call to the server the Token is sent and is verified server side, in case the token doesn't exist then a 401 response status is sent to client.
This is working pretty well, now Im using UI-Router to control application states (pages - real scenario):
I have the following state:
$stateProvider
.state('personinfo', {
url: "/personinfo",
controller: 'PersonController',
templateUrl: "app/partials/personinfo.html"
})
Inside my PersonContoller:
app.controller('PersonController', function ($scope,$sce, $location, PersonService) {
$scope.title = 'Person Page';
PersonService.getPersons().success(function (response) {
$scope.persons = response.success;
}).error(function () {
// If token doesn't exist, a 401 reponse status is sent by server
$location.url('/login');
});
});
I don't really like how it works because AngularJS will load the state and download the partial HTML file and then it will go into the controller and execute the get method and if the token is not valid then it will redirect to login state.
I would like to validate the token before the state is being loaded, so if the token is not valid then the partial HTML won't be downloaded or whatever.
I have read that UI-Router has a resolve property that can be used to get data before the view is loaded... can I use the resolve to validate the Token?
Hope someone can give me a guide or advice.
Thanks a lot.
Your build stack should compile production JS with template embedded, so there
is no round trip to worry about.
If you really want to intercept the initial page load, experiment with
$locationChangeSuccess, which is fired before the first $routeChangeStart.
If you want to hook into resolve, just attach a promise to it.

AngularJS $http and cookies

I'm trying to implement authentication with ExpressJS' cookie sessions and AngularJS. The problem is that even I can get ExpressJS to send session cookies, Angular won't send them with subsequent requests.
I'm running backend server at 192.168.1.2:3000 and yeoman server at 192.168.1.2:3501 so is there a cross-domain issue here? I already did the normal CORS stuff with ExpressJS in order to get $http working correctly but I'm not sure how to get the cookies working.
Have you checked that your request is sent with the withCredentialsflag set to true?
In angular, this can be done by in the HTTP request configuration object, e.g
//...
$http.get(myUrl, {withCredentials: true})
//...
Or if you don't want to reconfigure it all the time, using $httpProvider:
myApp.config(['$httpProvider', function ($httpProvider) {
$httpProvider.defaults.withCredentials = true;
}]);
to get cookies working in angularJS you could follow this link
I maintain session variable in the backend (expressJS) and return it to the $cookies object in the frontend(angularJS).
So When i logout, it would delete the cookie in angularJS and the session variable in the backend.

Resources