def get_xsrf_token(handler, cookie_path=""):
    """Override tornado's xsrf token to add further restrictions

    - only set cookie for regular pages (not API requests)
    - include login info in xsrf token
    - verify signature
    """
    # original: https://github.com/tornadoweb/tornado/blob/v6.4.0/tornado/web.py#L1455
    if hasattr(handler, "_xsrf_token"):
        return handler._xsrf_token

    _set_cookie = False
    # the raw cookie is the token
    xsrf_token, xsrf_id_cookie = _get_xsrf_token_cookie(handler)
    cookie_token = xsrf_token

    # check the decoded, signed value for validity
    xsrf_id = handler._xsrf_token_id
    if xsrf_id_cookie != xsrf_id:
        # this will usually happen on the first page request after login,
        # which changes the inputs to the token id
        if xsrf_id_cookie:
            app_log.debug("xsrf id mismatch %r != %r", xsrf_id_cookie, xsrf_id)
        # generate new value
        xsrf_token = _create_signed_value_urlsafe(handler, "_xsrf", xsrf_id)
        # only set cookie on regular navigation pages
        # i.e. not API requests, etc.
        # insecure URLs (public hostname/ip, no https)
        # don't set Sec-Fetch-Mode.
        # consequence of assuming 'navigate': setting a cookie unnecessarily
        # consequence of assuming not 'navigate': xsrf never set, nothing works
        _set_cookie = (
            handler.request.headers.get("Sec-Fetch-Mode", "navigate") == "navigate"
        )
        if xsrf_id_cookie and not _set_cookie:
            # if we aren't setting a cookie here but we got one,
            # this means things probably aren't going to work
            app_log.warning(
                "Not accepting incorrect xsrf token id in cookie on %s",
                handler.request.path,
            )

    if _set_cookie:
        _set_xsrf_cookie(handler, xsrf_id, cookie_path=cookie_path)
    handler._xsrf_token = xsrf_token
    return xsrf_token
Override tornado's xsrf token to add further restrictions

- only set cookie for regular pages (not API requests)
- include login info in xsrf token
- verify signature
jupyterhub/_xsrf_utils.py