2

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?

mafortis
  • 6,750
  • 23
  • 130
  • 288
  • I cannot see an Authorization header in your request headers. in attached screenshot. – Sunil Kashyap Jun 24 '19 at 04:44
  • @skdroid but i have it in my code `'/logout', { headers: headers }` what do you think gone wrong? – mafortis Jun 24 '19 at 04:47
  • code is correct might be its Authorization header issue, did you add `Bearer` with B capital? – Sunil Kashyap Jun 24 '19 at 04:51
  • @skdroid yes at some point i replaced `'Authorization': this.token["token_type"] + " " + this.token["access_token"]` with `'Authorization': "Bearer" + " " + this.token` it returned `[object object]` – mafortis Jun 24 '19 at 04:53
  • 1
    You are using a post request without body. Try `return this.http.post(this.env.BASE_URL + '/logout', null, { headers: headers })`. I'd rather use a get request for this purpose. – riorudo Jun 24 '19 at 06:18
  • @riorudo hey man thanks for the advice, i tried `null` body result was the same `401` error and also good to mention that my logout was get method at the first then i read this https://stackoverflow.com/a/38790086/8490993 and i changed it to post anyhow neither post nor get doesn't work :/ – mafortis Jun 24 '19 at 07:08
  • 1
    @mafortis did you find a solution for your problem? – riorudo Jun 26 '19 at 16:54
  • @riorudo not yet – mafortis Jun 28 '19 at 00:12

2 Answers2

1

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.

Community
  • 1
  • 1
mafortis
  • 6,750
  • 23
  • 130
  • 288
0

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!

GSari
  • 51
  • 1
  • 1
  • 8
  • Thanks for sharing your solution 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` error not `post` request. – mafortis Sep 03 '19 at 04:41
  • after double check is get for me but token part is as i said in my comment, (i am using get now.) – mafortis Sep 03 '19 at 05:06
  • In my case, If I switch to a POST method, from my working GET method provided, it gives me an Unauthorized response. I'm not sure where I am getting it wrong. My tokens match and postman tests are working fine. So I am sticking with the Get method for now. – GSari Sep 03 '19 at 05:21
  • using get method is fine as long as you can get the data from server, but if you have problem getting data from server then you might consider checking your token request. – mafortis Sep 03 '19 at 05:24
  • Yeah, I guess I just went over-board trying to get the POST method working for me.. lol. Yes, ur right, get method it is. – GSari Sep 03 '19 at 05:28