简体   繁体   中英

Angularjs no token in the Header

I don't understand something or missing something I think. I have a LoginPage to authorize user (that's Angularjs 1.5) As Back-end I have a Scala/Play Application that verify User and pwd so now I have the Problem that in the Login Service everything get fine

        var token = $cookies["XSRF-TOKEN"];
        if (token) {
            $http.get('http://localhost:9000/ping')
                .then(
                    function (response) {
                        return $http.get("http://localhost:9000/users/" + response.data.userId)
                    }, function (response) {
                        token = undefined;
                        $cookies["XSRF-TOKEN"] = undefined;
                        return $q.reject("Token invalid");
                    }
                    ).then(
                        function (response) {
                            console.log(response.data);
                        }, function (response) {
                    console.log("error");
                }
            );
        }
        $http.post('http://localhost:9000/login', user)
            .then(function (response) {
            token = response.data.authToken;
            console.log(token);
            var userId = response.data.userId;
            return $http.get('http://localhost:9000/users/' +  userId)
        }, function (response) {
                console.log(response.data.err);
                // return 'empty' promise so the right `then` function is called
                return $q.reject("Login failed");
            }).then(
            function (response) {
                console.log(response);
            }
        )
    }

when I now want to login everything is fine by login 在此处输入图片说明

But in the next case I send an get request to the api and want to check the xsrf cookie but no cookie is sent. 401状态码

here is the Security Trait in Scala -

    def HasToken[A](p: BodyParser[A] = parse.anyContent)(f: String => Long => Request[A] => Result): Action[A] =
Action(p) { implicit request =>
  val maybeToken = request.headers.get(AuthTokenHeader).orElse(request.getQueryString(AuthTokenUrlKey))
  maybeToken flatMap { token =>
    cache.get[Long](token) map { userid =>
      f(token)(userid)(request)
    }
  } getOrElse Unauthorized(Json.obj("err" -> "No Token"))
}

So now my question is - where is the Header Token?

Update: here is my app.js

    'use strict';

    function testInterceptor($rootScope, $q, $timeout) {
    return function(promise) {
        return promise.then(
            function(response) {
                return response;
            },
            function(response) {
                if (response.status == 401) {
                    $rootScope.$broadcast("InvalidToken");
                    $rootScope.sessionExpired = true;
                    $timeout(function() {$rootScope.sessionExpired = false;}, 5000);
                } else if (response.status == 403) {
                    $rootScope.$broadcast("InsufficientPrivileges");
                } else {
                    // Here you could handle other status codes, e.g. retry a 404
                }
                return $q.reject(response);
            }
        );
    };
}

var app=angular.module('telephone', ['ngRoute', 'ngCookies']);
app.factory('testInterceptor', testInterceptor);
app.config(["$httpProvider", "$routeProvider",function ($httpProvider, $routeProvider) {

    $httpProvider.interceptors.push('testInterceptor');

    $routeProvider.when('/login', {templateUrl: '../partials/login.html', controller: 'loginController'});
    $routeProvider.otherwise({redirectTo: '/login'});
}]);

I think you need to add token in default header for next requests so you can add like this

function SetCredentials(user) {
                $http.defaults.headers.common["Authorization"] = 'Bearer ' + user.access_token;
               //Here Token added in header
                $rootScope.globals = {
                    currentUser: {
                        username: user.userName,
                        authdata: user.access_token,
                        userid: user.userId,
                    }
                };

                $cookieStore.put('globals', $rootScope.globals);
                setUsers(user)
            };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM