Manage authentication with tokens created with OAuth2 in angular.js

Hello,
I have an angularjs client in which I want to get the access token via web service (the backend is with PHP5) when I fill the login form and the password,then I click the button “Log in”, this is my controller :

    'use strict';
app.controller('SigninFormController', ['$rootScope','$scope','$http', '$state','$localStorage', function($rootScope, $scope, $http, $state,$localStorage) {
$scope.user = {};
$scope.authError = null;
$scope.login = function() {
$scope.authError = null;
// Try to login
$http({method: 'POST', url: 'monURL/oauth/v2/token?client_id=idclient&client_secret=secretclient'})
.success(function(data){
$scope.msgs.splice(0, $scope.msgs.length);
$scope.posts = data; 
$localStorage.token = data.access_token;
$state.go('app.dhome');
})
.error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
$scope.authError = 'Email or Password not right';
console.log("error");
}); };

this is the result of the URL monURL/oauth/v2/token?client_id=idclient&client_secret=secretclient in json format

{"access_token":"ABSCD...","expires_in":3600,"token_type":"bearer","scope":"user"}

I want that the value of “access_token” recovered from the result of the above URL shown above will be saved to the session level for each request I can put it like this:

url:monURL/api/clients.json?access_token=ABSCD... (to get here the list of clients)

but what I always get the word “error” in console
is there any function or directive in angularjs that allows me to cut out the recovered string of the URL ,put it in a variable and use that variable
thank you for help

Kindia,

You want to append the query string parameter access_token with every HTTP request you send using $http, right?

If yes, you can save the access token in an angular value and append it to every request using an HTTP interceptor. Check Angular’s documentation for more info on interceptor: https://docs.angularjs.org/api/ng/service/$http. You need to define the request method on the interceptor service.

Let me know if it answers your question.

1 Like

thanks @sravikiran it was the solution thanks Mr al lot :blush:

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.