rodzzlessa's avatar

CSRF in separate angular app

So I'm building an API for a client. I decided to use Laravel 5 everything works fine except for posting data. I looked online for answers and they all said to include the laravel {{csrf_token()}} function; however, my angular app is a completely separate app in another server than the laravel API. what are some best practices for me to fix this issue?

0 likes
5 replies
Phillipp's avatar

Hmm you can get it with an ajax call to your api server. I think it should work.

davorminchorov's avatar

I was wondering the same thing but is it safe to include the csrf token in the json response?

nolros's avatar

@rodzzlessa

token() is a php call from the the client to the Laravel server. So you can pull JS from an NPM server and then in the JS code make a call to the Laravel server, or you can have an NPM server make a call to the Laravel server. The token is set in the users Session. You can also disable CSRF and create you own using Angular's.

Somewhere in your JS. Assuming JQuery, but you can do this with any DOM lookup.

var getToken = function(){
        return $('#mme-token').prop('value');
};

You would have some AJS method that then uses submits the token. I'm not including the AJS service provider for brevity sake.

    $scope.add = function() {
        $scope.isFormValid = true;

        var token = getToken();

        if(! isBlankOrEmpty(token)) {
            $scope.d._token = token;
        } else {
            $scope.isFormValid = false;
            throw "Form verification valid!! Please stop and login!";
        }

        if($scope.isFormValid) {
            FormService.add($scope.d)
                .success(function(d, status) {

                })
                .error(function() {

                });
        }

    };
davorminchorov's avatar

Cool, I forgot about this blog post. I have it saved on Evernote.

Thanks :)

Please or to participate in this conversation.