AngularJS is an awesome javascript framework. With it’s $resource service it is super fast and easy to connect your javascript client to a RESTful API. It comes with some good defaults to create a CRUD interface.

However if you are using an API, which needs authentication via an auth token, you might run into issues: The resource factory creates a singleton. If you do not already have an auth token when the factory is called, or if the auth token changes afterwards, you cannot put the auth token as a default request parameter in the factory.

This article shows, how to solve this. First we define our resource, consuming a RESTful API, without using an authentication. Afterwards we create a wrapper to send the auth token with every request. This allows consumption of an API with an exchangeable auth token.

Build a RESTful resource

Here is a simple example of how to create a resource in your client, fed by a RESTful backend on your localhost:

  1. angular.module('MyApp.services', ['ngResource'])
  2. .factory('Todo', ['$resource',
  3. function($resource) {
  4. var resource =
  5. $resource('http://localhost:port/todos/:id', {
  6. port:":3001",
  7. id:'@id'
  8. }, {
  9. update: {method: 'PUT'}
  10. });
  11. return resource;
  12. }])

We are creating a module which depends on ngResource, which provides the $resource service. We build a factory called Todo using the $resource service.

Inside the factory we create a resource object by passing an URL and a port to the $resource constructor. Have a look at the URL string: :port and :id are being replaced by the parameters defined in the object literal right after the URL string itself.

Setting a port is not as straight forward, as it could be: In this example we are setting it to 3001. Right now you cannot put it into the URL directly, as AngularJS would interpret :3001 in the URL as a placeholder with the name3001. So we put the placeholder :port in the URL and replace it with :3001 via the parameter object literal.

Now have a look at the :id placeholder: It’s being replaced with @id. With the @ in front, AngularJS takes the attribute with that name from the current resource when doing a request. This is very handy, when sending non-GET request. Here is a simple example: When sending an update REST action for an resource item with id=123 the URL will look like this: http://localhost:3001/todos/123.

There is one last thing in the example: We define an update action for our resource. $resource defines some default actions:

  1. { 'get': {method:'GET'},
  2. 'save': {method:'POST'},
  3. 'query': {method:'GET', isArray:true},
  4. 'remove': {method:'DELETE'},
  5. 'delete': {method:'DELETE'} };

I have no idea, why an update action is missing. I think it would be reasonable to add this to the AngularJS default actions. So, as the update action is missing, we define it ourselves. We just have to provide the HTTP method for it, which is PUT.

As you can see, connecting to a REST API is pretty straight forward.

Send auth token with every request

To send the auth token with every request we are going to wrap the resource actions in a function which appends the auth token. So first of all we create a new service to deal with all the token related stuff:

  1. .factory('TokenHandler', function() {
  2. var tokenHandler = {};
  3. var token = "none";
  4. tokenHandler.set = function( newToken ) {
  5. token = newToken;
  6. };
  7. tokenHandler.get = function() {
  8. return token;
  9. };

As you can see, we create a service called TokenHandler which stores the token itself and provides getter and setter methods.

Now, let’s have a look at the actual action wrapping:

  1. // wraps given actions of a resource to send auth token
  2. // with every request
  3. tokenHandler.wrapActions = function( resource, actions ) {
  4. // copy original resource
  5. var wrappedResource = resource;
  6. // loop through actions and actually wrap them
  7. for (var i=0; i < actions.length; i++) {
  8. tokenWrapper( wrappedResource, actions[i] );
  9. };
  10. // return modified copy of resource
  11. return wrappedResource;
  12. };

The method wrapAction takes a resource and an array with strings identifying the actions to be wrapped as parameters. A copy of the resource is created, modified and returned. We don’t want to change the original resource to prevent any side effects (‘Don’t change parameters inside a function’).

We loop through the actions array, calling the method tokenWrapper for every single action. So finally let us have a look what happens there:

  1. // wraps resource action to send request with auth token
  2. var tokenWrapper = function( resource, action ) {
  3. // copy original action
  4. resource['_' + action] = resource[action];
  5. // create new action wrapping the original
  6. // and sending token
  7. resource[action] = function( data, success, error){
  8. return resource['_' + action](
  9. // call action with provided data and
  10. // appended access_token
  11. angular.extend({}, data || {},
  12. {access_token: tokenHandler.get()}),
  13. success,
  14. error
  15. );
  16. };
  17. };
  18. return tokenHandler;
  19. });

