Search code examples
phpangularlaravelauthenticationcors

Error with CORS in project with Angular and Laravel


I'm working on a web project where I'm using Angular and Laravel. I managed to create a registration form successfully, thus creating users and solving the CORS issue. Now I'm facing a similar problem with the Login part. It's not working properly as it's giving me a CORS error again only in login, not in the registration form. Here's how my files are configured:

UserController:

public function store(Request $request){

$credentials = $request->only('email','password');

if (Auth::attempt($credentials, $request->filled('remember'))) {
    $request->session()->regenerate();

    return redirect()->intended('/');
}
return back()->withErrors([
    'email' => 'The provided credentials do not match our records.',
]);

}

api.php:

Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
return $request->user();
});

Route::post('/users/store', [UserController::class, 'store']);

Cors.php: <?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class Cors
{
/**
 * Handle an incoming request.
 *
 * @param  \Closure(\Illuminate\Http\Request): 
(\Symfony\Component\HttpFoundation\Response)  $next
 */
public function handle(Request $request, Closure $next): Response
{
    $response = $next($request);

    $response->headers->set('Access-Control-Allow-Origin', '*');
    $response->headers->set('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT, DELETE, HEAD');
    $response->headers->set('Access-Control-Allow-Headers', 'Content-Type, Accept, Authorization, X-Requested-With, Application');
    return $response;
}

}

And this is my service from Angular:

loginUser(userData: any): Observable<any>{
const requestOptions = {
    withCredentials: true
};
return this.http.post('http://localhost:8000/api/users/store', userData, requestOptions);

}


And the error message when I press the button for login:

Access to XMLHttpRequest at 'http://localhost:8000/api/users/store' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute. message: "Http failure response for http://localhost:8000/api/users/store: 0 Unknown Error" POST http://localhost:8000/api/users/store net::ERR_FAILED


Solution

  • Add this to your Cors.php:

    $response->headers->set('Access-Control-Allow-Credentials', 'true');