Search code examples
laravellaravel-sanctum

laravel sanctum, identify user from cookie


I'm new to larravel, and use laravel sanctum build an app, the session driver is cookie.

The laravel app is deployed behind caddy, I enabled caddy logs. The log format is json, I see that it contains each request headers, and cookie info is loged, so I wonder if I can identify user by the cookies, I try decode the cookie but failed, is there any method to identify user by the cookie?

this is log format

{
    "level": "info",
    "ts": 1648864255.073147,
    "logger": "http.log.access.log5",
    "msg": "handled request",
    "request": {
        ...
        "headers": {
            "Accept": [
                "application/json, text/plain, */*"
            ],
            "X-Xsrf-Token": [
                ".....yJpdiI6Ijh6bjVZMXUvOFlkR3V1U....."
            ],

            "Cookie": [
                "XSRF-TOKEN=...eyJpdiI6Ijh6bjVZMXUvOFlkR3V1UE....9"
            ]
        }
    },
    "resp_headers": {
        "Set-Cookie": [
            "XSRF-TOKEN=hbHVlIjoiOHN6L1BXa2N; expires=Sat, 02-Apr-2022 03:50:55 GMT; Max-Age=7200; ...",
            "card_session=2IzTC9BbTEydW5NUDEvd016aVhlOWp; expires=Sat, 02-Apr-2022 03:50:55 GMT; Max-Age=7200; ...",
            "hkx3q7J7TeLVf3hV9XSaDiwScSS7rUIPP7kcge7f=eyJpdiI6RzlOeEN5eUhxUVE4OUZpMkFmSmYSIsInRhZyI6IiJ9; expires=Sat, 02-Apr-2022 03:50:55 GMT; Max-Age=7200; ..."
        ],
        ..
    }
}
``

Solution

  • I really wonder why you need to know the user from cookie.

    But because you are new to laravel, I think you get it all wrong with using laravel sanctum as authenticator.

    When using laravel sanctum, it will generate token to use as bearer token for your next API request. So here what you should do

    1. login and get the user data and token
    2. store the token in the front end and use it as bearer token for your next request.
    3. logout and destroy the token.

    The user data can be get easily in any place in the laravel backend using

    Auth::user()
    

    or maybe if you only need the user id then use

    Auth:id()
    

    don't forget to restrict your end point with authentication middleware if you don't want unauthenticated user to use your end point