0

recently i am working hard on my website with angularjs on the Front End and Symfony 3 on the backend. I put a security layer on my backend so every request from my FE must need a valid token (using grant_type=client_credentials). I have read a looooot about the best practices about call my API Backend with angular... I normally send the token on every request that i make to the Backend, but i read that i can use the $http interceptor to send always on the header my bearer token.

So, i am a little confused that how start... because for one part:

  • i want to do calls to my backend to load certain data to be used on my pages to show info (using the grant_type=client_credentials) and,

  • i will have an user management system too. So this users must to login with user and password (again another call to my backend) but with grant_type=password...

The really big question is: can i do the same things with one interceptor? (one for show page elements data with grant_type=client_credentials and other for the normal users?)

Tha another question is... can i make a token with this interceptor if the token has not been created yet (only for the pages info, for the users i want to refresh the token if is going to expire)?

Sorry if is a little confused... i am confused, i really read many posts, documentation and help... but i don't know where to start... I hope that you can help me... Thanks for all.

2 Answers 2

1

The beauty of JWT is that they are essentially just javascript objects. You could for instance provide the user a token containing their role in the system (user, admin, support etc...) and show/hide elements accordingly. So basically not only you grant the user access to the API, you also provide them with their type of access. Of course you should NEVER rely on client side authentication to allow restricted API's directly (verify the token on each request, check for the provided role on the server).

Here's an example in NodeJS and Angular:

//In NodeJS...
app.get('/path/to/secured/api', verifyTokenOr401, function(req, res) {
//Do stuff...
res.json({msg: 'Success');
});

function verifyTokenOr401(req, res, next) {
 var authHeader = req.headers.authorization;
 try {
  var token = authHeader.split(' ')[1];
  if(jwt.verify(token, 'myAppSecret'))
   next();
 } catch(e) {
  res.status(401).send('Not authorized');
 }
}

//Assuming you use node-jsonwebtoken package
app.post('/path/to/authentication', function (req, res) {
//Verify authentication...

 User.findOne({username: req.body.username}).then(function(user) {
 //VerifyPassword
  if(!user)
   return res.status(401).send('No such user ' + req.body.username);

  if(!user.verifyPassword(req.body.password))
   return res.status(401).send('Wrong password for user ' + user.username);

 //Provide the user with the access token
  var token = jwt.sign({ subject: user.id, role: user.role }, 'myAppSecret');
  res.setHeader('Authorization', 'Bearer ' + token.toString());
  res.json(user);
 })
.catch(function (e) { res.status(500).json(e); });
});

//In angular...
.factory('jwtInterceptor', function() {
 return {
  request: function(config){
   var authHeader = config.headers('authorization');
   //Attach header if not present
   if(!authHeader)
    config.headers.authorization = 'Bearer ' + localStorage.get('myAppToken');
   return config;
  },
  response: function(response){
   //Look for token in the header if you get a response and save it
   var authHeader = response.headers('authorization');
   if(authHeader){
    try { localStorage.myAppToken = authHeader.split(' ')[1]; } catch(e) {}
   }
   return response;
  }
 }
});

Notable mention: check out auth0's repos for NodeJS and Angular. Both are awesome.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for the answer my friend! very clear, but i don't use NodeJS because the hosting is on apache web server.
This is just an example but you can apply the concept to any backend
Thanks my friend. I am really new on AngularJS. Can you help me with a basic example how to start to use JWT on my projects?
I just did. you'll need to configure your backend too.
1

You can create a service which when loaded by angular make a get call for authorization token and set in header. Through this you do not need to set token at every Ajax call. You can do it like this:

app.service("MyService", ["$http", function($http) {
    initialize();

    function initialize() {
        getAuthorizationToken().then(function(response) {
            $http.defaults.headers.common.Authorization = 'Bearer some_auth_code_here';
        });
    }

    function getAuthorizationToken() {
        // Get call for token
    }
}]);

3 Comments

Thanks my friend, i will try this... But... with this example is not necessary use the $http interceptors?
I used your example but if i try to call the API i now get the error: 401 (Unauthorized).. i call the api as: $http.post("http://xxxxxxxx/api/method" ).then(function(response){... and i get this error.
You can try getting authorization token at the time of login and setting it in the headers so that furthers calls do not require setting of tokens.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.