Get {"message":"Unauthenticated."} when sending POST request to laravel server - php

I have a problem with sending POST request from Vue axios to laravel server with sanctum.
Firstly I'm getting token.
My route of api.php
Route::post('/get_token', function (Request $request) {
$request->validate([
'email' => 'required|email',
'password' => 'required',
'device_name' => 'required'
]);
$user = User::where('email', $request->email)->first();
if (! $user || ! Hash::check($request->password, $user->password)) {
throw ValidationException::withMessages([
'email' => ['The provided credentials are incorrect.'],
]);
}
return $user->createToken($request->device_name)->plainTextToken;
});
vue axios
this.$axios.post('/api/get_token', {
email: this.email,
password: this.password,
device_name: this.device_name,
}).then(response=>{...});
And when I send GET request with received token, it works correctly
vue axios
this.$axios.get('/api/book/all', {
headers: {
"Authorization": 'Bearer ' + this.$store.getters.getToken
}
}).then(response=>{...})
api.php
Route::middleware('auth:sanctum')->get('/book/all', 'BookController#all');
But when I try to send POST request, I get {"message":"Unauthenticated."} and 401 error
vue axios
this.$axios.post('/api/book/add', {
headers: {
"Authorization": 'Bearer ' + this.$store.getters.getToken,
},
data: {
title: this.addingTitle,
author: this.addingAuthor,
}
})
api.php
Route::middleware('auth:sanctum')->post('/book/add', 'BookController#add');
Sorry, I’m just a noob in web and don’t understand many things, hope you can help me.

If you use post then the 1st parameter is the URL and the 2nd one is the data your are posting. In your case it might make more sense to use:
this.$axios({
method: 'POST',
url: '/api/book/add'
headers: {
"Authorization": 'Bearer ' + this.$store.getters.getToken,
},
data: {
title: this.addingTitle,
author: this.addingAuthor,
}
})
or if you want to still use .post then:
this.$axios.post('/api/book/add', {
title: this.addingTitle,
author: this.addingAuthor,
}, {
headers: {
"Authorization": 'Bearer ' + this.$store.getters.getToken,
}
})

Related

Laravel React API returns 404(Not Found) when sending axios post request even though the route is present in api.php

I keep getting 404 error when I try to submit the form even though the routes are correctly placed in api.php.Can somebody please help??
const url = "/api/add-feedback";
const token = process.env.MIX_REACT_APP_API_TOKEN;
const [name, setName] = useState("");
const [email, setEmail] = useState("");
const [review, setReview] = useState("");
const handleSubmit = async (e) => {
e.preventDefault();
const data = {
name: name,
email: email,
review: review
}
const res = await axios.post(url, data, {
headers: {
Authorization: "Bearer " + token,
},
});
if (res.data.status === 200) {
console.log(res.data.message);
}
}
Here is the route in api.php
Route::post('/add-feedback',[ApiController::class,'feedback']);
Here is the ApiController function
public function feedback(Request $res)
{
$data = $res->validate([
'name'=>'required',
'email'=>'required|email',
'review'=>'required'
]);
Feedback::create($data);
return response()->json([
'status' => 200,
'message' => 'Feedback Added Successfully'
]);
}
This is the error I get:
app.js:3415 POST http://127.0.0.1:8000/api/add-feedback 404 (Not Found)
app.js:3880 Uncaught (in promise) Error: Request failed with status code 404
The error is you're using promises with axios, modify your code to something like this:
axios.post(url, data,{
headers: {
Authorization: "Bearer " + token,
},
})
.then((response) => {
if (res.data.status === 200) {
console.log(res.data.message);
}
}, (error) => {
console.log(error);
});
This will send a post request to your route with the data specified.

Laravel passport unauthenticated message

I've been hitting wall for a while now with this, simply I can't get it where is the problem. So I've got backend Laravel and front Vue; logging in is alright, I get token but when I get into one of the routes with auth:api I get "message":"Unauthenticated.". I save token on the front, so should I send it with any request to backend or there is other way around it?
LoginController.php
public function login(Request $request)
{
$login = $request->validate([
'email' => 'required',
'password' => 'required',
]);
if(Auth::attempt($login))
{
return response(['message' => 'Invalid login']);
}
$user = User::where('email', $request->email)->first();
$accessToken = $user->createToken('Laravel Password Grant Client')->accessToken;
return response()->json(['user' => $user, 'access_token' => $accessToken]);
}
api.php
Route::namespace('\\')->middleware('auth:api')->group(function(){
Route::resource('budget', BudgetController::class);
});
user.js
const state = {
token: localStorage.getItem('access_token') || null,
isAuthenticated: localStorage.getItem('access_token') !== null
}
const getters = {
isAuthenticated: state => state.isAuthenticated
}
const actions = {
async retrieveToken({commit}, payload){
console.log(payload)
const response = axios.post(url + '/login', payload)
.then(response => {
const token = response.data.access_token
localStorage.setItem('access_token', token)
commit('setToken', token)
})
}
}
const mutations = {
setToken: (token) => state.token = token
}
Alright, so simply in my second module I used token as a header like this:
const state = {
budget: [],
header: {
headers: {
Authorization: `Bearer ${localStorage.getItem("access_token") || null}`,
withCredentials: true,
"Access-Control-Allow-Origin": "*"
},
}
};
const getters = {
allBudget: (state) => state.budget,
};
const actions = {
async fetchBudget({ commit, state }) {
const response = await axios.get(url, state.header);
console.log(state.header);
commit("setBudget", response.data);
},
};
After that I was getting CORS error so i needed to add two directives at the end of the file xampp\apache\conf\httpd.conf
Header Set Access-Control-Allow-Origin *
Header Set Access-Control-Allow-Headers *

Passport/axios not post username password

I am trying to POST username, password of auth to Laravel/Passport but it always return null
axios.post('http://localhost:8000/api/login', {
withCredentials: true,
auth: {
email: 'agent#test.com',
password: 'qwerty!##$%^'
}
})
.then(res => {
console.log(res);
})
PassportController.php
public function login(){
if(Auth::attempt(['email' => request('email'), 'password' => request('password')])){
$user = Auth::user();
$success['token'] = $user->createToken('MyApp')-> accessToken;
return response()->json(['success' => $success], $this-> successStatus);
}
else{
return response()->json(['email'=>request('email')], 401);
// I return email to see value
// return response()->json(['error'=>'Unauthorised'], 401);
}
}
api.php
Route::post('login', 'PassportController#login');
I checked everything many times, feel everything is ok, but for some reason data not send to passport.
conosle log:
POST http://localhost:8000/api/login 401 (Unauthorized)
{email: null}
email: null
Laravel is probably accessing the POST data's values with request. The axios.post method's second parameter is the object sent as POST data, so you probably meant to just pass the email and password as top-level keys:
axios
.post(
"http://localhost:8000/api/login",
{
email: "agent#test.com",
password: "qwerty!##$%^"
},
{ withCredentials: true }
)
.then(res => {
console.log(res);
});
I suspect that you may be mixing up authentication in general with HTTP ("Basic") Authentication. The auth key is part of the config object that you can pass as a third parameter to axios.post, which would control just that. I do not think this is what you are after, but just adding it here for completeness. Note that basic auth accepts an username and a password:
axios
.post("http://localhost:8000/api/login", {}, {
withCredentials: true,
auth: {
username: "agent#test.com",
password: "qwerty!##$%^"
}
})
.then(res => {
console.log(res);
});
Finally I solved my issue, the problem is no need to send credentials and auth via axios because from back-end laravel accept post data not auth data, so I passed email and password via form-data not auth:
axios.post("http://localhost:8000/api/login", {
email: "agent#test.com",
password: "qwerty!##$%^"
})
.then(res => {
console.log(res);
});
Now I got token in back-end.

How to post data from VueJS with PHP?

Please Help me, How to post data using the request which made by Vue.js
There's Vue's code
let tests = {
cat1: {
name: 'Auth',
items: {
authorize2: {
name: 'Successful',
subname: '',
request: {
method: 'POST',
link: 'auth',
data: {
login: 'admin',
password: 'password'
}
},
test: (result, status) => {
if (status.status == 200) {
return true;
}
return false;
}
}}}}
PHP page which receives this code doesn't have anything in POST data storage.
Originally Vue used the vue-resource package to perform POST requests via the $http instance property:
login(){
var data = {
login: 'admin',
password: 'password'
}
this.$http.post('/auth', data)
.then(response => { /* success callback */ }, response => { /* error callback */ })
}
In Vue2 vue-resource was retired and they started to recommend Axios. They also offered a way to override the $http instance property allowing you to invoke the axios library in a similar way.
this.$http.post('/auth', data)
.then(response => { /* success callback */ })
.catch(error => { /* error callback */ })
Or you can just load the Axios Package and call it directly:
const axios = require('axios');
...
axios.post('/auth', data)
.then(response => { /* success callback */ })
.catch(error => { /* error callback */ })
You could even choose to use vanilla js or another library like jQuery and use $.ajax() to make the request within your Vue instance, but using axios is the current recommendation from Vue.

Laravel/angular - 400 bad request

I am making an app in ionic and the backend is made in Laravel. I am working on a password reset functionality, and I keep getting the above mentioned error, when I am testing endpoints in chrome. This is the code for the contact information function:
sendContactConfirmation: function(contact, reset) {
var defer = $q.defer();
if(reset == 'reset'){
var endpointUrl = $http.post(AppSettings.apiUrl + "/users/reset", { phone: contact });
}
else {
var endpointUrl = $http.post(AppSettings.apiUrl + "/users", { phone: contact });
}
endpointUrl.then(function(result) {
service.set(result.data.user);
defer.resolve(result);
}, function(error) {
defer.reject(error);
});
return defer.promise;
},
And these are the routes in my Laravel back-end:
Route::group(['jwt.auth', ['except' => ['authenticate']], 'prefix' => 'api', 'namespace' => 'Api'], function() {
Route::post('authenticate', 'AuthenticateController#authenticate');
Route::get('authenticate/user', 'AuthenticateController#getAuthenticatedUser');
Route::post('users', 'UsersController#register');
Route::post('users/reset', 'UsersController#resetContact');
Route::put('users/{user}/reset', 'UsersController#resetPassword');
Route::put('users/{user}', 'UsersController#update');
Route::put('users/{user}/activate', 'UsersController#activate');
Route::post('users/{user}/pic', 'UsersController#uploadPicture');
});
And this is the resetContact function:
public function resetContact(Request $request)
{
$this->validate(
$request,
['phone' => 'required|regex:/^[0-9]{8}$/']
);
$user = User::where('phone', $request->get('phone'))->firstOrFail();
if ($user) {
try {
$this->sendValidationCode($user, 'reset');
}
catch (\Exception $e) {
throw new ApiException($e->getMessage(), 500);
}
}
return response()->json([
'user' => $user,
]);
}
Not sure why do I get this 400 Bad request error for this.
When using Laravel JWT make sure you always send the token for all routes under jwt.auth otherwise you will get the error 400 = Token not provided. In ionic make sure your toke is provided on each call to your laravel endpoint to avoid this error.

Categories