In a first step we copy the original action and store it with a new name. We prepend an underscore and save it into the resource. So the action query for example is now also available as _query.

Afterwards we overwrite the original action with our wrapper function. Parameters of the wrapper are identical with the normal actions: The resource data data and callback functions success and error.

The wrapper calls the renamed original action methods (_query for example) and returns the result. But checkout the first parameter we pass to the original action: We use the data parameter and append the access_token as an object literal to that. This way, the auth_token is send to the API as a parameter called access_token!

Usage of the token wrapper

Of course we have to actually use our new action wrapper in the resource we defined in the first section. So here is how to use it:

  1. .factory('Todo', ['$resource', 'TokenHandler', function($resource, tokenHandler) {
  2. var resource = $resource('http://localhost:port/todos/:id', {
  3. port:":3001",
  4. id:'@id'
  5. }, {
  6. update: {method: 'PUT'}
  7. });
  8. resource = tokenHandler.wrapActions( resource,
  9. ["query", "update", "save"] );
  10. return resource;
  11. }])

The TokenHandler has to be added as a dependency and is passed as a parameter to the constructor method. No changes to the definition of resource are necessary. But before returning resource we overwrite with the result formwrapActions method of the tokenHandler. We pass the original resource and an array with string identifying the actions we want to wrap.

As you can see we can easily overwrite the default actions which are created by $resource implicitly. You can use the overwritten actions the same way you would use the defaults:

  1. // get all todos
  2. var todos = Todo.query();
  3. // save a todo
  4. todo[0].text = "New Text";
  5. todo[0].$save();

You can get the full code of the TokenHandler service here. This approach is based on an idea by Andy Joslin on a stackoverflow question. Thanks, Andy!

refer: http://nils-blum-oeste.net/angularjs-send-auth-token-with-every–request/

参考资料:

django-rest-framework-authentication:http://www.django-rest-framework.org/api-guide/authentication/

django-oauth-toolkit-Django Rest Framework-Getting started:https://django-oauth-toolkit.readthedocs.io/en/latest/rest-framework/getting_started.html

Token-Based Authentication With AngularJS & NodeJS:http://code.tutsplus.com/tutorials/token-based-authentication-with-angularjs-nodejs--cms-22543

Using a token-based authentication design over cookie-based authentication.:https://auth0.com/blog/2014/01/07/angularjs-authentication-with-cookies-vs-token/

RESTful API User Authentication with Node.js and AngularJS – Part 1/2: Server:https://devdactic.com/restful-api-user-authentication-1/

AngularJS: Send auth token with every request:http://chenpeng.info/html/2947

Angular中在前后端分离模式下实现权限控制 – 基于RBAC:http://chenpeng.info/html/3287

