Laravel API返回401

时间:2019-06-24 04:41:21

标签: angular laravel ionic-framework

我正在开发移动应用程序,并且每次我尝试执行需要用户身份验证的操作时,我都会通过API将应用程序连接到服务器,但我收到401错误,而与postman进行的操作相同没问题。

我做了什么

  1. 将令牌存储到设备本地存储
  2. 检索该令牌并将其作为请求标头发送到服务器
  3. 'Accept': 'application/json, text/plain',添加到标头请求
  4. 添加了this package,以打开我的后端CROS起源。

代码

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'
  ]);
}
  

对于此示例,我共享了注销方法的其他方法,例如   更新,删除,存储是相同的结构。

结果

one

two

three

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

已解决

在我的情况下,我发现了令牌来自服务器并存储到本地存储的问题,因为令牌的结果是:

{success{token:xfdhgkhkhewrh}}

我必须获得

这样的令牌
'Authorization': 'Bearer' + " " + this.token.success.token

来自本地存储。 TOKEN UNDEFINED是返回401的问题。

答案 1 :(得分:0)

几天来,我使用POST方法遇到了类似的问题,最终切换到一种简单的GET方法。这是我下面的工作代码,直到提供一种POST方法方法的解决方案为止。

Laravel 5.5代码:

创建Cors中间件,然后在下面粘贴代码;

  

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');
    }
}

将CORS中间件注册到全局HTTP中间件堆栈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']);
    }

这是我正在使用的Ionic 5的方法。

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;
      })
    );
  }

希望,这会有所帮助!