Authorization middleware for GraphQL.
Project description
graphql-authz
GraphQL-Authz is a Python3.6+ port of GraphQL-Authz, the Casbin authorization middleware implementation in Node.js.
This package should be used with GraphQL-core 3, providing the capability to limit access to each GraphQL resource with the authorization middleware.
Installation
Install the package using pip.
pip install graphql-authz
Get Started
Limit the access to each GraphQL resource with a policy. For example, given this policy for an RBAC model:
p, authorized_user, hello, query
Authorization can be enforced using:
import casbin
from authz.middleware import enforcer_middleware
from graphql import (
graphql_sync,
GraphQLSchema,
GraphQLObjectType,
GraphQLField,
GraphQLString,
)
schema = GraphQLSchema(
query=GraphQLObjectType(
name="RootQueryType",
fields={
"hello": GraphQLField(
GraphQLString,
resolve=lambda obj, info: "world")
}))
enforcer = casbin.Enforcer("model_file.conf", "policy_file.csv")
authorization_middleware = enforcer_middleware(enforcer)
query = """{ hello }"""
# Authorized user ("authorized_user") has access to data
response = graphql_sync(
schema,
query,
middleware=[authorization_middleware],
context_value={"role": "authorized_user"}
)
assert response.data == {"hello": "world"}
# Unauthorized users ("unauthorized_user") are rejected
response = graphql_sync(
schema,
query,
middleware=[authorization_middleware],
context_value={"role": "unauthorized_user"}
)
assert response.errors[0].message == "unauthorized_user can not query hello"
For more interesting scenarios see tests
folder.
Credits
Implementation was heavily inspired by the Node.js middleware GraphQL-Authz.
Authorization enforcement is based on Casbin authorization library.
This package was created with Cookiecutter and the audreyr/cookiecutter-pypackage
project template.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Hashes for graphql_authz-0.1.2-py2.py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | cc448a68a9d803a2a9323da566df1a40ac650ec3c8131f01c340d6535567bb13 |
|
MD5 | a36dfacaea56f57cc2ae4a255616b1e4 |
|
BLAKE2b-256 | 965452c696867e744f7ad8bdc8c0535c3267738da097bca61dffd2573e044186 |