【前后台分离模式下,使用OAuth Token方式认证】的更多相关文章

  1. Spring Cloud实战 | 最八篇:Spring Cloud +Spring Security OAuth2+ Axios前后端分离模式下无感刷新实现JWT续期

    一. 前言 记得上一篇Spring Cloud的文章关于如何使JWT失效进行了理论结合代码实践的说明,想当然的以为那篇会是基于Spring Cloud统一认证架构系列的最终篇.但关于JWT另外还有一个 ...

  2. AngularJS中在前后端分离模式下实现权限控制 - 基于RBAC

    一:RBAC 百科解释: 基于角色的访问控制(Role-Based Access Control)作为传统访问控制(自主访问,强制访问)的有前景的代替受到广泛的关注.在RBAC中,权限与角色相关联,用 ...

  3. Epoll在LT和ET模式下的读写方式

    在一个非阻塞的socket上调用read/write函数, 返回EAGAIN或者EWOULDBLOCK(注: EAGAIN就是EWOULDBLOCK) 从字面上看, 意思是:EAGAIN: 再试一次, ...

  4. Spring Security构建Rest服务-1300-Spring Security OAuth开发APP认证框架之JWT实现单点登录

    基于JWT实现SSO 在淘宝( https://www.taobao.com )上点击登录,已经跳到了 https://login.taobao.com,这是又一个服务器.只要在淘宝登录了,就能直接访 ...

  5. Spring Security构建Rest服务-1200-SpringSecurity OAuth开发APP认证框架

    基于服务器Session的认证方式: 前边说的用户名密码登录.短信登录.第三方登录,都是普通的登录,是基于服务器Session保存用户信息的登录方式.登录信息都是存在服务器的session(服务器的一 ...

  6. spring-oauth-server实践:授权方式四:client_credentials 模式下有效期内重复申请 access_token ?

    spring-oauth-server入门(1-12)授权方式四:client_credentials 模式下有效期内重复申请 access_token ? 一.失效重建邏輯 二.如果沒有失效,不会重 ...

  7. flink on yarn模式下两种提交job方式

    yarn集群搭建,参见hadoop 完全分布式集群搭建 通过yarn进行资源管理,flink的任务直接提交到hadoop集群 1.hadoop集群启动,yarn需要运行起来.确保配置HADOOP_HO ...

  8. MySQL-Front 出现“程序注册时间到期 程序将被限制模式下运行”解决方式

    MySQL-Front 出现“程序注册时间到期 程序将被限制模式下运行”解决方式 在用mysql-front的时候遇到显示:程序注册时间到期程序将被限制模式下运行.可以在“帮助”菜单下的点“登记”-- ...

  9. spring-oauth-server实践:使用授权方式四:client_credentials 模式下access_token做业务!!!

    spring-oauth-server入门(1-10)使用授权方式四:client_credentials 模式下access_token做业务!!! 准备工作 授权方式四::客户端方式: 服务网关地 ...

随机推荐

  1. JS 判断某变量是否为某数组中的一个值 的几种方法

    1.正则表达式 js 中判断某个元素是否存在于某个 js 数组中,相当于 PHP 语言中的 in_array 函数. }; 用法如下: var arr=new Array([‘b’,2,‘a‘,4]) ...

  2. JSP(2) - JSP指令 - 小易Java笔记

    JSP指令是给JSP引擎用的,即给服务器用的.作用是告诉服务器,该如何处理JSP中除了指令之外的内容.包括page.include.taglib三种 基本的语法格式:<%@ 指令名称 属性1=& ...

  3. 字节、字、bit、byte的关系[转]

    字 word 字节 byte 位 bit 字长是指字的长度 1字=2字节(1 word = 2 byte) 1字节=8位(1 byte = 8bit)  一个字的字长为16 一个字节的字长是8 bps ...

  4. DELPHI数组,指针,字符串转换的例子

    关于数组,指针,字符串转换的例子 var   aa:   array [0..5] of Char;   bb:Pointer;   cc:string;   dd:PChar; procedure ...

  5. python multiprocessing多进程模块

    原文:https://blog.csdn.net/CityzenOldwang/article/details/78584175 多进程 Multiprocessing 模块 multiprocess ...

  6. rosbag使用--记录深度相机数据

    首先看一下教程: http://wiki.ros.org/openni_launch/Tutorials/BagRecordingPlayback 知道了rosbag如何进行使用记录深度数据 但是按照 ...

  7. (1)Python 安装使用IDLE

    安装 官网 https://www.python.org/ Windows x86 web-based installer 在线安装 Windows x86 executable installer ...

  8. </2017><2018>

    >>> Blog 随笔原始文档及源代码 -> github: https://github.com/StackLike/Python_Note >>> 统计信 ...

  9. 模板—字符串—Manacher

    模板—字符串—Manacher Code: #include <cstdio> #include <cstring> #include <algorithm> us ...

  10. (寒假GYM开黑)2018 German Collegiate Programming Contest (GCPC 18)

    layout: post title: 2018 German Collegiate Programming Contest (GCPC 18) author: "luowentaoaa&q ...