Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

SOLVED: Protect routes with oauth2

altralaser:

I want to protect my REST API by using an oauth2 authentication. I'm using bshaffer/oauth2-server-php in combination with zend 3.
I've the following config:


// autoload/oauth2.global.php
return [
'zf-oauth2' => [
'db' => [
'dsn' => sprintf(
'mysql:dbname=%s;host=%s',
false !== getenv('DB_NAME') ? getenv('DB_NAME') : '',
false !== getenv('DB_HOST') ? getenv('DB_HOST') : ''
),
'username' => false !== getenv('DB_USER') ? getenv('DB_USER') : '',
'password' => false !== getenv('DB_PASS') ? getenv('DB_PASS') : '',
],
'storage' => MyApp\OAuth2Module\Adapter\PdoAdapter::class,
'enforce_state' => true,
'allow_implicit' => true,
'access_lifetime' => 3600,
'api_problem_error_response' => false,
'options' => [
'use_jwt_access_tokens' => false,
'store_encrypted_token_string' => true,
'use_openid_connect' => false,
'id_lifetime' => 3600,
'www_realm' => 'Service',
'token_param_name' => 'access_token',
'token_bearer_header_name' => 'Bearer',
'require_exact_redirect_uri' => true,
'allow_public_clients' => true,
'allow_credentials_in_request_body' => true,
'always_issue_new_refresh_token' => false,
'refresh_token_lifetime' => 1209600,
],
],
];

And my auth route looks like this:


// autoload/router.global.php
return [
'router' => [
'routes' => [
'api' => [
'type' => Literal::class,
'options' => [
'route' => '/api',
],
'may_terminate' => false,
'child_routes' => [
'rest' => [
'type' => Literal::class,
'options' => [
'route' => '/rest',
],
'may_terminate' => false,
'child_routes' => [
'oauth' => [
'type' => Literal::class,
'options' => [
'route' => '/oauth',
'defaults' => [
'controller' => 'ZF\OAuth2\Controller\Auth',
'action' => 'token',
],
],
],
],
],
],
],
],
],
];

Everything works fine so far. I can post my client credentials to the oauth endpoint and get an access token.
But how can I protect the other endpoints? F.e. I make a GET request to /api/rest/myapp/GetList. The list of my entities should only be retrieved if the user also sends the authorization bearer with the request but I can't find a solution for this. Is it possible to set a parameter (something like "require_token") in the route config to "activate" this behavior? Or what is the correct way to protect my REST API?



Posted in S.E.F
via StackOverflow & StackExchange Atomic Web Robots
This Question have been answered
HERE


This post first appeared on Stack Solved, please read the originial post: here

Share the post

SOLVED: Protect routes with oauth2

×

Subscribe to Stack Solved

Get updates delivered right to your inbox!

Thank you for your subscription

×