Jose the hose
Jose the hose

Reputation: 1895

Passing auth0 token to $http.get (angular)

'm having some problems getting the auth0 token to append to a http.get request to an api that expects to see the token. the token is created when the user logs in and is kept in the browsers local storage. That part is working fine. So its appending the token to the http.get that I am having the issue with.

So far I have the following code. in my app.js I have the following...

var QuoteApp = angular.module('QuoteApp', ['ui.router', 'auth0', 'angular-jwt', 'angular-storage', 'ngCookies']);
priceQuoteApp.config(function ($stateProvider, $urlRouterProvider, $httpProvider, authProvider, $locationProvider, jwtInterceptorProvider) {

jwtInterceptorProvider.tokenGetter = function(store, jwtHelper, auth) {
    var idToken = store.get('token');
    var refreshToken = store.get('refreshToken');
    // If no token return null
    if (!idToken || !refreshToken) {
        return null;
    }        
}
$httpProvider.interceptors.push('jwtInterceptor');

});

Then I have a $http.get function that I send a request to the api that also requires a token

in my api.service.js file I have this...

this.getStuff = function (attributes) {
    return $http.get('http://www.theurl.com/api/getstuff?json=' + JSON.stringify(attributes)).
        success(function(){
        });
};

I call the getStuff function from my getStuff.js file like this...

  $scope.getTheStuff = function (){
         Services.getStuff($scope.Attributes)
         .then(function (res) {
         })
    };

So I am getting an authentication error from the server - 401 (Unauthorized) which to me means that the token is not appending to the http.het request for some reason. Any ideas why this might be happening?

I have also included the headers from the browser console if that would help...

Remote Address:10.34.51.34:80
Request URL:http://www.theurl.com/api/getstuff?json={stuff in here}]}
Request Method:GET
Status Code:401 Unauthorized
Accept:application/json, text/plain, */*
Accept-Encoding:gzip, deflate, sdch
Host:http://www.theurl.com
Origin:http://localhost:63342
Referer:http://localhost:63342/price-tool-ui-1/app/index.html
User-Agent:Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.115 Safari/537.36
Query String Parametersview sourceview URL encoded
json:{stuff in here}]}
Access-Control-Allow-Methods:GET, POST, OPTIONS, PUT, DELETE
Access-Control-Allow-Origin:*

Upvotes: 0

Views: 1922

Answers (3)

mgonto
mgonto

Reputation: 6595

You're not returning the token you got from localStorage.

@eer response is pretty good, but he still needs to save the newly refreshed token so that you don't have to call that endpoint again the next time.

Code looks like:

var refreshingToken = null;
jwtInterceptorProvider.tokenGetter = function(store, $http, jwtHelper) {
  var token = store.get('token');
  var refreshToken = store.get('refreshToken');
  if (token) {
    if (!jwtHelper.isTokenExpired(token)) {
      return store.get('token');
    } else {
      if (refreshingToken === null) {
        refreshingToken =  auth.refreshIdToken(refreshToken).then(function(idToken) {
          store.set('token', idToken);
          return idToken;
        }).finally(function() {
            refreshingToken = null;
        });
      }
      return refreshingToken;
    }
  }
}

Hope it helps!

More info on https://github.com/auth0/auth0-angular/blob/master/docs/refresh-token.md

Thanks!

Upvotes: 2

naneer
naneer

Reputation: 221

You're not returning the token in jwtInterceptorProvider.tokenGetter. From the docs

jwtInterceptorProvider.tokenGetter = function(store, $http, jwtHelper) {
  var idToken = store.get('token');
  var refreshToken = store.get('refreshToken');
  if (jwtHelper.isTokenExpired(idToken)) {
    return auth.refreshIdToken(refreshToken);
  } else {
    return idToken;
  }
}

Upvotes: 4

jp wizer
jp wizer

Reputation: 178

Not sure I understand your problem correctly. But here is what I do to set the token in the http request to my API, after authenticating :

$http.defaults.headers.common['token'] = token;

The name of the header depend on what is expected by your API (it may be X-Auth, Token, X-Token....).

Upvotes: 0

Related Questions