Using postman on localhost, I'm able to use POST successfully on my API. But when deployed to a server and using postman, I always get the error 405:MethodNotAllowedHttpException, even though the POST request is stated for the route, took our verifycsrf from middleware, and took out the web middleware. Also followed the CORS installation for laravel project by barryvdh.
Wondering if anyone has any suggestions to fix this?
Kernel:
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* #var array
*/
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
'Barryvdh\Cors\HandleCors',
];
/**
* The application's route middleware groups.
*
* #var array
*/
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
],
'api' => [
'throttle:60,1',
],
'admin' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\App\Http\Middleware\PermissionAdminMiddleware::class,
],
];
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* #var array
*/
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
];
}
cors.php
return [
/*
|--------------------------------------------------------------------------
| Laravel CORS
|--------------------------------------------------------------------------
|
| allowedOrigins, allowedHeaders and allowedMethods can be set to array('*')
| to accept any value.
|
*/
'supportsCredentials' => false,
'allowedOrigins' => ['*'],
'allowedHeaders' => ['*'],
'allowedMethods' => ['*'],
'exposedHeaders' => [],
'maxAge' => 5,
'hosts' => [],
];
app.php includes Barryvdh\Cors\ServiceProvider::class,
routes.php
Route::group(
[
'prefix' => 'api',
'middleware' => ['cors']
],
function()
{
Route::post('dummy', 'API\UsersController#dummy');
}
);
UsersController.php
namespace App\Http\Controllers\API;
use App\Http\Controllers\FP\UserController;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Database\Eloquent\ModelNotFoundException;
class UsersController extends Controller
{
function dummy(Request $request){
return "test";
}
}
Add Accept header in postman to application/json.
Related
I hosted laravel (Laravel Framework 8.40) and reactjs application on a subdomain. I installed Laravel Sanctum and sometimes it's working perfectly and sometimes i got an error about cors.
I configured one staging environment and one production environment like this :
Stating
Frontend : dev.domain.com
Backend : devapi.domain.com
Production
Frontend : domain.com
Backend : api.domain.com
As you can see on the 2 screenshots bellow in one environment i have cors issue and in the other environment i don't have it. And sometimes it's the reverse. Actually both have exactly the same code.
Api.php
Route::post('/signin', [AccountController::class, 'signin']);
Route::post('/signup', [AccountController::class, 'signup']);
Route::post('/reset_password', [AccountController::class, 'reset_password']);
Route::post('/confirm_account', [AccountController::class, 'confirm_account']);
Route::post('/send_mail_confirm_account', [AccountController::class, 'send_mail_confirm_account']);
Route::group(['middleware' => 'auth:sanctum'], function (){
Route::post('/signout/{user_id}', [AccountController::class, 'signout']);
});
Kernel.php
<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* #var array
*/
protected $middleware = [
// \App\Http\Middleware\TrustHosts::class,
\App\Http\Middleware\TrustProxies::class,
\Fruitcake\Cors\HandleCors::class,
\App\Http\Middleware\PreventRequestsDuringMaintenance::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
];
/**
* The application's route middleware groups.
*
* #var array
*/
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
// \Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [
'throttle:api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
];
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* #var array
*/
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
];
}
Cors.php
<?php
return [
/*
|--------------------------------------------------------------------------
| Cross-Origin Resource Sharing (CORS) Configuration
|--------------------------------------------------------------------------
|
| Here you may configure your settings for cross-origin resource sharing
| or "CORS". This determines what cross-origin operations may execute
| in web browsers. You are free to adjust these settings as needed.
|
| To learn more: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
|
*/
'paths' => ['api/*', 'sanctum/csrf-cookie'],
'allowed_methods' => ['*'],
'allowed_origins' => ['*'],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => true,
];
RouteServiceProvider.php
<?php
namespace App\Providers;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Facades\Route;
class RouteServiceProvider extends ServiceProvider
{
/**
* The path to the "home" route for your application.
*
* This is used by Laravel authentication to redirect users after login.
*
* #var string
*/
public const HOME = '/home';
/**
* The controller namespace for the application.
*
* When present, controller route declarations will automatically be prefixed with this namespace.
*
* #var string|null
*/
// protected $namespace = 'App\\Http\\Controllers';
/**
* Define your route model bindings, pattern filters, etc.
*
* #return void
*/
public function boot()
{
$this->configureRateLimiting();
$this->routes(function () {
Route::prefix('api')
->middleware('api')
->namespace($this->namespace)
->group(base_path('routes/api.php'));
Route::middleware('web')
->namespace($this->namespace)
->group(base_path('routes/web.php'));
});
}
/**
* Configure the rate limiters for the application.
*
* #return void
*/
protected function configureRateLimiting()
{
RateLimiter::for('api', function (Request $request) {
return Limit::perMinute(60)->by(optional($request->user())->id ?: $request->ip());
});
}
}
Thank's for your help 🙏
try add this header
var config = {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
withCredentials: false
}
axios.post(apiBaseUrl, payload, config)
So right now I'm using Laravel's default auth for api routes by doing this:
Route::group(['middleware' => ['auth:api']], function() {
...
}
The only thing with this is that it will throw a 401 if a non logged in user hits that page.
What I'm wondering is if there's a way to have a route that will login the user if a token is sent, but if not, they can still hit the api.
I know this will most likely be a custom Middleware, but I don't have a lot of experience with creating Middlewares so I'm not really sure where to start
EDIT
app/Http/Kernel.php
<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* #var array
*/
protected $middleware = [
// \App\Http\Middleware\TrustHosts::class,
\App\Http\Middleware\TrustProxies::class,
\Fruitcake\Cors\HandleCors::class,
\App\Http\Middleware\PreventRequestsDuringMaintenance::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
];
/**
* The application's route middleware groups.
*
* #var array
*/
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
// \Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [
'throttle:1000,1',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
\Fruitcake\Cors\HandleCors::class,
],
];
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* #var array
*/
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'admin' => \App\Http\Middleware\IsAdmin::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'cors' => \Fruitcake\Cors\HandleCors::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
];
}
Here's a pretty simplified version of my routes api.php file
routes/api.php
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
Route::group(['prefix' => 'v2', 'middleware' => ['cors:api']], function() {
//routes that people need to be logged into to do
Route::group(['middleware' => ['auth:api']], function() {
Route::post('/comments/save/{type}/{id}', 'App\Http\Controllers\Api\v2\CommentController#save');
Route::get('/leagues/{id}', 'App\Http\Controllers\Api\v2\LeaguesController#get');;
});
Route::post('/auth/login', 'App\Http\Controllers\Api\v2\AuthController#login');
Route::post('/contact', 'App\Http\Controllers\Api\v2\ContactController#sendMessage');
});
Basically I'm wanting the ability to hit the /leagues/{id} route with either a logged in user or a non logged in user. And if the user is logged in grab the user via Auth::user(). If it helps at all, I'm using React for a front end and sending an api_token in the Authorization header like Bearer $token.
I figured out a way by creating my own custom Middleware. For anyone interested, here it is:
<?php
namespace App\Http\Middleware;
use Closure;
use Auth;
use App\Models\User;
class OptionalAuthenticate
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
$header = $request->header('Authorization');
if(!empty($header)){
$token = str_replace('Bearer ', '', $header);
$user = User::where('api_token', '=', $token)->first();
if(!empty($user)){
Auth::login($user);
}
}
return $next($request);
}
}
I am building a laravel application where I have web and api routes.
I want to store sessions between my routes.
If i store as session without returning a view, it works fine.
But when i return a view my session no longer exists.
My web.php is as follows:
Route::get('/', 'ViewController#index');
Route::get('/check', 'ViewController#check');
My controller
public function index(Request $request)
{
$request->session()->put('test','123456');
$request->session()->save();
//echo $request->session()->get('test', 'default_value');
// return view('welcome'); //If I uncomment this the sessions are not working anymore.
}
public function check(Request $request)
{
echo $request->session()->get('test', 'default_value');
var_dump($request->session()->all());
//return view('welcome');
}
Maybe it has something to do that i also store sessions in my api routes in the api controllers. My api.php:
Route::group(['middleware' => ['web']], function () {
//board
Route::get('/board/create', 'BoardController#create');
Route::post('board/{id}/guess', 'BoardController#guessWord');
Route::get('/board/set', 'BoardController#set');
Route::get('/board/get', 'BoardController#get');
//user
Route::get('/user', 'UserController#get');
Route::post('/user/create', 'UserController#create');
});
kernel.php
<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* #var array
*/
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
\App\Http\Middleware\TrustProxies::class,
];
/**
* The application's route middleware groups.
*
* #var array
*/
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
// \Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [
'throttle:60,1',
'bindings',
],
];
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* #var array
*/
protected $routeMiddleware = [
'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
];
}
Thanks!
From the docs api routes does not use StartSession middleware because session is only available in web group of middlewares
So store session only in web routes
i have problem with laravel's (5.5) middlewares. Firstly, i created a middleware called AdminPanelAuth
Thats my middleware:
<?php
namespace App\Http\Middleware;
use Closure;
use Auth;
class AdminPanelAuth
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if(Auth::user() && Auth::user()->hasRole('admin'))
{
return $next($request);
}
else{
return redirect()->route('home');
}
}
}
and registered to Kernel.php
<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* #var array
*/
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
\App\Http\Middleware\TrustProxies::class,
];
/**
* The application's route middleware groups.
*
* #var array
*/
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
// \Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [
'throttle:60,1',
'bindings',
],
];
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* #var array
*/
protected $routeMiddleware = [
'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
'admin' => \App\Http\Middleware\AdminPanelAuth::class,
'auth.basic' =>
\Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' =>
\Illuminate\Routing\Middleware\SubstituteBindings::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' =>
\Illuminate\Routing\Middleware\ThrottleRequests::class,
];
}
And i put that new admin middleware to my route file,
Route::group(
[
'namespace' => 'Backpack\Base\app\Http\Controllers',
'middleware' => ['web', 'admin'],
'prefix' => config('backpack.base.route_prefix'),
],
function () {
...
};
Admin middleware does not work for my routes. I've been tried to put this in web.php but nothings changed, still not working for me.
ps. i allready use composer dump-autoload, php artisan clear:compiled and php artisan optimize.
Thanks for your helps, best regards!
Try separating web middleware from admin like this:
Route::group(['middleware' => 'web', 'prefix' => config('backpack.base.route_prefix')], function () {
...
Route::group(['middleware' => 'admin'], function() {
...
});
...
};
EDIT:
In your middleware add use Illuminate\Support\Facades\Auth;
And in your Kernel, add admin middleware you created under throttle
EDIT 2:
Kernel.php
protected $middlewareGroups = [
'web' => [
...
\App\Http\Middleware\AdminPanelAuth::class, //Make sure your middleware is last in array
],
...
]
web.php
Route::group(['middleware' => 'web', 'prefix' => config('backpack.base.route_prefix')], function () {
...
};
I am using Laravel 5.2.32, the validation of it is not work. I have tried to find solution on google and stackoverflow. However, the solution which can fix the 5.2.20 to 5.2.26 cannot fix the problem of laravel 5.2.32. Who can help me?
I have changed the router in the web middleware, the code as the following:
Route::group(['middleware' => ['web']], function () {
Route::get('/', function () {
return view('app/welcome');
});
Route::post('/signup', 'UserController#postSignup');
Route::post('/signin', 'UserController#postSignin');
Route::get('/dashboard', 'UserController#getDashboard');
Route::get('/logout', 'UserController#getLogout');
});
I also change the Kernel.php as the following. But it's still not work.
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\app\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\app\Http\Middleware\VerifyCsrfToken::class,
];
The code in my controller as below:
namespace app\Http\Controllers;
use app\User;
use Illuminate\Http\Request;
use app\Http\Requests;
use Illuminate\Support\Facades\Auth;
use Illuminate\View\Middleware\ErrorBinder;
use Validator;
class UserController extends Controller
{
// public function __construct()
// {
// $this->middleware('auth');
// }
public function postSignUp(Request $request)
{
$this->validate($request, [
'email' => 'required | email | unique:users',
'first_name' => 'required | max:60',
'password' => 'required | min:8'
]);
if ($request['password'] === $request['password_confirmation'])
{
$user = new User();
$user->first_name = $request['first_name'];
$user->email = $request['email'];
$user->password = bcrypt($request['password']);
$user->save();
Auth::login($user);
return view('app/dashboard');
}
// return redirect()->back();
}
}
you don't need the middleware web in your route anymore as its baked in to the latest version, s can do without the following:
Route::group(['middleware' => ['web']], function () {...
and your kernel something like...
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* #var array
*/
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
];
/**
* The application's route middleware groups.
*
* #var array
*/
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
],
'api' => [
'throttle:60,1',
],
];
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* #var array
*/
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'can' => \Illuminate\Foundation\Http\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
];