Authentication with Laravel

Hi All,

I’m trying to use Ionic to login to my backend system which is built on Laravel.

This is what I have for the login.ts file:

      export class LoginPage {

     apiUrl = "https://mydomain.com";
    private myData: any;

       constructor(public navCtrl: NavController, public navParams: NavParams, public http: Http) {

   }

   doLogin (formData) {


this.myData = formData.value;
let body = JSON.stringify({
  email: formData.value.email,
  password: formData.value.password
});
console.log(body);
let headers = new Headers({
   "Accept": "application/json",
   "Authorization": "Bearer: Pwjxo8aSrRGrdFutYSGqbbBy9Qtn5wyX",
});
this.http.post(this.apiUrl + '/api/authenticate', JSON.stringify(body), {
    headers: headers
  }).subscribe(function(data) {
    console.log('received response');
  });
 }

}

But I’m having an issue with CORS , although on the Laravel side CORS is enabled.

  Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header contains  multiple values '*, http://localhost:8100', but only one is allowed. Origin 'http://localhost:8100' is therefore not allowed access.

Does anyone have any ideas?

You need to add a middleware that will add the appropriate Access Control header. For example:

/**
 * Headers.
 * 
 * @var array
 */
protected $headers = [
    'Access-Control-Allow-Origin' => '*',
];

/**
 * Handle an incoming request.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Closure  $next
 * @return mixed
 */
public function handle($request, Closure $next)
{
    $response = $next($request);

    foreach($this->headers as $key => $value) {
        $response->headers->set($key, $value);
    }

    return $response;
}

You can add additional headers as needed.

Have you tried setting Access-Control-Allow-Origin to just ‘*’ (in your Laravel code)?

Yes I added Access-Control-Allow-Origin the main index.php file and also used Middleware to allow for this but still unable to connect.

The errors message says you’re using ‘*, http://localhost:8100. Have you tried using only the star, as ‘*’?