nw.lee
nw.lee

Reputation: 71

Can i store plainTextToken generated by Laravel Sanctum to local storage?

I have been building a blog project with React, Laravel, Laravel Sanctum, which provides authentication.

I have learned that clients, such as web browsers, must request to api/sanctum/csrf-cookie since I have to retrieve csrf token. Next, by requesting to api/login with appropriate login data(email, password), I can get plainTextToken, which is generated by Laravel Sanctum.

Now I am finding out that how can i use plainTextToken when i want to login. To put Bearer Token in request headers, I need to store plainTextToken somewhere.

Can i store plainTextToken in LocalStorage, or SessionStorage?

Because.. I think that whenever I access pages authentication required, React Components should maintain and provide token data.

I will attach AuthController of Laravel having been written.

class AuthController extends Controller
{
    public function register(Request $request)
    {
        $val = $request->validate([
            'name' => 'required|string|max:255',
            "email" => "required|email|string|max:255|unique:users",
            "password" => "required|confirmed|string|min:12"
        ]);
        $user = User::create([
            "name" => $val['name'],
            'email' => $val['email'],
            'password' => Hash::make($val['password']),
        ]);
        return response()->json([
            'user' => $user
        ], 201);
    }

    public function login(Request $request)
    {
        if(!Auth::attempt($request->only('email', 'password'))) {
            return response()->json([
                'message' => "Invalid Login Details"
            ], 401);
        }
        $user = User::where('email', $request['email'])->firstOrFail();
        $token = $user->createToken("auth_token")->plainTextToken;
        return response()->json([
            'access_token' => $token,
            "token_type" => "Bearer",
        ]);
    }

    public function account(Request $request)
    {
        return $request->user();
    }

    public function logout(Request $request)
    {
        $request->user()->currentAccessToken()->delete();
        return response()->json([
            "msg" => "See You Later"
        ]);
    }

    public function delete(Request $request)
    {
        $request->user()->softDelete();
        return response()->json([
            "msg" => "You never register this email again"
        ]);
    }
}

Upvotes: 3

Views: 957

Answers (1)

divad
divad

Reputation: 137

With Laravel Sanctum, it's not required to store the 'plaintexttoken' at the server-side either via a Session, locally or in a database. You only need to send in the 'plaintexttoken' (from the client) in the Authorization header as a Bearer token, and at the server-side, Sanctum carries out the authorization actions (which is mysterious to me right now).

Upvotes: 1

Related Questions