In an app which mixes Laravel and Angular, I have this persistent CSRF token mismatch error coming up when calling a route from an Angular service. This is more or less how it's set up:
ROUTES
Route::group(['middleware' => ['web'] ], function () {
// non-auth routes (e.g. signup, login) ...
Route::group(['middleware' => 'auth'], function() {
Route::get('w/{ignore?}', function () { return view('writer.index');})
->where('ignore', '.*');
Route::match(['get', 'post'], 'doc/open', 'Controller#openItem');
});
});
The writer.index view shows up fine without token error (the user has been authenticated).
The VIEW includes:
<meta name="csrf-token" content="{{ csrf_token() }}" />
and
<script>
$(function(){
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var token = $('meta[name="csrf-token"]').attr('content');
if (token) {
return xhr.setRequestHeader('X-CSRF-TOKEN', token);
}
});
});
</script>
From Angular, a service is producing a request to the doc/open route over $http.post which returns the token mismatch error.
I checked the headers and the $http.post did in fact send over a value for X-XSRF-TOKEN. However, this header value does not match the XSRF-TOKEN value in the cookie. If that's the mismatch, why is it occurring?
In laravel 5.3, this is made simple with Passport package. I was having the same trouble with Angular resource requests. I fixed it by installing Passport via composer and adding the following lines to
app\Http\Kernel.php
protected $middlewareGroups = [
'web' => [
\stix\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\stix\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
\Laravel\Passport\Http\Middleware\CreateFreshApiToken::class,
],
Now laravel will automatically include X-CRSF-TOKEN for every request made within the web middleware group. Hope this helps.
Related
NodeJs configured and running fine with passportJS OAuth2, but the requirement is angular should call node api, both are runs in different ports, calling all nodeJS's rest API from angular and it runs fine using proxy.conf.json, while calling /googleauth/redirect from angular getting error response.
Response :
Failed to load https://accounts.google.com/o/oauth2/v2/auth?response_type=code... No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.
Google API Setting :
Restrictions
Authorised JavaScript origins :
http://localhost:4200
http://localhost:8088
Authorised redirect URIs :
http://localhost:4200/api/googleauth/redirect
http://localhost:8088/api/googleauth/redirect
Update 1 : CORS to app.js (new): but no changes.
var cors = require('cors');
var app = express();
app.use(cors());
app.options('*', cors());
app.use('/api',cors(),require('./routes/api'));
Update 2 : api.js
router.get('/google', passport.authenticate('google', { scope: ['profile','email'] }));
passport setup
const passport = require('passport');
const GoogleStrategy = require('passport-google-oauth20');
const userModel = require('../model/user');
passport.serializeUser((user,done)=>{
done(null,user.id);
});
passport.deserializeUser((id,done)=>{
userModel.findById(id).then((user)=>{
done(null,user);
})
});
passport.use(
new GoogleStrategy({
callbackURL:'/api/googleauth/redirect',
clientID:'',
clientSecret:''
},(accessToken,refreshToken,profile,done) =>{
console.log("call back function fired");
//console.log(accessToken);
userModel.findOne({email:profile.emails[0].value,authType:'google'},function(err,user){
if(user){
done(null,user);
}else{
done(null,user);
}
});
}))
I resolved this problem with a tutorial https://medium.com/#ahsan.ayaz/how-to-handle-cors-in-an-angular2-and-node-express-applications-eb3de412abef
Only lack a detail... next to the lines
import { BrowserXhr } from ‘#angular/http’;
and
import {CustExtBrowserXhr} from ‘./app/path-to-file/cust-ext-browser-xhr’;
you should add
import { LocationStrategy, HashLocationStrategy } from '#angular/common';
I am trying to build an angular + laravel rest application. I can get the views of my database. When I try to add new items. I get 500 error telling me mismatch csrf token.
My form layout is :
<form class="form-horizontal" ng-submit="addItem()">
<input type="text" ng-model="itemEntry" placeholder="Type and hit Enter to add item">
</form>
This is how I try to add item to database :
$scope.addItem = function(CSRF_TOKEN) {
$http.post('/shop', { text: $scope.itemEntry, csrf_token: CSRF_TOKEN} ).success(function(data, status) {
if(data) {
var last = _.last($scope.items);
_token = CSRF_TOKEN;
$scope.items.push({text: $scope.itemEntry, bought: false, id: (last.id + 1) });
$scope.itemEntry = '';
console.log($scope.items);
} else {
console.log('There was a problem. Status: ' + status + '; Data: ' + data);
}
}).error(function(data, status) {
console.log('status: ' + status);
});
}
Here is my filter that I use for my application:
Route::filter('csrf', function()
{
if (Session::token() != Input::get('_token'))
{
throw new Illuminate\Session\TokenMismatchException;
}
});
In my blade views I use this and it works :
<input type="hidden" name="_token" value="{{ csrf_token() }}" />
How can I send the csrf_token when I use html forms?
Thanks
Edit 1 :
Adding header to post request like this does not give errors.
$http({
method : 'POST',
url : '/shop',
data : $scope.itemEntry, // pass in data as strings
headers : { 'Content-Type': 'application/x-www-form-urlencoded' }
});
An option will be to inject the CSRF token as a constant. Append the following in your head tag:
<script>
angular.module("app").constant("CSRF_TOKEN", '{{ csrf_token() }}');
</script>
Then in your module methods it can be injected when needed.
app.factory("FooService", function($http, CSRF_TOKEN) {
console.log(CSRF_TOKEN);
};
Maybe you will be interested of peeking at the source code of this sample Laravel + AngularJS project.
the accepted solution by Rubens Mariuzzo works, however I think that I have found an alternative solution which I think is better.
This way you don't have to pass data from the html script into your angularjs app and there is a better separation of concerns. E.g. This allows you to have your Laravel APP as just an API.
My solution involves getting the CSRF token via an api request and setting this value as a constant.
Further, instead of injecting the CSRF token when needed, you set the token in a default header which would get checked by the server upon any API http request.
Example shows laravel, however any serious framework should be able to offer something similar.
CSRF Route in LARAVEL:
// Returns the csrf token for the current visitor's session.
Route::get('api/csrf', function() {
return Session::token();
});
Protecting Routes with the before => 'api.csrf' Filter
// Before making the declared routes available, run them through the api.csrf filter
Route::group(array('prefix' => 'api/v1', 'before' => 'api.csrf'), function() {
Route::resource('test1', 'Api\V1\Test1Controller');
Route::resource('test2', 'Api\V1\Test2Controller');
});
The api.csrf filter
// If the session token is not the same as the the request header X-Csrf-Token, then return a 400 error.
Route::filter('api.csrf', function($route, $request)
{
if (Session::token() != $request->header('X-Csrf-Token') )
{
return Response::json('CSRF does not match', 400);
}
});
The AngularJS stuff put this in app.js:
Blocking Version:
var xhReq = new XMLHttpRequest();
xhReq.open("GET", "//" + window.location.hostname + "/api/csrf", false);
xhReq.send(null);
app.constant("CSRF_TOKEN", xhReq.responseText);
app.run(['$http', 'CSRF_TOKEN', function($http, CSRF_TOKEN) {
$http.defaults.headers.common['X-Csrf-Token'] = CSRF_TOKEN;
}]);
Non-Blocking Version
var xhReq = new XMLHttpRequest();
xhReq.open("GET", "//" + window.location.hostname + "/api/csrf", true);
xhReq.onload = function(e) {
if (xhReq.readyState === 4) {
if (xhReq.status === 200) {
app.constant("CSRF_TOKEN", xhReq.responseText);
app.run(['$http', 'CSRF_TOKEN', function($http, CSRF_TOKEN) {
$http.defaults.headers.common['X-Csrf-Token'] = CSRF_TOKEN;
}]);
}
}
};
xhReq.send(null);
Now the CSRF_TOKEN constant is injected as a header in ALL http requests from the AngularJS app and ALL API routes are protected.
If you use Laravel 5, no need to add CSRF token to Angular http headers.
Laravel 5 with Angular do this automatically for you.
http://laravel.com/docs/5.1/routing#csrf-x-xsrf-token
I think my solution is less pain and much more flexible, especially it thinks testing your App on Karma.
Firstly add this code your master view
<meta name="csrf-token" content="{{ csrf_token() }}">
We have saved csrf token into html content without adding route.
Now we protect all requests of AngularJs App by CSRF token
/**
*
* when it thinks testing your app unit test with Karma,
* this solution was better than getting token via AJAX.
* Because low-level Ajax request correctly doesn't work on Karma
*
* Helper idea to me :
* http://stackoverflow.com/questions/14734243/rails-csrf-protection-angular-js-protect-from-forgery-makes-me-to-log-out-on/15761835#15761835
*
*/
var csrftoken = (function() {
// not need Jquery for doing that
var metas = window.document.getElementsByTagName('meta');
// finding one has csrf token
for(var i=0 ; i < metas.length ; i++) {
if ( metas[i].name === "csrf-token") {
return metas[i].content;
}
}
})();
// adding constant into our app
yourAngularApp.constant('CSRF_TOKEN', csrftoken);
We need to setup default http headers for Angular. Let's add our csrf token to Angular's headers
/*
* App Configs
*/
blog.config(['$httpProvider', 'CSRF_TOKEN',
function($httpProvider, CSRF_TOKEN) {
/**
* adds CSRF token to header
*/
$httpProvider.defaults.headers.common['X-CSRF-TOKEN'] = CSRF_TOKEN;
}]);
Finally we have to need new filter for this changes on side of laravel..
Route::filter('csrfInHeader', function($route, $request) {
if (Session::token() !== (string) $request->header('X-CSRF-TOKEN') ) {
throw new Illuminate\Session\TokenMismatchException;
}
});
"csrfInHeader" filter will check all http request by angular app. You are not need adding csrf token to every each request. Plus if you test your app by Karma, you will not effort to getting csrf token on testing..
The easiest way to do it as
Route::get('/getToken','Controller#getToken');
In your web or api.php file
In Controller
public function getToken(){
return csrf_token();
}
Place this code
In Angular app
$http.get("http://localhost:8000/getToken")
.then(function(response) {
alert(response.data)
});
Safe way to get csrf_token()
There is a site and a web api. All the files I receive from the web api server.
I have an ADFS OAUTH2 authorization on the site.
And I need get the images from the web api with the auth token.
So now I do something like this:
<img src='webApiUrl/Photo/Id?token=token_value' alt />
But I have got a bug with token length. It is very long for some clients and I cannot control it.
I can send the authorization header with the xhr request but I do not understand how to set the authorization header for the site which requests the resources from the html via src.
Can you help me to fix it?
Whenever you have an HTTP request to the Web API you can use Angular Interceptors to put your token on the request header. Here I chose to demonstrate the Bearer authentication. Like this:
appName.config(["$httpProvider", ($httpProvider: ng.IHttpProvider) => {
$httpProvider.interceptors.push(<any>["$q", "$location",
($q: ng.IQService, $location: ng.ILocationService) => {
return {
// config is the request data, including all its properties
'request': (config) => {
// Intercepting only the API requests
if (config.url.indexOf(apiServerUrl) >= 0) {
// Getting the token from local storage for example
var token = localStorage.getItem("token");
// Placing the token in the right header
if (token)
config.headers["Authorization"] = "Bearer " + token;
}
return config;
}
}
}
]);
}]);
Maybe this would solve your problem: http://blog.jsgoupil.com/request-image-files-with-angular-2-and-an-bearer-access-token/
It involves registering a pipe so that you can use secure src attributes with your img tags.
I'm using Laravel and Angular to write a web app.
In the front end Laravel is used to create the basic template, but otherwise controlled by Angular. In the back end laravel is used to create a restful API.
I have a few routes like this:
Route::group(['domain' => 'domain.com'], function() {
Route::get('/', ['as' => 'home', function () {
return view('homepage');
}]);
Route::get('/login', ['as' => 'login', function () {
return view('login');
}]);
//users should be authenticated before accessing this page
Route::get('/dashboard', ['as' => 'dashboard', function () {
return view('dashboard');
}]);
});
Route::group(['domain' => 'api.domain.com', 'middleware' => ['oauth']], function() {
Route::post('/post/create', ['uses' => 'PostController#store']);
Route::get('/post/{id}', ['uses' => 'PostController#show']);
//other API endpoints
// ...
});
I want to make sure my domain.com/dashboard URL is only accessed by authenticated users.
In my backend I have OAuth implemented for my API routes which makes sure the user accessing those routes are authentic. Laravel's Auth::once() is used by the OAuth library to make sure the user credentials are correct then generates an access_token. Since Auth::once() is a "stateless" function no session or cookies are utilized and I cannot use Auth::check() to make sure a user is authenticated before the dashboard page is rendered.
How should I go about checking to see if the user trying to access domain.com/dashboard is authenticated? Should I send the access_token in the header when I forward the user from /login to /dashboard? Or should I implement Laravel's a session/cookie based authentication?
EDIT: As per this: Adding http headers to window.location.href in Angular app I cannot forward the user to the dashboard page with an Authorization header.
In order to reuse my API for my mobile apps I STRONGLY prefer to use some sort of token based authentication.
I would advise to use JWT (JSON Web Tokens) to control for authentication.
I think there are several tutorials for their use with Lavarel and AngularJS. I'm more into Python and I use Flask, but the followings look interesting :
Simple AngularJS Authentication with JWT : the AngularJS configuration
Token-Based Authentication for AngularJS and Laravel Apps : the connection with Laravel
JSON Web Token Tutorial: An Example in Laravel and AngularJS
Pierre was right in suggesting JWT for your token based auth.
When the user successfully logs in, before you finish the request, you can create a JWT and pass that back to the client. You can store it on the client (localStorage, sessionStorage) if you want. Then on subsequent requests, put the JWT inside of your Authorization header. You can then check for this header in your middleware and prevent access to your API routes if the token is valid. You can also use that token on the client and prevent Angular from switching routes if the token doesn't exists or isn't valid.
Now if you are trying to prevent the user from accessing the page entirely on initial load (Opens browser, goes straight to domain.com/dashboard), then I believe that is impossible since there is no way to get information about the client without first loading some code on the page.
Not sure about Angular, as I have never used it, but have you tried targeting a controller with your dashboard route? For example
Route::get('/dashboard', [
'uses' => 'UserController#getDashboard',
'as' => 'dashboard',
'middleware' => 'auth'
]);
UserController.php (I'm assuming you have a blade called dashboard.blade.php)
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
class UserController extends Controller
{
public function getDashboard()
{
if(Auth::user()) {
return view('dashboard');
} else {
redirect()->back();
}
}
}
Also, you could always group whichever routes you want to protect with this (taken from the Laravel 5.2 documentation):
Route::group(['middleware' => 'auth'], function () {
Route::get('/', function () {
// Uses Auth Middleware
});
Route::get('user/profile', function () {
// Uses Auth Middleware
});
});
EDIT: Regarding the session token, your login blade should have this in its code:
<input type="hidden" name="_token" value="{{ Session::token() }}">
When the /dashboard HTML loads, does it already include data specific to the user's account?
I would suggest to load the /dashboard HTML separately from the user's data, and hide the dashboard items with ng-cloak while Angular loads the data to populate it.
Redirect to /dashboard URL
Load (static?) dashboard HTML / Angular app, hiding all parts with ng-cloak.
Have Angular access the API using the access_token to load all dashboard data.
Revealing the parts of the dashboard when the data from the API comes in, or showing an error message if the access_token wan't valid.
That way, your /dashboard HTML could actually be just a static HTML file and directly served by the web server and cached by any proxy on the way.
If that isn't an option, you could put your access_token into a cookie with Javascript that runs on the /login view, then redirect to /dashboard, then have your server-side /dashboard view read the cookie to check if the access_token is valid. But that sounds messy and mixes up things that should be separated.
#Pierre Cordier #Mr_Antivius Thank you guys for your answer, it helped me get insight into the problem and allowed me to tinker with with JWT but ultimately did not product a solution for me.
To allow only authenticated users to access domain.com/dashboard I had to implement a hybrid session and OAuth authentication system. I decided to go with Sentinel (instead of Laravel's out of the box auth system) because it has a user permission system I need in other places in my app. I use this library for the OAuth Server.
Here is what I do in my controller:
POST domain.com/auth/authenticate:
public function processLogin(Request $request)
{
$credentials = [
'email' => $request->input('username'),
'password' => $request->input('password'),
];
try
{
$sentinel = Sentinel::authenticate($credentials);
}
catch (\Cartalyst\Sentinel\Checkpoints\ThrottlingException $e)
{
$response = ['error' => [$e->getMessage()]];
$httpStatus = 429;
return response()->json($response, $httpStatus);
}
catch (\Cartalyst\Sentinel\Checkpoints\NotActivatedException $e)
{
$response = ['error' => [$e->getMessage()]];
$httpStatus = 401;
return response()->json($response, $httpStatus);
}
if ($sentinel) //user credentials correct
{
//get oauth token
$oauthToken = Authorizer::issueAccessToken();
$response = ['success' => true, 'user' => ['id' => $sentinel->id, 'email' => $sentinel->email]] + $oauthToken;
$httpStatus = 200;
}
else
{
$response = ['success' => false, 'error' => ['Incorrect credentials']];
$httpStatus = 401;
}
return response()->json($response, $httpStatus);
}
Here is the method the OAuth library looks at to authenticate the user:
public function verifyAuth($email, $password)
{
$credentials = [
'email' => $email,
'password' => $password,
];
if ($user = Sentinel::stateless($credentials))
{
return $user->id;
}
else
{
return false;
}
}
This would create a response like so:
{
"success": true,
"user": {
"id": 1,
"email": "email#domain.tld"
},
"access_token": "6a204bd89f3c8348afd5c77c717a097a",
"token_type": "Bearer",
"expires_in": 28800,
"refresh_token": "092a8e1a7025f700af39e38a638e199b"
}
Hope this helps someone out there
Side Note: I'm sending a POST request to domain.com/auth/authenticate instead of api.domain.com/auth/authenticate because I could not get domain.com/dashboard to recognize sentinel's cookie if I posted to api.domain.com. I've tried changing domain in config/session.php to .domain.com but still nothing. Maybe I'm doing something wrong?
I am trying to build an angular + laravel rest application. I can get the views of my database. When I try to add new items. I get 500 error telling me mismatch csrf token.
My form layout is :
<form class="form-horizontal" ng-submit="addItem()">
<input type="text" ng-model="itemEntry" placeholder="Type and hit Enter to add item">
</form>
This is how I try to add item to database :
$scope.addItem = function(CSRF_TOKEN) {
$http.post('/shop', { text: $scope.itemEntry, csrf_token: CSRF_TOKEN} ).success(function(data, status) {
if(data) {
var last = _.last($scope.items);
_token = CSRF_TOKEN;
$scope.items.push({text: $scope.itemEntry, bought: false, id: (last.id + 1) });
$scope.itemEntry = '';
console.log($scope.items);
} else {
console.log('There was a problem. Status: ' + status + '; Data: ' + data);
}
}).error(function(data, status) {
console.log('status: ' + status);
});
}
Here is my filter that I use for my application:
Route::filter('csrf', function()
{
if (Session::token() != Input::get('_token'))
{
throw new Illuminate\Session\TokenMismatchException;
}
});
In my blade views I use this and it works :
<input type="hidden" name="_token" value="{{ csrf_token() }}" />
How can I send the csrf_token when I use html forms?
Thanks
Edit 1 :
Adding header to post request like this does not give errors.
$http({
method : 'POST',
url : '/shop',
data : $scope.itemEntry, // pass in data as strings
headers : { 'Content-Type': 'application/x-www-form-urlencoded' }
});
An option will be to inject the CSRF token as a constant. Append the following in your head tag:
<script>
angular.module("app").constant("CSRF_TOKEN", '{{ csrf_token() }}');
</script>
Then in your module methods it can be injected when needed.
app.factory("FooService", function($http, CSRF_TOKEN) {
console.log(CSRF_TOKEN);
};
Maybe you will be interested of peeking at the source code of this sample Laravel + AngularJS project.
the accepted solution by Rubens Mariuzzo works, however I think that I have found an alternative solution which I think is better.
This way you don't have to pass data from the html script into your angularjs app and there is a better separation of concerns. E.g. This allows you to have your Laravel APP as just an API.
My solution involves getting the CSRF token via an api request and setting this value as a constant.
Further, instead of injecting the CSRF token when needed, you set the token in a default header which would get checked by the server upon any API http request.
Example shows laravel, however any serious framework should be able to offer something similar.
CSRF Route in LARAVEL:
// Returns the csrf token for the current visitor's session.
Route::get('api/csrf', function() {
return Session::token();
});
Protecting Routes with the before => 'api.csrf' Filter
// Before making the declared routes available, run them through the api.csrf filter
Route::group(array('prefix' => 'api/v1', 'before' => 'api.csrf'), function() {
Route::resource('test1', 'Api\V1\Test1Controller');
Route::resource('test2', 'Api\V1\Test2Controller');
});
The api.csrf filter
// If the session token is not the same as the the request header X-Csrf-Token, then return a 400 error.
Route::filter('api.csrf', function($route, $request)
{
if (Session::token() != $request->header('X-Csrf-Token') )
{
return Response::json('CSRF does not match', 400);
}
});
The AngularJS stuff put this in app.js:
Blocking Version:
var xhReq = new XMLHttpRequest();
xhReq.open("GET", "//" + window.location.hostname + "/api/csrf", false);
xhReq.send(null);
app.constant("CSRF_TOKEN", xhReq.responseText);
app.run(['$http', 'CSRF_TOKEN', function($http, CSRF_TOKEN) {
$http.defaults.headers.common['X-Csrf-Token'] = CSRF_TOKEN;
}]);
Non-Blocking Version
var xhReq = new XMLHttpRequest();
xhReq.open("GET", "//" + window.location.hostname + "/api/csrf", true);
xhReq.onload = function(e) {
if (xhReq.readyState === 4) {
if (xhReq.status === 200) {
app.constant("CSRF_TOKEN", xhReq.responseText);
app.run(['$http', 'CSRF_TOKEN', function($http, CSRF_TOKEN) {
$http.defaults.headers.common['X-Csrf-Token'] = CSRF_TOKEN;
}]);
}
}
};
xhReq.send(null);
Now the CSRF_TOKEN constant is injected as a header in ALL http requests from the AngularJS app and ALL API routes are protected.
If you use Laravel 5, no need to add CSRF token to Angular http headers.
Laravel 5 with Angular do this automatically for you.
http://laravel.com/docs/5.1/routing#csrf-x-xsrf-token
I think my solution is less pain and much more flexible, especially it thinks testing your App on Karma.
Firstly add this code your master view
<meta name="csrf-token" content="{{ csrf_token() }}">
We have saved csrf token into html content without adding route.
Now we protect all requests of AngularJs App by CSRF token
/**
*
* when it thinks testing your app unit test with Karma,
* this solution was better than getting token via AJAX.
* Because low-level Ajax request correctly doesn't work on Karma
*
* Helper idea to me :
* http://stackoverflow.com/questions/14734243/rails-csrf-protection-angular-js-protect-from-forgery-makes-me-to-log-out-on/15761835#15761835
*
*/
var csrftoken = (function() {
// not need Jquery for doing that
var metas = window.document.getElementsByTagName('meta');
// finding one has csrf token
for(var i=0 ; i < metas.length ; i++) {
if ( metas[i].name === "csrf-token") {
return metas[i].content;
}
}
})();
// adding constant into our app
yourAngularApp.constant('CSRF_TOKEN', csrftoken);
We need to setup default http headers for Angular. Let's add our csrf token to Angular's headers
/*
* App Configs
*/
blog.config(['$httpProvider', 'CSRF_TOKEN',
function($httpProvider, CSRF_TOKEN) {
/**
* adds CSRF token to header
*/
$httpProvider.defaults.headers.common['X-CSRF-TOKEN'] = CSRF_TOKEN;
}]);
Finally we have to need new filter for this changes on side of laravel..
Route::filter('csrfInHeader', function($route, $request) {
if (Session::token() !== (string) $request->header('X-CSRF-TOKEN') ) {
throw new Illuminate\Session\TokenMismatchException;
}
});
"csrfInHeader" filter will check all http request by angular app. You are not need adding csrf token to every each request. Plus if you test your app by Karma, you will not effort to getting csrf token on testing..
The easiest way to do it as
Route::get('/getToken','Controller#getToken');
In your web or api.php file
In Controller
public function getToken(){
return csrf_token();
}
Place this code
In Angular app
$http.get("http://localhost:8000/getToken")
.then(function(response) {
alert(response.data)
});
Safe way to get csrf_token()