简体   繁体   English

使用 jwt 成功登录 Laravel 后出现错误 401

[英]Error 401 after successful login to Laravel using jwt

In my Laravel project, I use jwt for user authentication.I successfully login and receive the token.在我的 Laravel 项目中,我使用 jwt 进行用户身份验证。我成功登录并收到了令牌。 I send the token with the Barear prefix in the header but I get a 401 error.Meanwhile, my project works well on localhost, but it has this problem on cpanel hosts.My codes are below我在 header 中发送带有 Barear 前缀的令牌,但出现 401 错误。同时,我的项目在 localhost 上运行良好,但在 cpanel 主机上出现此问题。我的代码如下

//AuthController 
class AuthController extends Controller
{
   public function __construct()
   {
      $this->middleware('JWT', ['except' => ['login', 'signup']]);
   }
   public function login(\Illuminate\Http\Request $request)
   {
       $credentials = request(['username', 'password']);
       $result= new ResultModel();
       if (!$token = auth()->attempt($credentials)) {
          
          $result->message="Wrong username or password";
          $result->code=401;
          $result->is_success=false;
          $result->status=ResultModel::WARNING;
          $result->result= null;
          return response()->json($result, 401);
    }
    $result->result= $token;
    return response()->json($result, 200);
    }
 }

in config/auth.php在 config/auth.php

'defaults' => [
    'guard' => 'api',
    'passwords' => 'users',
],
'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],

    'api' => [
        'driver' => 'jwt',
        'provider' => 'users',
        'hash' => false,
    ],
],
'providers' => [
       'users' => [
           'driver' => 'eloquent',
          'model' => App\User::class,
      ],
     'passwords' => [
        'users' => [
           'provider' => 'users',
           'table' => 'password_resets',
           'expire' => 60,
           'throttle' => 60,
       ],
],
 'password_timeout' => 10800,

and in \config\jwt.php并在 \config\jwt.php

return [

/*
|--------------------------------------------------------------------------
| JWT Authentication Secret
|--------------------------------------------------------------------------
|
| Don't forget to set this in your .env file, as it will be used to sign
| your tokens. A helper command is provided for this:
| `php artisan jwt:secret`
|
| Note: This will be used for Symmetric algorithms only (HMAC),
| since RSA and ECDSA use a private/public key combo (See below).
|
*/

'secret' => env('JWT_SECRET'),

/*
|--------------------------------------------------------------------------
| JWT Authentication Keys
|--------------------------------------------------------------------------
|
| The algorithm you are using, will determine whether your tokens are
| signed with a random string (defined in `JWT_SECRET`) or using the
| following public & private keys.
|
| Symmetric Algorithms:
| HS256, HS384 & HS512 will use `JWT_SECRET`.
|
| Asymmetric Algorithms:
| RS256, RS384 & RS512 / ES256, ES384 & ES512 will use the keys below.
|
*/

'keys' => [

    /*
    |--------------------------------------------------------------------------
    | Public Key
    |--------------------------------------------------------------------------
    |
    | A path or resource to your public key.
    |
    | E.g. 'file://path/to/public/key'
    |
    */

    'public' => env('JWT_PUBLIC_KEY'),

    /*
    |--------------------------------------------------------------------------
    | Private Key
    |--------------------------------------------------------------------------
    |
    | A path or resource to your private key.
    |
    | E.g. 'file://path/to/private/key'
    |
    */

    'private' => env('JWT_PRIVATE_KEY'),

    /*
    |--------------------------------------------------------------------------
    | Passphrase
    |--------------------------------------------------------------------------
    |
    | The passphrase for your private key. Can be null if none set.
    |
    */

    'passphrase' => env('JWT_PASSPHRASE'),

],

/*
|--------------------------------------------------------------------------
| JWT time to live
|--------------------------------------------------------------------------
|
| Specify the length of time (in minutes) that the token will be valid for.
| Defaults to 1 hour.
|
| You can also set this to null, to yield a never expiring token.
| Some people may want this behaviour for e.g. a mobile app.
| This is not particularly recommended, so make sure you have appropriate
| systems in place to revoke the token if necessary.
| Notice: If you set this to null you should remove 'exp' element from 'required_claims' list.
|
*/

'ttl' => env('JWT_TTL', 180),

/*
|--------------------------------------------------------------------------
| Refresh time to live
|--------------------------------------------------------------------------
|
| Specify the length of time (in minutes) that the token can be refreshed
| within. I.E. The user can refresh their token within a 2 week window of
| the original token being created until they must re-authenticate.
| Defaults to 2 weeks.
|
| You can also set this to null, to yield an infinite refresh time.
| Some may want this instead of never expiring tokens for e.g. a mobile app.
| This is not particularly recommended, so make sure you have appropriate
| systems in place to revoke the token if necessary.
|
*/

'refresh_ttl' => env('JWT_REFRESH_TTL', 20160),

/*
|--------------------------------------------------------------------------
| JWT hashing algorithm
|--------------------------------------------------------------------------
|
| Specify the hashing algorithm that will be used to sign the token.
|
| See here: https://github.com/namshi/jose/tree/master/src/Namshi/JOSE/Signer/OpenSSL
| for possible values.
|
*/

'algo' => env('JWT_ALGO', 'HS256'),

/*
|--------------------------------------------------------------------------
| Required Claims
|--------------------------------------------------------------------------
|
| Specify the required claims that must exist in any token.
| A TokenInvalidException will be thrown if any of these claims are not
| present in the payload.
|
*/

'required_claims' => [
    'iss',
    'iat',
    'exp',
    'nbf',
    'sub',
    'jti',
],

/*
|--------------------------------------------------------------------------
| Persistent Claims
|--------------------------------------------------------------------------
|
| Specify the claim keys to be persisted when refreshing a token.
| `sub` and `iat` will automatically be persisted, in
| addition to the these claims.
|
| Note: If a claim does not exist then it will be ignored.
|
*/

'persistent_claims' => [
    // 'foo',
    // 'bar',
],

/*
|--------------------------------------------------------------------------
| Lock Subject
|--------------------------------------------------------------------------
|
| This will determine whether a `prv` claim is automatically added to
| the token. The purpose of this is to ensure that if you have multiple
| authentication models e.g. `App\User` & `App\OtherPerson`, then we
| should prevent one authentication request from impersonating another,
| if 2 tokens happen to have the same id across the 2 different models.
|
| Under specific circumstances, you may want to disable this behaviour
| e.g. if you only have one authentication model, then you would save
| a little on token size.
|
*/

'lock_subject' => true,

/*
|--------------------------------------------------------------------------
| Leeway
|--------------------------------------------------------------------------
|
| This property gives the jwt timestamp claims some "leeway".
| Meaning that if you have any unavoidable slight clock skew on
| any of your servers then this will afford you some level of cushioning.
|
| This applies to the claims `iat`, `nbf` and `exp`.
|
| Specify in seconds - only if you know you need it.
|
*/

'leeway' => env('JWT_LEEWAY', 0),

/*
|--------------------------------------------------------------------------
| Blacklist Enabled
|--------------------------------------------------------------------------
|
| In order to invalidate tokens, you must have the blacklist enabled.
| If you do not want or need this functionality, then set this to false.
|
*/

'blacklist_enabled' => env('JWT_BLACKLIST_ENABLED', true),

/*
| -------------------------------------------------------------------------
| Blacklist Grace Period
| -------------------------------------------------------------------------
|
| When multiple concurrent requests are made with the same JWT,
| it is possible that some of them fail, due to token regeneration
| on every request.
|
| Set grace period in seconds to prevent parallel request failure.
|
*/

'blacklist_grace_period' => env('JWT_BLACKLIST_GRACE_PERIOD', 0),

/*
|--------------------------------------------------------------------------
| Cookies encryption
|--------------------------------------------------------------------------
|
| By default Laravel encrypt cookies for security reason.
| If you decide to not decrypt cookies, you will have to configure Laravel
| to not encrypt your cookie token by adding its name into the $except
| array available in the middleware "EncryptCookies" provided by Laravel.
| see https://laravel.com/docs/master/responses#cookies-and-encryption
| for details.
|
| Set it to true if you want to decrypt cookies.
|
*/

'decrypt_cookies' => false,

/*
|--------------------------------------------------------------------------
| Providers
|--------------------------------------------------------------------------
|
| Specify the various providers used throughout the package.
|
*/

'providers' => [

    /*
    |--------------------------------------------------------------------------
    | JWT Provider
    |--------------------------------------------------------------------------
    |
    | Specify the provider that is used to create and decode the tokens.
    |
    */

    'jwt' => Tymon\JWTAuth\Providers\JWT\Lcobucci::class,

    /*
    |--------------------------------------------------------------------------
    | Authentication Provider
    |--------------------------------------------------------------------------
    |
    | Specify the provider that is used to authenticate users.
    |
    */

    'auth' => Tymon\JWTAuth\Providers\Auth\Illuminate::class,

    /*
    |--------------------------------------------------------------------------
    | Storage Provider
    |--------------------------------------------------------------------------
    |
    | Specify the provider that is used to store tokens in the blacklist.
    |
    */

    'storage' => Tymon\JWTAuth\Providers\Storage\Illuminate::class,

],

]; ];

