Handle Angular 401 responses - angularjs

I have simple api and a authorization point
when i request to api i get a 401 if the token is invalid (token loses validity past five minutes).
i know i can intercept 401 for example with
app.factory("HttpErrorInterceptorModule", ["$q", "$rootScope", "$location",
function($q, $rootScope, $location) {
var success = function(response) {
// pass through
return response;
},
error = function(response) {
if(response.status === 401) {
// dostuff
}
return $q.reject(response);
};
return function(httpPromise) {
return httpPromise.then(success, error);
};
}
]).config(["$httpProvider",
function($httpProvider) {
$httpProvider.responseInterceptors.push("HttpErrorInterceptorModule");
}
]);
but i want capture and queue the request and show a login form if is success then change the token (it's a header) and execute request again

You can use $httpInterceptor in slightly another way. If you want to redirect user after login to page where user actually failed you need to cache failed request in some service and then redirect user somewhere after login (I beleive in logic connected to your login).
But you may need to have some test endpoint to protect your controllers from unrestricted access, you might want to use resolve https://thinkster.io/egghead/resolve/
So in this case you will receive error connected with restricted access to proctedted endpoint but not to your page.
To solve this problem I used marker param (or header) to find out where I should redirect user after login.
Here is example of your httpInterceptor.
angular.factory('httpInterceptor', function ($q, $rootScope, $log, someService) {
return {
request: function (config) {
return config || $q.when(config)
},
response: function (response) {
return response || $q.when(response);
},
responseError: function (response) {
if (response.status === 401) {
//here I preserve login page
someService
.setRestrictedPageBeforeLogin(
extractPreservedInfoAboutPage(response)
)
$rootScope.$broadcast('error')
}
return $q.reject(response);
}
};
})
.config(function ($httpProvider) {
$httpProvider.interceptors.push('httpInterceptor');
});

angular-http-auth module provides a service that intercepts requests and queques them to re-send them later once a user logs in.
This service fires also these events below, so you could listen to them and decide what to show on screen
event:auth-loginRequired
event:auth-loginCancelled
event:aut-loginConfirmed
Look at the code. It has just a few lines of code
https://github.com/witoldsz/angular-http-auth

Related

Getting response code 401 causes skipping code blocks

I'm writing an ionic v1/express/mongo/node app. When checking if the user is authenticated i have the following piece of code:
checkAuthentication: function(token) {
console.log(token);
return $http.get("http://validUrl/test", {
headers: {
'testingAuth': token
}
}).then(function(result) {
return result.data;
});
}
and am calling it like this:
checkAuthentication(token).then(function(response) {
console.log("testing response: " + response);
// if a valid token is already in storage = response contains "Success"(?), just $state.go to main page, else call the login() function
if (response.content === "Success") {
// $state.go main page
} else {
console.log("could not log in");
}
})
The problem is, when I get back code 401 from the server, I somehow skip the then block in the checkAuthentication function. Execution doesn't stop at a breakpoint at "return result.data", or "console.log("could not log").
Am I doing something obviously wrong? Is there something i need to do to force going into that block? Thanks for any advice.
The issue is with your error handling ! I took the liberty to modify your code and the way to do a $http call. Here is the working plunker for the same.
If you observe the $scope.login() function I've injected the service object and invoked the checkAuthentication() function which does the HTTP call.As you are using .then for http calls, angular provides provision to use two functions for success and error callbacks where your HTTP errors go when HTTP calls fail.
Here is the angular doc for the same.
In your example you don't have error callback method hence it doesn't go into your if else conditions.
var app = angular.module("App", []);
app.controller('AppCtrl', ['$rootScope', '$scope', '$http', 'Service', function($rootScope, $scope, $http, Service) {
$scope.login = function(token) {
//call the injected service in the function for HTTP call..
Service.checkAuthentication(token).then(function(response) {
console.log("testing response: " + response);
// if a valid token is already in storage = response contains "Success"(?), just $state.go to main page, else call the login() function
if (response.content === "Success") {
// $state.go main page
}
},function(error){
console.log(error);
console.log("could not log in due to error...");
});
};
}]);
//use angular services to do a http call for better code maintainability...
app.service('Service', ['$http', '$rootScope', function($http, $rootScope) {
return {
checkAuthentication: function(token) {
return $http.get("http://validUrl/test", {
headers: {
'testingAuth': token
}
});
}
};
}]);

Simple interceptor that will fetch all requests and add the jwt token to its authorization header

In my efforts to setup login required to protected pages and reroute to the login page if not authorized, while using Django REST Framework and DRF-JWT, I am trying to go through the following tutorial:
https://www.octobot.io/blog/2016-11-11-json-web-token-jwt-authentication-in-a-djangoangularjs-web-app/
I am not sure what this looks like in step 3 of the front-end section.
// Add a simple interceptor that will fetch all requests and add the jwt token to its authorization header.
Can someone provide an example?
Also, my original post regarding the issues I am having setting this up in general.
Trying to get login required to work when trying to access protected pages
Thanks!
The interceptors are service factories that are registered with the
$httpProvider by adding them to the $httpProvider.interceptors array.
The factory is called and injected with dependencies (if specified)
and returns the interceptor.
The basic idea behind intercepter is that it will be called before each $http request and you could use a service to check if user is logged in and add a token or anything else that needs to be added into the header.You could also add some logic for response for each $http request, like handling the response based on status code.
Here is how you can use it in angular for adding the access token for each http request.
angular.module('myapp')
.run(['$rootScope', '$injector', function($rootScope,$injector) {
$injector.get("$http").defaults.transformRequest = function(data, headersGetter) {
if (sessionService.isLogged()) {
headersGetter()['Authorization'] = "Bearer " + sessionService.getAccessToken();
}
if (data) {
return angular.toJson(data);
}
};
});
Here is how you can use response intercepter:
angular.module('myapp')
.factory('authHttpResponseInterceptor', function($q, $location, sessionService, $http) {
return {
response: function(response) {
//some logic here
return response || $q.when(response);
},
responseError: function(rejection) {
if (rejection.status === 401) {
//some logic here
}
return $q.reject(rejection);
}
}
});

angularjs http interceptor to show error on loaded location path

I have an application for which I created an interceptor to handle token expirations after 15 minute inactivity, it successfully redirects to the login page after a token has expired, but Im not able to show the error after redirecting to the login page.
My question is, how can I show the user the token expired error on the login page, after the interceptor has redirected the app to that page.
Heres my redirector:
app
.config(['$httpProvider', function($httpProvider) {
$httpProvider.interceptors.push(function($q, $location, LoopBackAuth) {
return {
responseError: function(rejection) {
if (rejection.status == 401) {
//Now clearing the loopback values from client browser for safe logout...
LoopBackAuth.clearUser();
LoopBackAuth.clearStorage();
$location.path("/login");
}
return $q.reject(rejection);
}
};
})
}])
.config(function(LoopBackResourceProvider) {    
LoopBackResourceProvider.setAuthHeader('X-Access-Token');
})
Finally and thanks to #forrestmid to point me in the right direction this is what I ended up doing.
on the http interceptor just added:
$location.path("/login").search({error: 'invalid_token'});
and then on the controller just had to do:
var queryString = $location.search();
$scope.errors = {};
if (queryString && queryString.error) {
$scope.errors = {
'invalid_token': {
code: 'invalid_token'
}
}
}
now on the template I already have logic to handle the error object so now it works fine :)
Referencing this post in regards to injecting the $state service into an HTTP interceptor:
app.config(['$httpProvider', function($httpProvider) {
$httpProvider.interceptors.push(function($q, $injector, LoopBackAuth) {
return {
responseError: function(rejection) {
if (rejection.status == 401) {
//Now clearing the loopback values from client browser for safe logout...
LoopBackAuth.clearUser();
LoopBackAuth.clearStorage();
$injector.get('$state').go('app.login', {error: 'Token expired.'});
}
return $q.reject(rejection);
}
};
})
}]);
Assuming that you're using ui.router:
app.config(function($stateProvider){
$stateProvider
.state("app",{abstract: true})
.state("app.login", {
url: "/login",
params: {error: ""}
});
});
By default there will be no error when transitioning to the app.login state, but when there is a param error set to whatever, it can display the error. This will be in the $stateParams.error variable on your login page.
Let me know if I botched any of that code since I didn't test it. The line I think you want is the $injector line.

AngularJs : event listener on http requests

Since i'm using Oauth2 to protect my Api, i need to get a new access token before any http requets if the previous access token has expired.
I didn't used event listener much until now.
Here what i did for now (Please let me know if it is correct) :
ApplicationController.js :
app.controller('ApplicationController', function($rootScope, $scope, $localStorage, AuthService){
// Listening event apiRequested
$scope.$on('event:apiRequested', function(e) {
AuthService.token();
// Restore the access_token in case it has changed
access_token = $localStorage.getObject('access_token');
});
})
UserController.js :
$rootScope.$broadcast('event:apiRequested');
// Get Users around
return $http.post(domain+'/api/users?access_token='+access_token.key, data).then(function(response){
return response;
});
First thing i'm not sure about ... Does $http is processed if the event already executed entirely?
So since i'm not sure, i'm thinking about adding a callback.
Here the idea :
$rootScope.$broadcast('event:apiRequested', function(response){
if(response){
// Get Users around
return $http.post(domain+'/api/users?access_token='+access_token.key, data).then(function(response){
return response;
});
}
});
Please let me know if it is possible to do that or should i use something else than event listener for that case.
Why don't you use interceptors that is done to intercept HTTP request ?
In your case, you shall add this very specific behaviour into the "request" part.
See an interceptor exemple bellow:
var $myService; // Add a constant that store the service
$httpProvider.interceptors.push(['$location', '$injector', '$q', function($location, $injector, $q) {
return {
'request' : function(config){
console.log("intercept request", config.url,config)
// Your token shall be retreive in this part
return config
},
'response' : function(config){
$myService= $myService|| $injector.get('$myService'); // inject the service manually if constant is undefined
console.log("intercept response", config)
// Your token shall be retreive in this part
return config
},
'responseError': function(rejection) {
console.log("responseError intercepted" , rejection);
if (rejection.status === 403) {
return $q.reject(rejection);
} else if (rejection.status === 423) {
return $q.reject(rejection);
}else
return $q.reject(rejection);
}
};
}]);
Interceptors shall be defined into .config(["$httpProvider", function($httpProvider)

How can I redirect a user to the login page using angularjs and laravel

I am working on a project using laravel and angularjs. I am using only Laravel to authenticate the users and when their logged in, then angularjs ui veiw will handle the navigation. when doing this I realized a problem, when the session has expire the user should be redirected to the logged in page based on the auth filter that is set on the route. Additionally when I checked the browser dev tool network tab, I see that the sign in page is send as a response. I am wondering how can I make my project redirect the user to the logged in page when the session has expire. how can I solve this problem and Thanks in advance for the assistance.
You can do that with $httpInterceptor, here is demo code:
var myApp = angular.module("MyApp", []);
myApp.config(function ($httpProvider, $provide) {
$provide.factory('myHttpInterceptor', function ($q, $location) {
return {
'response': function (response) {
//you can handle you sucess response here.
return response;
},
'responseError': function (rejection) {
console.log(rejection);
//if(rejection.data.xxx==="xxx")
if(rejection.status === 408){//session expired code
alert('logout!');
// clear your local data here...
$location.url("/login")
}
return $q.reject(rejection);
}
};
});
$httpProvider.interceptors.push('myHttpInterceptor');
});
myApp.controller("MainController", function ($scope, $http) {
$scope.response = {};
$scope.triggerGet = function () {
$http.get("/my/json").success(function (data) {
$scope.response = data;
});
};
});
When your server side response is session expired, you can handle the response.status or you can handle the other data with response.data.
Here is $httpInterceptor document.(In the middle of the page)
To redirect the user client-side in JavaScript use location. https://developer.mozilla.org/en-US/docs/Web/API/Location
For this case I think you want to look at location.assign() specifically.

Resources