Last active
June 19, 2017 04:56
-
-
Save Mirodil/952e5932c284a2d205db to your computer and use it in GitHub Desktop.
AngularJs: OAuth 2.0 Refresh Token
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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; | |
}); | |
} | |
} | |
}); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
dsfasdfsdafas