Integrate with your application#

Use this guide to fit the SCIM endpoints into your Flask application: authenticate the clients, commit the changes of each request, choose the URLs, page with cursors and limit the size of the requests. It assumes a ScimStorage and a ScimProvider, such as the ones of the Overview.

The guide covers the Flask side only. The scim2-server guides cover the rest:

The examples come from the examples directory, and reuse the create_provider function of the overview.

Authenticate the clients#

Subclass ScimServer, and add a before_request() hook to the Blueprint it creates. The hook runs before every SCIM request, and only before them. Raise UnauthorizedException to refuse a request.

Leave /ServiceProviderConfig open: per RFC 7643 §5, clients read the authentication schemes there before they authenticate. The hook recognizes it with request.endpoint: its endpoint is service_provider_config, prefixed with the name of the blueprint.

The extension serves each request with a ScimService, which applies the rules of the protocol. Override get_subject() to pass what the hook stored in g to this service, as the subject of the request:

class ProtectedScimServer(ScimServer):
    def create_blueprint(self) -> Blueprint:
        blueprint = super().create_blueprint()

        @blueprint.before_request
        def check_token() -> None:
            if request.endpoint == f"{self.name}.service_provider_config":
                return
            scheme, _, token = request.headers.get("Authorization", "").partition(" ")
            if scheme.lower() != "bearer" or token not in TOKENS:
                raise UnauthorizedException(detail="Missing or invalid token")
            g.client = TOKENS[token]

        return blueprint

    def get_subject(self) -> Any:
        return g.get("client")

Replace TOKENS with the validation of the tokens of your application, preferably with a library dedicated to authentication, such as Authlib.

Announce the scheme in the authentication_schemes of the ServiceProviderConfig:

config = ServiceProviderConfig(
    ...,
    authentication_schemes=[
        AuthenticationScheme(
            type=AuthenticationScheme.Type.oauthbearertoken,
            name="OAuth Bearer Token",
            description="Authentication with an OAuth 2.0 bearer token",
        )
    ],
)

A refused client receives a SCIM error, with a WWW-Authenticate header built from the announced schemes:

>>> from examples.authentication import create_app
>>> client = create_app().test_client()
>>> response = client.get("/scim/v2/Users")
>>> response.status_code, response.headers["WWW-Authenticate"]
(401, 'Bearer realm="SCIM"')
>>> client.get("/scim/v2/Users", headers={"Authorization": "Bearer secret"}).status_code
200
>>> client.get("/scim/v2/ServiceProviderConfig").status_code
200

By default, every authenticated client may run every operation, and /Me answers 501. To change this, subclass ScimService, and pass an instance to the service parameter of ScimServer:

  • override authorize() to limit what each client may do, such as a client that may only read;

  • override me_target() to serve /Me, with the resource of the authenticated client.

Authenticate and authorize the clients and Serve the /Me endpoint describe these methods.

Commit the changes of each request#

The extension never commits. It encloses each SCIM operation in the operation() context manager of the storage: the request itself, or each operation of a bulk request. A SQL storage opens a savepoint there, so that a failed operation of a bulk request does not undo the others.

Commit once per request, in an after_request() hook of the blueprint. Flask calls the hook for every response: the SCIM errors, and the 500 of an unexpected exception. Commit the responses below 500, so that the successful operations of a bulk request are kept, and roll back the others:

class TransactionalScimServer(ScimServer):
    def __init__(
        self, storage: ScimStorage, provider: ScimProvider, session: Any, **kwargs: Any
    ) -> None:
        self.session = session
        super().__init__(storage, provider, **kwargs)

    def create_blueprint(self) -> Blueprint:
        blueprint = super().create_blueprint()

        @blueprint.after_request
        def end_transaction(response: Response) -> Response:
            if response.status_code < 500:
                self.session.commit()
            else:
                self.session.rollback()
            return response

        return blueprint

Pass the database session of your application, such as db.session with Flask-SQLAlchemy:

TransactionalScimServer(storage, provider, session=db.session, app=app)

A commit that fails raises an exception in the hook, and the client receives a 500 rather than a success.

Choose the URLs#

The extension serves the endpoints under /scim/v2 by default. To serve them under another path, pass it as url_prefix:

>>> from flask import Flask
>>> from scim2_server.memory import InMemoryStorage
>>> from examples.minimal_server import create_provider
>>> from scim2_flask import ScimServer
>>> app = Flask(__name__)
>>> scim_server = ScimServer(InMemoryStorage(), create_provider(), app=app, url_prefix="/api/scim")
>>> app.test_client().get("/api/scim/Users").status_code
200

To serve several SCIM servers from one application, such as one per tenant, give each instance its own prefix and its own name. The name is the one of the blueprint, and the key of the instance in the "scim" entry of extensions:

>>> app = Flask(__name__)
>>> tenant_a = ScimServer(InMemoryStorage(), create_provider(), app=app, url_prefix="/a/scim/v2", name="tenant_a")
>>> tenant_b = ScimServer(InMemoryStorage(), create_provider(), app=app, url_prefix="/b/scim/v2", name="tenant_b")
>>> app.extensions["scim"]["tenant_b"] is tenant_b
True

The blueprint has one Flask endpoint per SCIM route. scim2-server lists these routes in ROUTES, and each Flask endpoint takes the name of its route, such as query for GET /{endpoint}/{resource_id}. Build their URLs with url_for(). The path of a resource type, such as Users, is the resource_endpoint argument:

>>> from flask import url_for
>>> with app.test_request_context():
...     url_for("tenant_a.query", resource_endpoint="Users", resource_id="2819c223")
'/a/scim/v2/Users/2819c223'

The extension builds the URL of each resource from the host the request reached and the url_prefix. Behind a reverse proxy, Werkzeug’s ProxyFix makes these URLs use the host and scheme the proxy received, as Tell Flask it is Behind a Proxy describes.

Page with cursors#

The server encrypts the cursors with a secret. The extension takes the SECRET_KEY of your application as this secret. Every process of your application needs the same one. init_app() reads it, so load the configuration first. When the ServiceProviderConfig announces cursor pagination and the application has no SECRET_KEY, init_app() raises a ValueError.

A ScimService passed as service keeps its own secret.

Limit the size of the requests#

The ServiceProviderConfig announces maxPayloadSize, the largest body of a bulk request. The extension reads at most one byte more of a bulk request body, and the server answers 413 beyond it. The extension reads the bodies of the other requests it serves in full.

To protect the memory of the server, set the MAX_CONTENT_LENGTH setting of Flask. Keep it above maxPayloadSize: a bulk request within maxPayloadSize but beyond MAX_CONTENT_LENGTH gets a 413 too. Any request with a larger body gets a 413, as a SCIM error:

>>> app = Flask(__name__)
>>> app.config["MAX_CONTENT_LENGTH"] = 2 * 1_048_576
>>> scim_server = ScimServer(InMemoryStorage(), create_provider(), app=app)
>>> response = app.test_client().post(
...     "/scim/v2/Users",
...     data=b"x" * (3 * 1_048_576),
...     headers={"Content-Type": "application/scim+json"},
... )
>>> response.status_code, response.headers["Content-Type"]
(413, 'application/scim+json')