How do Laravel get GET request made by vue.js? - laravel-5

Vue.js HTTP call
methods :{
login(){
var data ={
client_id: 2,
client_secret: '5YVQ6rsSehoh5BOWsxAU3KxGeqT1tCRGHn5dx1iX',
grant_type: 'password',
username : this.email,
password: this.password
}
//send a GET request using Vue-Resource
this.$http.get("http://localhost/kubikt2/public/api/login", data)
.then(response=>{
console.log(response)
})
}
}
Laravel
Route::get('api/login',function(Illuminate\Http\Request $req){
$arr["echo"]=$req->all();
$arr["test"]="OK!!";
return json_encode($arr);
}
As you can see, echo $req->getContent(); return nothing in Laravel.
check this out
How do I access the var data sent by Vue.js in Laravel ?

$req->all() is empty because no data is passed!
A GET request only evaluates data passed as query-string in the URI. It acts like the data parameter is null.
You could send your data as query (like "localhost/kubikt2/public/api/login?email"+email+"&someMore"+someMore) or use a POST request (which would be the better option here)

Related

i have token in header of ajax and when i get dd return null

i wanna send GET request from frontend to backend
i mean i want to send token from frontend to middlware
i mean i want get token from cookie and push in GET request and send for one of route in api.php that the route is GET method
i mean i want to push my token in ajax and send to laravel
infact i have two laravel project that i want send token from one to another
i mean i want push my token in header in ajax and get in backend with laravel
so see my code in the below fisrt my route from backend
later my jquery and then middleware
but my current problem is that when i dd header is is null
thanks
Route::get('/customers', 'App\Http\Controllers\CustomerController#show');
//
$.ajax({
url: "http://localhost:8000/api/customers",
type: "GET",
headers: {
"Authorization": getCookie("access_token")
}
});
//
dd($request->header('Authorization'));
if ($request->hasHeader('Authorization')) {
$access_token = $request->header('Authorization');
$query = DB::table("admins")->where("access_token", $access_token)->first();
if (isset($access_token) && $access_token == $query->access_token) {
return $next($request);
} else {
return response()->json([
"status" => 401,
"message" => "شما اجازه دسترسی ندارید",
]);
}
}

Axios JWT doesn't send

I have a project divided in two layers. The back-end is developed in spring boot, secured by Sprint security and JWT, and the front-end is developed in Vue.js, using Axios library for communication between layers.
I receive the "Bearer token" authentication properly, and all the authentication process is done correctly. The issue appears when I try to send a request with a token header to access content but the token doesn't send, and the Spring boot returns null without the content.
Here is the code
getOffers: function () {
if (localStorage.getItem("userSession")) {
this.aux = JSON.parse(localStorage.getItem("userSession"));
this.token = this.aux.token;
this.tokenHeader = "Bearer "+this.token;
alert(this.tokenHeader)
};
console.log(`Bearer ${this.token}`)
axios.
get('http://localhost:8080/api/v1/offer', {'Authorization' : `Bearer ${this.token}`})
.then(response => {
console.log(response);
this.offers = response.data
}).catch(e => console.log(e))
}
P.S: When I make a request in Postman, it works fine and returns the desired object. Here is a postman example:
postman
Correct way to pass header is :
axios.get(uri, { headers: { "header1": "value1", "header2": "value2" } })
In your case try this:
axios.get('http://localhost:8080/api/v1/offer', { headers:{Authorization : `Bearer ${this.token}`} })
Also, check in console if this gives correct Bearer token:
console.log(`Bearer ${this.token}`)
Register the Bearer Token as a common header with Axios so that all outgoing HTTP requests automatically have it attached.
window.axios = require('axios')
let bearer = window.localStorage['auth_token']
if (bearer) {`enter code here`
window.axios.defaults.headers.common['Authorization'] = 'Bearer ' + bearer
}
And no need to send bearer token on every request.

Can not get laravel cookie laravel_token while consuming own API

Cookie is avaiable in browser but can not get it even can not check if it exists .
working on laravel and vuejs app where I am using passport for authentication.
I am consuming own api with vuejs so I have added CreateFreshApiToken middleware in kernel.php
vuejs is creating and sending laravel_token cookie successfully but I can not read it using vuejs or javascript.
since I can not check if cookie is available or not I can not check if user is logged in or not.
How I will tell vuejs that user is logged in and take to intended route ?
For now I am saving access_token in localStorage and sending it with each request but I am looking for a solution which can help to use laravel builtin laravel_token cookie to authenticate and authorize the users.
More Details
If i run this command in console then I get response
document.cookie.match('XSRF-TOKEN')
But
document.cookie.match('laravel_token')
returns null
I think the tick icon in the shown image at top is sign of making it private or something that makes it inaccessible.
Update
I found something from internet
But I still want to know how I can tell vuejs app that user is logged in or not ??
Update 2
For now I am sending access_token in header manually from vuejs and it is working fine.
if(localStorage.getItem('laravel_token') !== 'undefined' && !! localStorage.getItem('laravel_token') == true){
window.axios.defaults.headers.common['Authorization'] = 'Bearer '+ localStorage.getItem('laravel_token')
}
A little work around will be for you to implement the authenticated method in your LoginController, and return a json success code. You can then receive this code and store.
public function authenticated(Request $request, $user)
{
// return redirect()->intended($this->redirectPath());
return json_encode(['authenticated' => true]);
}
Using axios...
axios.post('/login', {
email: user.username,
password: user.password
}).then(response => {
.then(response => {
console.log(response)
//response.data.authenticated will return true if user has been authenticated
})
}).catch(err => {
console.log(err)
})

Axios AJAX call nulls parameter

I use Vuejs to create my frontend for my project.
At the creation of one component ('TimeCapsy.vue'), I make an AJAX call to my backend like this:
created: function () {
if (verify.verify_login()) {
let token = this.$cookies.get('jwt_us_cas');
let params = {'jwt': token};
console.log(params);
axios({
method: 'post',
url: dev.HOST+'getuserinfoobject',
params: queryString.stringify(params)
})
.then(response => {
console.log(response.data)
})
}
}
As you can see I use the
this.$cookies.get('jwt_us_cas');
to get the a json web token, that I set on the client at the login.
I use the queryString Library to stringify my parameters for my request.
I also tried it without the queryString.stringify(params) call, but I get the same error, e.g. the parameter still turns into null.
When I look at the console log, where I check the params variable, I get this output:
{jwt: "my token comes here"}
So I can see, that it gets the correct value from the cookie.
But when I check the answer from my backend (PHP), I get this error:
Undefined index: jwt in <b>D:\casb\public\index.php</b> on line <b>52</b>
Of course I know that it means, that jwt is null, but I can't understand why.
As I said, right before I make the call I check the params and it shows the token.
I checked the endpoint with Postman and the token as the jwt parameter and it returned a successfull call with the correct answer.
A correct answer is basically just a nested object with some information in it.
My PHP endpoint is pretty basic too:
Router::add('/getuserinfoobject', function () {
$response['response'] = User::getUserInfoObject($_POST['jwt']);
echo json_encode($response);
}, 'post');
So I guess that right before or in my call it nulls my parameter. But I can't understand how, since I make a lot of requests and never had this problem.
From axios docs
params are the URL parameters to be sent with the request
Which means, you should get the value with PHP $_GET.
Or $_REQUEST (which stores both $_GET, $_POST. Also $_COOKIE).
The other hand, you can use data key as docs says
data is the data to be sent as the request body
Only applicable for request methods PUT, POST, and PATCH
So the value would be available in $_POST
axios({
method: 'post',
url: dev.HOST+'getuserinfoobject',
data: {
jwt: token
}
})

How to add Authorization header in vueJs

I'm trying to send a post request from a vuejs app to a spring backend with which I'm attaching a jwt authorization header.
I have tried with vue-resource
Vue.http.headers.common['Authorization'] = 'Bearer YXBpOnBhc3N3b3Jk';
and the backend headers are like this
{accept-language=en-US,en;q=0.5, origin=http://localhost:8080, host=127.0.0.1:8084, access-control-request-headers=authorization, connection=keep-alive,...
But if i use postman to send the same request, the backend headers are like this
{authorization=Bearer eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI1OTBhYWFmMjRhNjQ3ZjRiYmZlMDBhMDQiLCJzdWIiOiJiYmIiLCJpYXQiOjE0OTM5NzUxMDQsInJvbGVzIjoidXNlciIsImV4cCI6MTQ5Mzk3NTQ2NH0.kldUh3H1i3xEiNcxQ2ecq1HsjIIF5BI8Q-tb3sALc3E, content-length=0, accept-language=en-US,en;q=0.8,.......
My question is, how can i achieve the postman header using vuejs. I have tried with axios as well but without success.
Try this way with axios. I'm using spring backend too and it works..
axios.post(
url,
query ,
{headers: {
"header name" : "header value"
}}
)
.then((response) => {
var response = response.data;
}, (error) => {
var error = error.response;
}
}
)

Resources