mardi 29 mars 2016

Laravel CORS headers not shown if user is not auth'ed

So I'm trying to create an API using Laravel, everything was going well until it came to that point where I have to connect it with Angular on another subdomain. I'm using JWT token-based auth which works fine.

I have created a CORS middleware like this:

<?php
namespace App\Http\Middleware;
use Closure;
class Cors
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     *
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        return $next($request)
            ->header('Access-Control-Allow-Origin', '*')
            ->header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT, DELETE')
            ->header('Access-Control-Allow-Credentials', 'true')
            ->header('Access-Control-Max-Age', '10000')
            ->header('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Requested-With');
    }
}

Added in Kernel.php and created Route group like this:

Route::group(['middleware' => 'cors'], function () {
    Route::group(['prefix' => 'api/v1'], function() {
        Route::get('/test', 'MemberController@test');
    });  
});

I'm trying to create a call that checks if user is authenticated and returns that to angular app so the app knows what to show.

I trued like this:

public function test()
{
    if(Auth::check()){
        echo "logged in";
    } else {
        echo "nuno";
    }
}

But that returns the page without CORS headers, but if I remove "else" statement and only leave "if auth" it will return the page with headers.

Also, another problem I have is that JWT returns 400 if the token is invalid or not supplied.



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1SsZ4yR
via IFTTT

Aucun commentaire:

Enregistrer un commentaire