This tutorial shows how to create a custom authorization check by tokens with scopes for HTTP handlers. Required scopes are specified in static configuration file for each HTTP handler. In the tutorial the authorization data is cached in components::PostgreCache, and information of an authorized user (it's name) is passed to the HTTP handler.
Creation of tokens and user registration is out of scope of this tutorial.
Warning
Authorization scheme from this sample is vulnerable to the MITM-attack unless you are using a secure connection (HTTPS).
PostgreSQL Cache
Let's make a table to store users data:
V001__create_db.sql
V002__add_name.sql
DROP SCHEMA IFEXISTS auth_schema CASCADE;
CREATE SCHEMA IFNOTEXISTS auth_schema;
CREATETABLEIFNOTEXISTS auth_schema.tokens (
token TEXT PRIMARY KEY NOTNULL,
user_id INTEGERNOTNULL,
scopes TEXT[] NOTNULL,
updated TIMESTAMPTZ NOTNULLDEFAULT NOW()
);
ALTERTABLE auth_schema.tokens
ADDCOLUMN name TEXT NOTNULL;
Authorization data is rarely changed and often queried. Caching it would improve response times:
CheckAuth functions are invoked concurrently on the same instance of the class. In this sample the AuthCheckerBearer class only reads the class data. synchronization primitives should be used if data is mutated.
That factory is invoked on each HTTP handler with the matching authorization type:
handler-hello:path:/v1/hellotask_processor:main-task-processormethod:GETauth:# Authorization config for this handlertypes:-bearer# Authorization type that was specified in main()scopes:# Required user scopes for that handler-read-hello
To build the sample, execute the following build steps at the userver root directory:
mkdir build_release
cd build_release
cmake -DCMAKE_BUILD_TYPE=Release ..
make userver-samples-postgres_auth
The sample could be started by running make start-userver-samples-postgres_auth. The command would invoke testsuite start target that sets proper paths in the configuration files, prepares and starts the DB, and starts the service.
To start the service manually start the DB server and run ./samples/postgres_service/userver-samples-postgres_auth -c </path/to/static_config.yaml> (do not forget to prepare the configuration files!).
Now you can send a request to your service from another terminal: