mafortis
mafortis

Reputation: 7128

Laravel API return 401

I am working on mobile app and I connected my app to server through API now every time I try to do actions that requires users authentication I get 401 error while same action with postman do the job without issue.

What I did

  1. stored token to device local storage
  2. retrieved that token and send it as request header to server
  3. Additionally added 'Accept': 'application/json, text/plain', to header request
  4. Added this package in order to open my back-end CROS origins.

Code

app

logout() {
    const headers = new HttpHeaders({
      'Accept': 'application/json, text/plain',
      'Authorization': this.token["token_type"] + " " + this.token["access_token"]
    });
    return this.http.post(this.env.BASE_URL + '/logout', { headers: headers })
      .pipe(
        tap(data => {
          this.storage.remove("token");
          this.isLoggedIn = false;
          delete this.token;
          return data;
        })
      )
}

route (back-end)

Route::group(['middleware' => 'auth:api'], function(){
  Route::post('logout', 'Api\AuthController@logout');
});

controller (back-end)

public function logout(Request $request)
{
  $request->user()->token()->revoke();
  return response()->json([
    'message' => 'Successfully logged out'
  ]);
}

For this sample I shared my logout method other methods such as update, delete,store are the same structure.

Results

one

two

three

Any idea?

Upvotes: 2

Views: 5178

Answers (2)

mafortis
mafortis

Reputation: 7128

SOLVED

In my case I found the issue in way that token comes from server and stored to local storage as result of my token was like:

{success{token:xfdhgkhkhewrh}}

I had to get token like

'Authorization': 'Bearer' + " " + this.token.success.token

from local storage. TOKEN UNDEFINED was the issue of returning 401.

Upvotes: 1

GSari
GSari

Reputation: 51

I come across a similar issue using the POST method for days, and ended up switching over to a simple GET method approach. Here's my working code below, until a solution on a POST method approach is provided.

Laravel 5.5 Code:

Create Cors middleware, then paste code below;

app\Http\Middleware\Cors.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, PATCH, DELETE, OPTIONS')
        ->header('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Requested-With, X-XSRF-TOKEN');
    }
}

Register CORS middlerware to global HTTP middleware stack app/Http/Kernal.php.

protected $middleware = [
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
        \App\Http\Middleware\Cors::class,
    ];

routes\api.php

Route::group([
  'middleware' => 'auth:api'
], function() {    
    Route::get('logout', 'YourController@logout');
});

YourController@logout

public function logout(){

        auth('api')->user()->tokens->each(function ($token, $key) {
            $token->delete();
        });

        return response()->json(['message' => 'Successfully logged out']);
    }

Here's the method from Ionic 5, I am using.

logout() {

    const headers = new HttpHeaders({
      'Authorization': this.token["token_type"]+" "+this.token["access_token"]
    });

    return this.http.get(this.env.API_URL + 'logout', { headers: headers })
    .pipe(
      tap(data => {
        this.storage.remove("token");
        this.isLoggedIn = false;
        delete this.token;
        return data;
      })
    );
  }

Hope, this helps!

Upvotes: 0

Related Questions