Gramex 1.77 supports API keys, secure MongoDB access, session cookies, and more.
API keys let users access services as if they were logged-in users. These are like one-time passwords, but can be used multiple times, until expiry.
These are useful to provide allow services (e.g. bots, apps, scripts) to act on behalf of a user. For example, to fetch data, trigger a refresh, etc.
Add this code to a FunctionHandler or any Python code in a handler:
expiry = 24 * 60 * 60 # Expires in 24 hours
key = handler.apikey(expire=expiry) # Create API key as current user
This creates an API key
string for the currently logged-in user that expires after 24 hours.
To create an API key
for a different user, use:
expiry = 24 * 60 * 60 # Expires in 24 hours
user = {'id': 'alpha'} # User to create API key for
key = handler.apikey(expire=expiry, user=user) # Create key as specified user
When a user visits any page with ?gramex-key=<key>
added, or with a X-Gramex-Key: <key>
header,
the user is logged in for that session. handler.current_user
is set to the user object.
API key example
It’s now possible to connect securely to a MongoDB instance using TLS/SSL.
An example of a secure MongoDB access configuration is:
url:
mongodb:
pattern: /mongodb/
handler: FormHandler
kwargs:
url: "mongodb://$USER:$PASS@mongodb.example.com:27017"
database: db_name
collection: collection_name
tls: true
tlsCAFile: /path/to/ca.pem # OPTIONAL path to CA certificate
tlsCertificateKeyFile: /path/to/client.pem # OPTIONAL path to Client certificate
Here are tips on troubleshooting errors
Gramex allows setting session cookies (that expire when the browser is closed, normally). To enable these, use:
app:
session:
expiry: false # Sessions expire when browser closes
You can specify it just for a single login handler rather than the entire app:
url:
auth/expiry:
pattern: /$YAMLURL/expiry
handler: SimpleAuth # session_expiry works on DBAuth, GoogleAuth, etc too
kwargs:
session_expiry: false # Sessions expire when browser closes
# ...
Gramex also supports the
samesite
cookie attribute. Strict
sends cookies only for requests from the same site. Lax
(the default) sends cookies across sites.
An example of a secure cookie configuration is:
app:
session:
httponly: true # Allow JavaScript access via document.cookie
secure: true # Cookies can be accessed only via HTTPS (not HTTP)
samesite:
Strict # Browser sends the cookie only for same-site requests.
# Values can be Strict, Lax or None. (Case-sensitive)
domain: example.org # All subdomains in *.example.org can access session
delay: <number>
Gramex 1.77 is backward compatible with previous releases unless the release notes say otherwise. Automated builds test this.
Every Gramex release is tested for security vulnerabilities using the following tools.
The Gramex code base has: