Skip to content

Instantly share code, notes, and snippets.

@Mirodil Mirodil/config.js
Last active Jun 19, 2017

Embed
What would you like to do?
AngularJs: OAuth 2.0 Refresh Token
(function(){
angular.module('app', [])
.config(['$httpProvider', function($httpProvider) {
$httpProvider.interceptors.push(['$q', '$window', '$timeout', '$injector', function ($q, $window, $timeout, $injector) {
var $login, $http, $auth;
$timeout(function () {
$login = $injector.get('$login');
$http = $injector.get('$http');
$auth = $injector.get('$auth');
});
return {
'request': function (config) {
config.headers = config.headers || {};
var token = JSON.parse($window.localStorage.token || null);
if(token){
// if token expire
if(token.expire && token.expire < Date.now()){
// re-new token
return $auth.refresh()
.then(function(token){
config.headers.Authorization = (token.type || 'Bearer') + token.access;
return config;
});
} else if (token.access) {
config.headers.Authorization = (token.type || 'Bearer') + token.access;
}
}
return config;
},
'responseError': function (response) {
if (response.status === 401 || response.status === 403) {
return $auth.refresh()
.then(function () {
return $http(response.config);
})
.catch(function () {
return $q.reject(response);
});
}
return $q.reject(response);
}
};
}]);
}])
.provider('$auth', function($http, $window){
return {
login:function(){
// TODO: login
},
logout:function(){
window.localStorage.removeItem('token');
},
refresh: function(){
var token = JSON.parse($window.localStorage.token || null);
return $http.post('/auth/refresh', {
accessToken: token.accessToken,
refreshToken: token.refreshToken
})
.then(function(res) {
var token = {
access: res.data.access_token,
refresh: res.data.refresh_token,
type: res.data.token_type,
expire: Date.now()+ parseInt(res.data.expires_in)*1000 // calculate time of expire
};
$window.localStorage.token = JSON.stringify(token);
return token;
});
}
}
});
})();
@sakthibalanssb

This comment has been minimized.

Copy link

sakthibalanssb commented Jun 19, 2017

dsfasdfsdafas

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.