javascript - How to manage authentication with token in angular.js? -


Hi Everyone I created a RESTIPAL API with authentication along with Token (Rail 4 + Device), as well as manage the CORS implementation. Mani (rack-cores) but now I want to use encoding with encoding.

For this, I do this:

  var app = angular Module ('model'); App.factory ('session', ['$ resource', work ($ resource) {var session = $ resource ('http://api.creositios.dev/sessions/:id', {}, {create: { Method: 'Post'}, Delete: {Method: 'Delete', Parameters: {ID: 'id'}}}); Return session;}]);  

And this is my controller

  app = angular. Module ('controller'); App.controller ('session' Ctrl, ['$ scope', 'session', function ($ scope, session) {$ scope.new_session = function () {$ scope.session = session .create ({email: 'developer Jimenez@gmail.com, password: '12345678'});};}]);  

So far I have no problem with implementation. My problem is not known how the management is broken, which returns to my factory.

What are good practices for managing a user's token with angular.js and are valid in angular.js in the user angle controller?

With certification with the token this is my first app advice very much appreciate !.

To put security logic in a service generally and to set a token in your requests, httpInterceptor

Security service.

  Angular Modules ('Security'). Factor ('security', ['$ http', function ($ http) {var token; function login (email, password) {return $ http.post ('/ auth / login', {email: email, password: password }}. Then (function (response) {if (response.data.token) {token = Response.data.token;}});} function getToken () {return token;} return {login: login, token: getToken };}]);  

This specific login method can be used by a login controller for example: When the user login in the token gets credited back.

Return} {request: function (configuration) {var token = Security.getToken (); Config.headers = config.headers || {}; if (token) {config.headers.Authorization = 'beerer' token;} return conversion ;}};}]) ;;

While booting the application, do not forget to add your interceptor

  .config (['$ httpProvider', function ($ httpProvider) { $ HttpProvider.interceptors.push ('Authority Interceptor');}]);  

Token will now be set on every HTTP request, whatever you do in case of failure is up to you.

For example, you can add another reaction interceptor, which redirects 401 or 403 responses to the login page, etc.


Comments