Skip to main content

Keycloak based authentication policy for Pyramid framework

Authentication policy which uses Keycloak's OpenID API via a client to authenticate the user. It uses cookies to hold the access token and the refresh token.

This package is dependant on the package python-keycloak.

Usage

from keycloak import KeycloakOpenID
from pyramid.config import Configurator
from keycloak_auth_policy import KeycloakBasedAuthenticationPolicy

def main():
    openid_client = KeycloakOpenID(...)
    config = Configurator()
    config.set_authentication_policy(
        KeycloakBasedAuthenticationPolicy(openid_client))

You have to handle the redirect logic in your forbidden view based on your needs:

from pyramid.httpexceptions import HTTPFound, HTTPForbidden
from pyramid.request import Request
from pyramid.view import forbidden_view_config

@forbidden_view_config()
def forbidden_view(request: Request):
    if ...: # user has no privileges
        raise HTTPForbidden("You don't have permissions for this action")

    # Keycloak's URL to redirect to where the user can log in
    url = ...

    # you can either redirect to the URL or return it if you have a client 
    # which consumes your API
    return HTTPFound(url)

You also need to have a callback endpoint where Keycloak redirects to after a successful login

from keycloak.exceptions import KeycloakError
from pyramid.httpexceptions import HTTPFound
from pyramid.request import Request
from pyramid.view import view_defaults, view_config


@view_defaults(renderer='json')
class AuthApi:

    def __init__(self, request: Request) -> None:
        self.request = request
        self._openid_client = ... # get OpenID client

    @view_config(route_name='auth.exchange', request_method='GET',
                 permission='public')
    def exchange(self):
        try:
            token_response = self._openid_client.exchange(
                self.request.GET.get("code"),
                self.request.route_url("auth.exchange")) # the redirect URI
        except KeycloakError as e:
            ... # handle exception

        access_token = token_response.get("access_token")
        refresh_token = token_response.get("refresh_token")

        # set the tokens as cookies to the client and return a response
        # you can either redirect from here or if your application is consumed
        # as an API you can return a successful response
        response = HTTPFound(...)
        response.set_cookie("refresh_token_cookie_name", refresh_token)
        response.set_cookie("access_token_cookie_name", access_token)

        return response

You can also implement a logout endpoint if you feel like to

from pyramid.security import forget

    ...

    @view_config(route_name='auth.logout', request_method='GET',
                 permission='private')
    def logout(self):
        headers = forget(self.request)
        response = self.request.response
        response.headerlist.extend(headers)
        return response

For more information see the docstrings of each method in the source.

Metadata

Release files for pyramid-keycloak 0.0.13

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for pyramid-keycloak 0.0.13
File Size Uploaded Provenance Actions
pyramid_keycloak-0.0.13.tar.gz 3.9 kB Without provenance Details for pyramid_keycloak-0.0.13.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for pyramid-keycloak 0.0.13
File Interpreter ABI Platform Actions
pyramid_keycloak-0.0.13-py3-none-any.whl Python 3 none any Details for pyramid_keycloak-0.0.13-py3-none-any.whl

Total release size: 9.0 kB

Release files / pyramid_keycloak-0.0.13.tar.gz

Download URL pyramid_keycloak-0.0.13.tar.gz
Size 3.9 kB
Tags Source
SHA-256 checksum
How to use checksums
8ffabe6541edd1d7b7eed0f82925ef922997afaebf95137f81b30183f11dada7
BLAKE2b-256 checksum
How to use checksums
77db3535e98d8ca11a69fad24baeabdf8a5cd9d331481c49d602172dcc6453f0
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/1.11.0 pkginfo/1.4.2 requests/2.19.1 setuptools/40.4.3 requests-toolbelt/0.8.0 tqdm/4.23.4 CPython/3.6.4

Release files / pyramid_keycloak-0.0.13-py3-none-any.whl

Download URL pyramid_keycloak-0.0.13-py3-none-any.whl
Size 5.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
b5ddb84b61c749f3c36f053545a16a39ebca42ec2bcec9a60274215deae12f79
BLAKE2b-256 checksum
How to use checksums
a8f1858c9d6950cdad32ba7dc164e6ea5eb3212b17ac6736538117fc452648a0
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/1.11.0 pkginfo/1.4.2 requests/2.19.1 setuptools/40.4.3 requests-toolbelt/0.8.0 tqdm/4.23.4 CPython/3.6.4

Security for pyramid-keycloak 0.0.13

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.0.13 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page