jwt-auth icon indicating copy to clipboard operation
jwt-auth copied to clipboard

I visit /api/auth/logout why it tip me :Unauthenticated.

Open zhangwei900808 opened this issue 6 years ago • 11 comments

AuthController.php

<?php

namespace Awbeci\Http\Controllers;
use Illuminate\Support\Facades\Auth;
use Awbeci\Http\Models\User;
use Awbeci\Http\Controllers\Controller;

use Illuminate\Http\Request;


class AuthController extends Controller
{
    /**
     * Create a new AuthController instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth:api', ['except' => ['login']]);
    }

    /**
     * Get a JWT token via given credentials.
     *
     * @param  \Illuminate\Http\Request  $request
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function login(Request $request)
    {
        $this->validate($request, [
            'email' => 'required|string|email|max:255',
            'password' => 'required|string|min:6'
        ]);
        $email = $request->input('email');
        $password = $request->input('password');

        //验证用户
        if (Auth::attempt([
            'email' => $email,
            'password' => $password
        ], true)
        ) {
            //验证用户通过下面生成jwt token并返回
            $credentials = $request->only('email', 'password');
            if ($token = $this->guard()->attempt($credentials)) {
                return response()->json([
                    'success' => true,
                    'msg' => 'Successfully login!',
                    'access_token' => $token,
                    'user' => Auth::user()
                ], 201);
            }
        }
        $email_count = User::where('email', '=', $email)->count();
        return response()->json([
            'success' => false,
            'msg' => '邮箱或者密码有误,请重新输入!',
            'emailCount' => $email_count
        ]);
    }

    /**
     * Get the authenticated User
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function me()
    {
        return response()->json($this->guard()->user());
    }

    /**
     * Log the user out (Invalidate the token)
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function logout()
    {
        $this->guard()->logout();

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

    /**
     * Refresh a token.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function refresh()
    {
        return $this->respondWithToken($this->guard()->refresh());
    }

    /**
     * Get the token array structure.
     *
     * @param  string $token
     *
     * @return \Illuminate\Http\JsonResponse
     */
    protected function respondWithToken($token)
    {
        return response()->json([
            'access_token' => $token,
            'token_type' => 'bearer',
            'expires_in' => $this->guard()->factory()->getTTL() * 60
        ]);
    }

    /**
     * Get the guard to be used during authentication.
     *
     * @return \Illuminate\Contracts\Auth\Guard
     */
    public function guard()
    {
        return Auth::guard();
    }
}

api.php

Route::group([
    'middleware' => 'api',
    'prefix' => 'auth'
], function ($router) {
    Route::post('login', 'AuthController@login');
    Route::post('logout', 'AuthController@logout');
});

image

zhangwei900808 avatar Oct 15 '17 13:10 zhangwei900808

Info?

jampack avatar Oct 15 '17 14:10 jampack

what?

zhangwei900808 avatar Oct 16 '17 01:10 zhangwei900808

@zhangwei900808 framework version package version etc..

jampack avatar Oct 16 '17 07:10 jampack

{
    "name": "laravel/laravel",
    "description": "The Laravel Framework.",
    "keywords": ["framework", "laravel"],
    "license": "MIT",
    "type": "project",
    "require": {
        "php": ">=7.0.0",
        "awbeci/aliyun-dm": "^1.0",
        "caouecs/laravel-lang": "~3.0",
        "fideloper/proxy": "~3.3",
        "laravel/framework": "5.5.*",
        "laravel/tinker": "~1.0",
        "tymon/jwt-auth": "1.0.0-rc.1"
    },
    "require-dev": {
        "filp/whoops": "~2.0",
        "fzaninotto/faker": "~1.4",
        "mockery/mockery": "0.9.*",
        "phpunit/phpunit": "~6.0"
    },
    "autoload": {
        "classmap": [
            "database/seeds",
            "database/factories"
        ],
        "psr-4": {
            "Awbeci\\": "app/"
        }
    },
    "autoload-dev": {
        "psr-4": {
            "Tests\\": "tests/"
        }
    },
    "extra": {
        "laravel": {
            "dont-discover": [
            ]
        }
    },
    "scripts": {
        "post-root-package-install": [
            "@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
        ],
        "post-create-project-cmd": [
            "@php artisan key:generate"
        ],
        "post-autoload-dump": [
            "Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
            "@php artisan package:discover"
        ]
    },
    "config": {
        "preferred-install": "dist",
        "sort-packages": true,
        "optimize-autoloader": true
    }
}

zhangwei900808 avatar Oct 17 '17 01:10 zhangwei900808

Did you solve it? Had same issue

durancu avatar Feb 27 '18 16:02 durancu

You have to pass your current token in, to the logout the user

eg.)

curl -X POST http://localhost/logout --header "Content-Type: application/json" --header "Authorization: Bearer <your-token>"

lmj0011 avatar Mar 30 '18 23:03 lmj0011

How about in testing environment, how do you get current user token?

you can login with $this->actingAs($user) from a test, but how to get the token?

dbrw avatar Sep 17 '18 07:09 dbrw

very late answer but this could help someone:

Route::post('logout', 'AuthController@logout');

since the route is "post" you must send the token, and another string, for example with axios

Axios.post("/api/me", "POSTDATA",{headers:{"AUTHORIZATION":Bearer ${sessionStorage.jwt}}})

check that there is an array after the route, if you dont use it, the server will asume that the payload is the token and the tokes isn't in the request, or changing it to a GET request may work?... test :)

chincodev avatar Jul 01 '19 19:07 chincodev

@iAnthonyCoder :

Axios.post("/api/me", "POSTDATA",{headers:{"AUTHORIZATION":Bearer ${sessionStorage.jwt}}})

POSTDATA did it for me

DerkJanSpeelman avatar Oct 05 '20 15:10 DerkJanSpeelman

Is this still relevant? If so, what is blocking it? Is there anything you can do to help move it forward?

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs.

stale[bot] avatar Dec 25 '20 15:12 stale[bot]

very late answer but this could help someone:

Route::post('logout', 'AuthController@logout');

since the route is "post" you must send the token, and another string, for example with axios

Axios.post("/api/me", "POSTDATA",{headers:{"AUTHORIZATION":Bearer ${sessionStorage.jwt}}})

check that there is an array after the route, if you dont use it, the server will asume that the payload is the token and the tokes isn't in the request, or changing it to a GET request may work?... test :)

this is what worked for me, thanks.

stima-sacco avatar Jan 12 '22 06:01 stima-sacco