Skip to content

[Feature Request] Ability to refresh auth token #834

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
asarkar opened this issue Oct 18, 2022 · 1 comment · Fixed by #890
Closed

[Feature Request] Ability to refresh auth token #834

asarkar opened this issue Oct 18, 2022 · 1 comment · Fixed by #890

Comments

@asarkar
Copy link

asarkar commented Oct 18, 2022

To help us understand your issue, please specify important details, primarily:

  • Neo4j version: AWS Neptune
  • Neo4j Mode: N/A
  • Driver version: All
  • Operating system: Linux

We're using openCypher with AWS Neptune and want to use the neo4j driver with the bolt protocol. We are generating an AWS V4 signature and passing it in as a basic auth to the driver. The request is signed using temporary credentials that expires in 5 minutes.

Unfortunately, it seems that the authentication token is cached at connection creation time.

# Determine auth details
if not auth:
    self.auth_dict = {}
elif isinstance(auth, tuple) and 2 <= len(auth) <= 3:
    from neo4j import Auth
    self.auth_dict = vars(Auth("basic", *auth))
else:
    try:
        self.auth_dict = vars(auth)
    except (KeyError, TypeError):
        raise AuthError("Cannot determine auth details from %r" % auth)

Thus, if the max_connection_lifetime is set to less than 5 minutes, requests start failing after 5 minutes because the signature is no longer valid.

self = <neo4j.io._common.InitResponse object at 0x7f41eb9dc750>
metadata = {'code': '"BoltProtocol.unexpectedException"', 'message': '"Unexpected server exception \'Signature expired: 20221018T003343Z is now earlier than 20221018T003344Z (20221018T003844Z - 5 min.)\'"'}

    def on_failure(self, metadata):
        code = metadata.get("code")
        if code == "Neo.ClientError.Security.Unauthorized":
            raise Neo4jError.hydrate(**metadata)
        else:
            raise ServiceUnavailable(
>               metadata.get("message", "Connection initialisation failed")
            )
E           neo4j.exceptions.ServiceUnavailable: "Unexpected server exception 'Signature expired: 20221018T003343Z is now earlier than 20221018T003344Z (20221018T003844Z - 5 min.)'"

The Javascript driver also has the same issue.

But the Java driver provides a way to avoid this problem by exposing a toMap method, that is called to obtain the token. While the cached token is returned by default, this method can be overridden in a subclass as shown here.

We would like the Python driver to also provide an option not to cache the auth token and regenerate it on demand.

@germangamboa95
Copy link

@asarkar we also ran into this issue, and we fixed it by forking and adding support for it in the javascript on neo4j/neo4j-javascript-driver#993

with that said. Neptune is a piece of shit, and I recommend using an excel spreadsheet before trying to go down that path.

robsdedude added a commit that referenced this issue Apr 12, 2023
# ADR 012: re-authentication

This PR introduces two new auth mechanics for different use-cases
1) Auth Rotation
2) Session Auth (a.k.a. user switching)

**Note that all APIs introduced in this PR are previews**
See https://github.com/neo4j/neo4j-python-driver/wiki/preview-features


## 1) Auth Rotation
This is used for auth tokens that is expected to expire (e.g., SSO).

A `neo4j.auth_management.AuthManager` instance 
(or `neo4j.auth_management.AsyncAuthManager` for async driver) may be passed
to the driver instead of a static auth token.

```python
import neo4j
from neo4j.auth_management import AuthManager


class MyManager(AuthManager):
    ...  # see API dos for details


with neo4j.GraphDatabase.driver(
    "neo4j://example.com:7687", 
    auth=MyManager(),
) as driver:
    ...
```

The easiest way to get started is using the provided `AuthManager`
implementation. For example:

```python
import neo4j
from neo4j.auth_management import (
    AuthManagers,
    ExpiringAuth,
)


def auth_provider():
    # some way to getting a token
    sso_token = get_sso_token()
    # assume we know our tokens expire every 60 seconds
    expires_in = 60
    return ExpiringAuth(
        auth=neo4j.bearer_auth(sso_token),
        # Include a little buffer so that we fetch a new token
        # *before* the old one expires
        expires_in=expires_in - 10
    )


with neo4j.GraphDatabase.driver(
    "neo4j://example.com:7687",
    auth=AuthManagers.temporal(auth_provider)
) as driver:
    ... 
```

**Note**  
This API is explicitly *not* designed for switching users.
In fact, the token returned by each manager must always belong to the same
identity. Switching identities using the `AuthManager` is undefined behavior.


## 2) Session Auth
For the purpose of switching users, `Session`s can be configured with a static
auth token. This is very similar to impersonation in that all work in the
session will be executed in the security context of the user associated with
the auth token. The major difference is that impersonation does not require or
verify authentication information of the target user, however it requires
the impersonating user to have the permission to impersonate.

**Note**
This requires Bolt protocol version 5.3 or higher (Neo4j DBMS 5.8+).

```python
import neo4j


with neo4j.GraphDatabase.driver(
    "neo4j://example.com:7687",
    auth=("user1", "password1"),
) as driver:
    with driver.session(database="neo4j") as session:
        ...  # do some work as user1
    with driver.session(database="neo4j",
                        auth=("user2", "password2")) as session:
        ...  # do some work as user2
```


## References
Depends on:
 * neo4j-drivers/testkit#539

Related PRs:
 * #891

Issues:
 * closes #834
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants