"The GET method is not supported for this route. Supported methods: POST" message in my laravel API - laravel

I followed a tutorial to do a login page with an external api, but my API is not working.
In the localhost http://localhost:8000/api/auth/login appear "The GET method is not supported for this route. Supported methods: POST." and in the Chrome DevTools
headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
message: "Http failure response for http://127.0.0.1:8000/api/auth/register: 422 Unprocessable Entity"
name: "HttpErrorResponse"
ok: false
status: 422
statusText: "Unprocessable Entity"
url: "http://127.0.0.1:8000/api/auth/register"
I use laravel 6,php 7, ionic 4
Please, help me!
(tutorial is: https://blog.flicher.net/laravel-rest-api-passport-authentication-for-ionic-app/)

If you follow the tutorial in section Step 6 — Set API routes it list down all routes for api.
Here it says as below
File: api.php
Route::group([
'prefix' => 'auth'
], function () {
Route::post('login', 'Auth\AuthController#login')->name('login');
});
That means we have a route with name as login which would be a POST request and url would be api/auth/login as it is api.php file.
You are calling it from the browser, that would be a get request, which is not found by laravel in routes, so it is generating this error.
Reference: Laravel Routing

Related

Laravel Socialite Github - error 401 Unauthorized/Bad credentials

I've got fresh installation of Laravel 9 with Socialite package. This is my config/services.php file:
'github' => [
'client_id' => 'xxx',
'client_secret' => 'xxx',
'redirect' => 'http://localhost:3000/login',
],
From my frontend Nuxt application, I redirect to github oauth page https://github.com/login/oauth/authorize?client_id=xxx which works fine. I confirm authorization for my account and then it redirects me back to my frontend http://localhost:3000/login as this URL is set in my GitHub settings for Authorization callback URL.
In return URL I have my code for authorization: http://localhost:3000?code=xxx
Then I do axios call to my Laravel server:
axios({
method: "post",
url: 'http://localhost/api/auth/socialite/github',
data: qs.stringify({
client_id: 'xxx',
client_secret: 'xxx',
code: this.$route.query.code,
redirect_uri: 'http://localhost:3000/login',
response_type: 'code'
}),
headers: {
"Content-Type": "application/x-www-form-urlencoded"
}
})
On server side, in routes/api.php I have this route:
Route::post("auth/socialite/{provider}", function($provider){
return Socialite::driver($provider)->stateless()->user();
});
And when I'm trying to return user from github using Socialite, it returns this error:
Client error: `GET https://api.github.com/user` resulted in a `401 Unauthorized` response:{"message":"Bad credentials","documentation_url":"https://docs.github.com/rest"}
So Socialite calls this URL https://api.github.com/user with my credentials and is trying to get user from github if I understand it right. But somehow it returns the error. I have checked my client_id, client_secret, redirect URL...
I'm sure everything works fine until I call Socialite::driver..., because If I kill the process with for example dd($provider) before Socialite::driver... it returns "github" as it should. And If I kill the process and take generated code parameter from github page and I'm trying to do the same call on Postman with my credentials, Github returns me token.
So I would expect for Socialite call to do the same.
I have two questions:
Is my structure of code (communication of frontend with backend and back, usage of Socialite package...) right?
Why it is showing me error when the same call in Postman works?

Laravel Sanctum returns 404 instead of 401 unauthenticated

I am using laravel/sanctum package for authenticating my api. I have followed all the steps from the documentation but I get 404 not found when using an invalid token for hitting a guarded route instead of 401.
Route::group(['middleware' => ['auth:sanctum']], function () {
Route::post("/upload", [AuthController::class, "uploadFile"]);
Route::post('/me', [AuthController::class, 'me']);
});
few steps to follow
clear cache
test.ca/api/upload - make sure you have 'api' in url (from where you are calling)
add 'Accept application/json' in your request header.

Laravel Sanctum - sanctum/csrf-cookie (204 "No content")

Laravel sanctum has been a bit of a headache for me as i have spent hours trying to figure out why sanctum/csrf-cookie route returns no content. initially the same route return 404 not found but after adding 'prefix' => 'api/sanctum' config/sanctum.php it seems to work except that it outputs nothing and no cookie is set in my browser.
Here are some of my codes
.env
SANCTUM_STATEFUL_DOMAINS=localhost:8080
SPA_URL=http://localhost:8080
SESSION_DOMAIN=localhost
--config/cors.php
'paths' => [
'api/*',
'login',
'logout',
'register',
'user/password',
'forgot-password',
'reset-password',
'sanctum/csrf-cookie',
'user/profile-information',
'email/verification-notification',
],
'allowed_methods' => ['*'],
'allowed_origins' => ['*'],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => true,
axios
export const authClient = axios.create({
baseURL: process.env.VUE_APP_API_URL,
withCredentials: true, // required to handle the CSRF token
});
and having done all of that, if i tried to generate a token using
axios.get('/sanctum/csrf-cookie').then(response => {
// Login...
});
i get 204 no content response
i have also added the api middleware in kernel.php as instructed in the doucmentation but still wont set the cookie. and when i try to make request to another route protected by sanctum i 419 token mismatch.
i have also run a fresh installation of laravel, php artisan optimize, cleared my brower history, checked the endpoints in postman but still thesame 204 and 419 exceptions
I was struggling with the same issue for days and then founded a way that worked.
so :
The '/sanctum/csrf-cookie' route return a 204 response when successfull, the then you have to send your post request with credentials. i used to get a 419 reponse status.
so after followed laravel docs here is what i added :
SPA
make sure you set the withCredentials header to true
API
.env
SESSION_DRIVER=cookie
SESSION_DOMAIN='.localhost'
SANCTUM_STATEFUL_DOMAINS='localhost,127.0.0.1'
.kernel.php
add in your middleware array : \Illuminate\Session\Middleware\StartSession::class
Hey I don't know whether you've found the answer or not but that request meant to have empty response body. Your CSRF token is available in the header of the response ;D
From HTTP Specification:
The HTTP 204 No Content success status response code indicates that a request has succeeded, but that the client doesn't need to navigate away from its current page. This might be used, for example, when implementing "save and continue editing" functionality for a wiki site.
According to specification 204 is the exptected response from server.
You can insert in bootstrap.js file
import axios from 'axios';
window._ = _;
window.axios = axios;
window.axios.defaults.baseURL = "/api/";
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

Rapid API, Google Translate post request with laravel

I need to use the Google Translate API in my Laravel application, get requests are working fine, but post requests don't seem to, I tried with Postman and got the same error message.
Here's the test I made:
Route::get('/', function () {
return Http::withHeaders([
"content-type" => "application/x-www-form-urlencoded",
"accept-encoding"=> "application/gzip",
"x-rapidapi-key"=> "<rapid_api_key_here>",
"x-rapidapi-host"=> "google-translate1.p.rapidapi.com",
"useQueryString"=> true
])->post('https://google-translate1.p.rapidapi.com/language/translate/v2/detect', [
"q"=> "English is hard, but detectably so",
]);
});
Here's the test with Postman:
Here's the error I got in both tests:
I don't know what went wrong, any suggestions?
You can try using Route::post method instead of get as you're making a post request here.
Context: https://laravel.com/docs/5.0/routing#basic-routing

Can't get auth user with laravel passport, keep getting "Unauthenticated" error

I can't get the information of the authenticated user in a Laravel passport app with JWT and vue.
I've installed laravel passport. Ive done everything in the documentation and added:
\Laravel\Passport\Http\Middleware\CreateFreshApiToken::class,
To consume it with js for a SPA app.
I've protected my routes with the auth:api middleware, but i keep getting:
{"Status":{"api_status":0,"Code":401,"Message":"Unauthenticated"}}
When i use postman to manually insert the CSRF-TOKEN in Authorization Bearer Token. It does give me the auth user.
Whatever i do, i keep getting null on Auth::user(); in my controllers and routes
Laravel V5.7
Node V10.15.3
Npm V.6.9.0
You need to send a POST request (using Postman/Insomnia) with the details of the user you want to log in as to /oauth/token in your app which will respond with an API token. You save this api token locally, and then add add it as a Header variable to your guzzle/axios/whatever function's http calls (every one of them!) to your API.
$http = new GuzzleHttp\Client;
$data = 'Whatever';
$response = $http->request('POST','api/user',[
'data' => $data,
'headers' => [
'Accept' => 'application/json',
'Authorization' => 'Bearer xxxxxxxxxxxxThis is the long authentication string returned from the Postman requestxxxxxxxxxxxxxx'
]
]);
dd(json_decode((string) $response->getBody())); // To view the response
From: https://laravel.com/docs/5.5/passport#creating-a-password-grant-client

Resources