Search code examples
angularlaravelauthenticationlaravel-passport

Laravel Passport and Angular giving me unauthorized on api/login route but works fine on postman?


i am having this problem and have been trying to solve it and search the internet for solution but i didn't find anything helping me, I have this app that have Laravel with Passport on the backend and Angular in the Client side, i am trying to authenticate user through http://localhost:8000/api/login route and it's working fine on postman and giving me the token but on Angular giving me unauthorized and unable to get token, i tried a get request on the laravel api and it's getting me data and showing in Angular so get request is working fine with me the problem is with post request although i have checked the login credentials many times and it's correct

usercontroller.php which contains login method

    class UserController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth:api')->except(['login' , 'register' , 'get_articles']);
    }

  public function register(Request $request)
    {
        $validator = Validator::make($request->all() , [
            'name' => 'required|min:3|max:100',
            'email' => 'required|email|unique:users,email',
            'password' => 'required|min:6|max:100',
            'c_password' => 'required|same:password'
        ]);

        if($validator->fails())
        {
            return response()->json(['errors' => $validator->errors()] , 400);
        }

        $user = new User;
        $user->email = $request->input('email');
        $user->name = $request->input('name');
        $user->password = Hash::make($request->input('password'));
        $user->save();
        return response()->json(['message' => 'created user successfully'] , 201);
    }


    public function login(Request $request)
    {

        if(Auth::attempt(['email' => request('email') , 'password' => request('password')]))
        {
            $user = Auth::user();
            $success['token'] = $user->createToken('myapp')->accessToken;
            return response()->json(['success' => $success] , 200);
        }

        return response()->json(['error' => 'unauthorized'] , 401);
    }

Cors.php

<?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' , 'GET,POST,PUT,DELETE,OPTIONS')
        ->header('Access-Control-Allow-Headers' , 'Origin , Content-Type, Accept, Authorization, X-Request-With')
        ->header('Access-Control-Allow-Credentials' ,  'true');
    }
}

here is login.component.ts

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Loginform } from '../loginform';
import { LoginService } from '../login.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {

  constructor(private http:HttpClient , private LoginService: LoginService) { }

  public submitted = false;
  public errorMsg;
  public email = "";
  public pass = "";

  public Loginform = new Loginform(this.email , this.pass);

  ngOnInit() {
  }

  onSubmit() {
    this.LoginService.login(this.Loginform).subscribe((data) => {console.log(data)} , 
      (error) => {//this.errorMsg = error.statusText
      console.log(error)});
      this.submitted = true;
  }

}

and login.service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Loginform } from './loginform';
import { catchError } from 'rxjs/operators';
import { throwError } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class LoginService {

  constructor(private http: HttpClient) { }

  public url: string = "http://localhost:8000/api/login"; 

  login(loginform : Loginform) {
    return this.http.post(this.url , loginform).pipe(catchError(this.handleError))
  }

  handleError(error: HttpErrorResponse) {
    return throwError(error);
  }

}

and here is a snapshot of postman with the same credentials postman snapshot

and a picture for the error in the browser browser


Solution

  • Maybe this could happen because you're doing two request with different Content-Type: in case of Postman you are using Form-Data with a key-value body, instead in Angular6 service you are trying to send data as JSON.

    Two different solutions:

    1. Serialize JSON object from Laravel Controller;
    2. Try to send your data with 'Content-Type': 'multipart/form-data' in Angular6.