my web route:我的 web 路线:

Route::get('/', function () {
  return view('welcome');
});

Route::get('/{vue_capture?}', function () {
   return view('welcome');
})->where('vue_capture', '[\/\w\.-]*');

my api route:我的 api 路线:

Route::group([

'middleware' => 'api',
'prefix' => 'auth'

], function ($router) {

Route::post('login', 'AuthController@login');
Route::post('logout', 'AuthController@logout');
Route::post('signup', 'AuthController@signup');
Route::post('refresh', 'AuthController@refresh');
Route::post('me', 'AuthController@me');

});

 Route::middleware('auth')->apiResource('/fabric', 'FabricController');

Route::middleware('auth')
  ->post('/fabricLading','FabricController@fabricLading');
Route::middleware('auth')->get('/machines', 
 'FabricController@getMachines');

Thanks in advance for your guidance提前感谢您的指导

I also had this problem and did the following things.我也遇到了这个问题,做了以下事情。 My problem was solved.我的问题解决了。 First install jwt here首先在这里安装jwt

and finaly最后

composer update

I think the problem is the jwt issue settings ◑﹏◐我认为问题是jwt问题设置◑﹏◐

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Laravel 成功登录后返回 401 的产品/登台服务器上的密室 - Laravel sanctum on product/staging server returning 401 after successful login Laravel 8 登录 JWT 始终验证 401 - Laravel 8 Login JWT Auth always 401 PHP DocuSing:更新到 Laravel 9 后收到错误 non successful HTTP code [400] User not found for JWT - PHP DocuSing: after updating to Laravel 9 getting the error non successful HTTP code [400] User not found for JWT 成功登录后将用户重定向到仪表板,但如果登录期间发生错误,仍保持 laravel 默认错误消息 - Redirect user to dashboard after successful login but still maintain laravel default error messages if an error occurs during login 登录成功后认证用户为null Laravel - Authenticated user is null after successful Login Laravel Laravel 身份验证成功后社交名流登录未重定向 - Laravel socialite login after successful auth not redirecting 将 Laravel 用于 JWT 的作曲家出错 - Error with composer using Laravel for JWT Laravel4:成功登录后获取用户数据 - Laravel4: Fetching User data after successful login Laravel - 成功登录后将用户重定向到上一页 - Laravel - Redirect user to previous page after successful login Laravel 5.6:Auth :: login成功后直接失败Auth :: check() - Laravel 5.6: Auth::check() fails directly after successful Auth::login
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM