AngularJS 将 requestVerificationToken 传递给服务 [英] AngularJS pass requestVerificationToken to a service

查看:17
本文介绍了AngularJS 将 requestVerificationToken 传递给服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将一个由 Razor MVC 助手在我的登录表单中生成的 RequestVerificationToken 传递给我为管理我的应用程序的身份验证所做的 AngularJS 服务

我的表格如下:

@Html.AntiForgeryToken() 以这种方式呈现:

我的 AngujarJs 控制器成功注入了我的loginService",我可以通过 Post 将用户名和密码发送到服务

function loginCtrl($scope, loginService) {$scope.submit = 函数 () {loginService.authenticate($scope.loginRequest,function(data) {$scope.loginRequest.isValid = (data.User!=null);//console.log(数据);});};}

服务:

angular.module('App.services', ['ngResource']).工厂('登录服务',功能($资源){return $resource('/Api/User/login', '',{验证:{方法:'POST',isArray:假,标头:{'X-XSRF-Token':'?????'}}});});

我的问题是如何读取表单中呈现的令牌并将其传递给服务并使用从登录表单中获取的令牌设置标头,据我所知,这不是操作 DOM 和我不知道是否需要创建指令来执行该任务,因此欢迎提出任何建议!

解决方案

我想我已经找到了一个很好的解决方案.我从这里的建议开始 http://www.novanet.no/no/blog/olav-nybo/dates/2013/12/anti-forgery-tokens-using-mvc-web-api-and-angularjs/ 但问题是指令是在控制器之后执行的.所以如果你想在控制器中检索初始数据是非常困难的.

不要使用指令,只需使用 $http 服务文档中设置 HTTP 标头部分下的 Module.run() 方法http://docs.angularjs.org/api/ng.$http.

我使用了上面博客文章中引用的 HtmlHelper 扩展和 body 元素,然后我的 Module.run() 看起来像这样:

myModule.run(['$http', function($http) {$http.defaults.headers.common['RequestVerificationToken'] = angular.element("body").attr('ncg-request-verification-token');}]);

我认为这是一个非常优雅的解决方案.

I'd like to pass a RequestVerificationToken which is generated by a Razor MVC helper in my login form to an AngularJS service that I've done to manage the authentication of my application

my form is the following:

<div ng-model="loginRequest" >
        <form ng-submit="submit()"  ng-controller="loginCtrl">
            @Html.AntiForgeryToken()

            <input id="username" ng-model="loginRequest.Username"  type="text" name="text"  />
            <input id="password" ng-model="loginRequest.Password" type="text" name="text" />
            <input type="submit" id="submit" value="Submit" />
            <br/>
            isValid: {{loginRequest.isValid}}
            <br/>
            username: {{loginRequest.Username}}
            <br/>
            Password: {{loginRequest.Password}}
        </form>
    </div>

the @Html.AntiForgeryToken() renders in this way:

<input name="__RequestVerificationToken" type="hidden" value="AVzyqDKHSPjaY7L_GTpkasMAABRQRVRFUkFMSUVOV0FSRVxQZWRybwA1">

my AngujarJs controller injects successfully my "loginService" and I can send via Post the username and the password to the service

function loginCtrl($scope, loginService) {
   $scope.submit = function () {
      loginService.authenticate($scope.loginRequest,function(data) {
          $scope.loginRequest.isValid = (data.User!=null);
          //console.log(data);
      });

   };
}

the service:

angular.module('App.services', ['ngResource']).
    factory('loginService',
        function ($resource) {
            return $resource('/Api/User/login', '',
                {
                        authenticate: {
                        method: 'POST',
                        isArray: false,
                        headers: { 'X-XSRF-Token': '?????' }
                    }
                });
        });

my question is how can I read the token rendered in the form and pass it to the service and set a header with the token taken from the login form, as far I as Know is not a good practice to manipulate the DOM and I don't know if I'll need to create a directive to perform that task so any suggestions are welcome!

解决方案

I think I've found a pretty good solution. I started with the suggestions here http://www.novanet.no/no/blog/olav-nybo/dates/2013/12/anti-forgery-tokens-using-mvc-web-api-and-angularjs/ but the problem was that the directive is executed after the controller. So if you wanted to retrieve initial data in the controller it was very difficult.

Instead of using the directive just use the Module.run() method as referenced in the $http service documentation under the Setting HTTP Headers section http://docs.angularjs.org/api/ng.$http.

I used the HtmlHelper extension referenced in the blog post above with the body element and then my Module.run() looks like this:

myModule.run(['$http', function($http) {
    $http.defaults.headers.common['RequestVerificationToken'] = angular.element("body").attr('ncg-request-verification-token');
}]);

I think it makes for a pretty elegant solution.

这篇关于AngularJS 将 requestVerificationToken 传递给服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