设为首页 收藏本站
查看: 2415|回复: 0

[经验分享] 【前后台分离模式下,使用OAuth Token方式认证】

[复制链接]

尚未签到

发表于 2017-2-25 11:10:26 | 显示全部楼层 |阅读模式
  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:

angular.module('MyApp.services', ['ngResource'])
.factory('Todo', ['$resource',
function($resource) {
var resource =
$resource('http://localhost:port/todos/:id', {
port:":3001",
id:'@id'
}, {
update: {method: 'PUT'}
});
return resource;
}])

  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:

{ 'get':    {method:'GET'},
'save':   {method:'POST'},
'query':  {method:'GET', isArray:true},
'remove': {method:'DELETE'},
'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:

.factory('TokenHandler', function() {
var tokenHandler = {};
var token = "none";
tokenHandler.set = function( newToken ) {
token = newToken;
};
tokenHandler.get = function() {
return token;
};

  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:





  // wraps given actions of a resource to send auth token
// with every request
tokenHandler.wrapActions = function( resource, actions ) {
// copy original resource
var wrappedResource = resource;
// loop through actions and actually wrap them
for (var i=0; i < actions.length; i++) {
tokenWrapper( wrappedResource, actions );
};
// return modified copy of resource
return wrappedResource;
};

  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:

  // wraps resource action to send request with auth token
var tokenWrapper = function( resource, action ) {
// copy original action
resource['_' + action]  = resource[action];
// create new action wrapping the original
// and sending token
resource[action] = function( data, success, error){
return resource['_' + action](
// call action with provided data and
// appended access_token
angular.extend({}, data || {},
{access_token: tokenHandler.get()}),
success,
error
);
};
};
return tokenHandler;
});

  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:

.factory('Todo', ['$resource', 'TokenHandler', function($resource, tokenHandler) {
var resource = $resource('http://localhost:port/todos/:id', {
port:":3001",
id:'@id'
}, {
update: {method: 'PUT'}
});
resource = tokenHandler.wrapActions( resource,
["query", "update", "save"] );
return resource;
}])

  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:

// get all todos
var todos = Todo.query();
// save a todo
todo[0].text = "New Text";
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

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-346986-1-1.html 上篇帖子: Apache Zeppelin 下篇帖子: 转一篇sublime必备的一些插件
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表