You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: conceptual/Npgsql/security.md
+13-5Lines changed: 13 additions & 5 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -8,20 +8,28 @@ If a `Password` is not specified and your PostgreSQL is configured to request a
8
8
9
9
### Auth token rotation and dynamic password
10
10
11
-
In some cloud scenarios, logging into PostgreSQL is done with an auth token that is rotated every time interval (e.g. one hour). Starting with version 7.0, Npgsql has a built-in periodic password provider mechanism, which allows refreshing the password with zero effort:
11
+
In some cloud scenarios, logging into PostgreSQL is done with an auth token that is rotated every time interval (e.g. one hour). Npgsql has a built-in periodic password provider mechanism, which allows using an up-to-date access token with zero effort:
Every time a new physical connection needs to be opened to PostgreSQL, either the synchronous `passwordProvider` or the asynchronous `passwordProviderAsync` will be called (depending whether you used `Open()` or `OpenAsync()`). Since modern .NET applications are encouraged to always use synchronous I/O, it's good practice to simply throw in the synchronous password provider, as above.
22
+
23
+
Note that since the password provider is invoked *every* time a physical connection is opened, it shouldn't take too long; typically, this would call into a cloud provider API (e.g. Azure Managed Identity), which itself implements a caching mechanism. However, if no such caching is done and the code could take a while, you can instead instruct Npgsql to cache the auth token for a given amount of time:
24
+
25
+
```csharp
15
26
dataSourceBuilder.UsePeriodicPasswordProvider(
16
27
(settings, cancellationToken) =>/* async code to fetch the new access token */,
17
28
TimeSpan.FromMinutes(55), // Interval for refreshing the token
18
29
TimeSpan.FromSeconds(5)); // Interval for retrying after a refresh failure
This API allows you to provide a minimal async code fragment for fetching the latest auth token, and have Npgsql take care of running it for you as needed.
23
-
24
-
If, instead, you prefer to manage this yourself, you can simply inject a new password at any time into a working data source:
32
+
Finally, if you already have code running when the auth token changes, you can simply inject it manually at any time into a working data source:
0 commit comments