Bshaffer oauth2 server php

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

OAuth2 for your Symfony Application

License

bshaffer/oauth2-server-bundle

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

OAuth2 Server Bundle for Symfony 2, built on the oauth2-server-php library.

Build Status

See the Complete Documentation for information regarding the OAuth2.0 protocol and the PHP library used by this bundle to implement it.

For documentation specific to this bundle, continue reading below.

The following grant types are supported out the box:

  • Client Credentials
  • Authorization Code
  • Refresh Token
  • User Credentials (see below)

You can make token requests to the /token path via POST.

You can restrict the grant types available per client in the database, use a Compiler Pass or in your own TokenController you could do something like:

public function tokenAction() < $server = $this->get('oauth2.server'); // Override default grant types to authorization code only $server->addGrantType($this->get('oauth2.grant_type.authorization_code')); return $server->handleTokenRequest($this->get('oauth2.request'), $this->get('oauth2.response')); >

Step 1: Add package to Composer

Use composer to add the requirement and download it by running the command:

$ php composer.phar require bshaffer/oauth2-server-bundle

Composer will update your composer.json and install the bundle to your project’s vendor/bshaffer directory.

Enable the bundle in the kernel:

 // app/AppKernel.php public function registerBundles() < $bundles = array( // . new OAuth2\ServerBundle\OAuth2ServerBundle(), ); >

You’ll need to update your schema to setup the Entities provided by this module.

$ php app/console doctrine:schema:update --force

You’ll need to add the following to your routing.yml

# app/config/routing.yml oauth2_server: resource: "@OAuth2ServerBundle/Controller/" type: annotation prefix: /

You’ll need to setup a scope before you can create a client, use this command. The description you give here will appear on the Authorization page.

$ php app/console OAuth2:CreateScope scope (description)

Use this console command to create a new client:

$ php app/console OAuth2:CreateClient client_id redirect_uri (grant_types) (scope)

You can override any of the built-in components in your own bundle by adding new parameters in your config.yml:

# app/config/config.yml parameters: oauth2.storage.client_credentials.class: Amce\OAuth2ServerBundle\Storage\ClientCredentials

Where Amce\OAuth2ServerBundle\Storage\ClientCredentials is your own implementation of the ClientCredentials interface.

If you provide your own storage managers then you’ll be able to hook everything up to your own custom Entities.

User Credentials (Resource Owner Password)

To make it easy to plug-in your own User Provider we’ve conformed to the UserInterface , UserProviderInterface & EncoderFactoryInterface .

Therefore to make proper use of the user credentials grant type you’ll need to modify your config.yml with the relevant classes.

# app/config/config.yml parameters: oauth2.user_provider.class: Amce\OAuth2ServerBundle\User\OAuth2UserProvider

If you want to take advantage of scope restriction on a per user basis your User entity will need to implement the OAuth2\ServerBundle\OAuth2UserInterface or OAuth2\ServerBundle\AdvancedOAuth2UserInterface .

Out of the box we do provide a basic user provider and entity for you to use. Setup your security.yml to use it:

# app/config/security.yml security: encoders: OAuth2\ServerBundle\Entity\User: algorithm: sha512 encode_as_base64: true iterations: 5000 providers: oauth2: id: oauth2.user_provider

You’ll need some users first though! Use the console command to create a new user:

$ php app/console OAuth2:CreateUser username password

You’ll need to use a Compiler Pass to configure settings for a grant type. For example say we want our refresh tokens to always get renewed:

// Amce/OAuth2ServerBundle/AmceOAuth2ServerBundle.php namespace Amce\OAuth2ServerBundle; use Symfony\Component\HttpKernel\Bundle\Bundle; use Symfony\Component\DependencyInjection\ContainerBuilder; use Amce\OAuth2ServerBundle\DependencyInjection\Compiler\OAuth2CompilerPass; class AmceOAuth2ServerBundle extends Bundle < public function build(ContainerBuilder $container) < parent::build($container); $container->addCompilerPass(new OAuth2CompilerPass()); > >
// Amce/OAuth2ServerBundle/DependencyInjection\Compiler\OAuth2CompilerPass.php namespace Amce\OAuth2ServerBundle\DependencyInjection\Compiler; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; use Symfony\Component\DependencyInjection\Reference; class OAuth2CompilerPass implements CompilerPassInterface < public function process(ContainerBuilder $container) < // Override Refresh Token Grant Type Settings $serviceId = 'oauth2.grant_type.refresh_token'; if ($container->hasDefinition($serviceId)) < $definition = $container->getDefinition($serviceId); $definition->replaceArgument(1, array( 'always_issue_new_refresh_token' => TRUE )); > > >

About

OAuth2 for your Symfony Application

Источник

Step-By-Step Walkthrough

The following instructions provide a detailed walkthrough to help you get an OAuth2 server up and running. To see the codebase of an existing OAuth2 server implementing this library, check out the OAuth2 Demo.

Initialize your Project

Create a directory for your project and pull in this library

mkdir my-oauth2-walkthrough cd my-oauth2-walkthrough git clone https://github.com/bshaffer/oauth2-server-php.git -b master

Define your Schema

Now use the following schema to create the default database:

MySQL / SQLite / PostgreSQL / MS SQL Server

CREATE TABLE oauth_clients ( client_id VARCHAR(80) NOT NULL, client_secret VARCHAR(80), redirect_uri VARCHAR(2000), grant_types VARCHAR(80), scope VARCHAR(4000), user_id VARCHAR(80), PRIMARY KEY (client_id) ); CREATE TABLE oauth_access_tokens ( access_token VARCHAR(40) NOT NULL, client_id VARCHAR(80) NOT NULL, user_id VARCHAR(80), expires TIMESTAMP NOT NULL, scope VARCHAR(4000), PRIMARY KEY (access_token) ); CREATE TABLE oauth_authorization_codes ( authorization_code VARCHAR(40) NOT NULL, client_id VARCHAR(80) NOT NULL, user_id VARCHAR(80), redirect_uri VARCHAR(2000), expires TIMESTAMP NOT NULL, scope VARCHAR(4000), id_token VARCHAR(1000), PRIMARY KEY (authorization_code) ); CREATE TABLE oauth_refresh_tokens ( refresh_token VARCHAR(40) NOT NULL, client_id VARCHAR(80) NOT NULL, user_id VARCHAR(80), expires TIMESTAMP NOT NULL, scope VARCHAR(4000), PRIMARY KEY (refresh_token) ); CREATE TABLE oauth_users ( username VARCHAR(80), password VARCHAR(80), first_name VARCHAR(80), last_name VARCHAR(80), email VARCHAR(80), email_verified BOOLEAN, scope VARCHAR(4000), PRIMARY KEY (username) ); CREATE TABLE oauth_scopes ( scope VARCHAR(80) NOT NULL, is_default BOOLEAN, PRIMARY KEY (scope) ); CREATE TABLE oauth_jwt ( client_id VARCHAR(80) NOT NULL, subject VARCHAR(80), public_key VARCHAR(2000) NOT NULL );

Bootstrap your OAuth2 Server

We need to create and configure our OAuth2 Server object. This will be used by all the endpoints in our application. Name this file server.php :

$dsn = 'mysql:dbname=my_oauth2_db;host=localhost'; $username = 'root'; $password = ''; // error reporting (this is a demo, after all!) ini_set('display_errors',1);error_reporting(E_ALL); // Autoloading (composer is preferred, but for this example let's just do this) require_once('oauth2-server-php/src/OAuth2/Autoloader.php'); OAuth2\Autoloader::register(); // $dsn is the Data Source Name for your database, for exmaple "mysql:dbname=my_oauth2_db;host=localhost" $storage = new OAuth2\Storage\Pdo(array('dsn' => $dsn, 'username' => $username, 'password' => $password)); // Pass a storage object or array of storage objects to the OAuth2 server class $server = new OAuth2\Server($storage); // Add the "Client Credentials" grant type (it is the simplest of the grant types) $server->addGrantType(new OAuth2\GrantType\ClientCredentials($storage)); // Add the "Authorization Code" grant type (this is where the oauth magic happens) $server->addGrantType(new OAuth2\GrantType\AuthorizationCode($storage));

Note: Be sure to define the $dsn , $username , and $password variables to be the appropriate values for your database.

Create a Token Controller

Next, we will create the Token Controller. This is the URI which returns an OAuth2.0 Token to the client. Here is an example of a token controller in the file token.php :

// include our OAuth2 Server object require_once __DIR__.'/server.php'; // Handle a request for an OAuth2.0 Access Token and send the response to the client $server->handleTokenRequest(OAuth2\Request::createFromGlobals())->send();

Congratulatons! You have created a Token Controller! Do you want to see it in action? Run the following SQL to create an OAuth Client:

INSERT INTO oauth_clients (client_id, client_secret, redirect_uri) VALUES ("testclient", "testpass", "http://fake/");

Now run the following from the command line:

curl -u testclient:testpass http://localhost/token.php -d 'grant_type=client_credentials'

Note: http://localhost/token.php assumes you have the file token.php on your local machine, and you have set up the “localhost” webhost to point to it. This may vary for your application.

If everything works, you should receive a response like this:

"access_token":"03807cb390319329bdf6c777d4dfae9c0d3b3c35","expires_in":3600,"token_type":"bearer","scope":null>

Create a Resource Controller

Now that you are creating tokens, you’ll want to validate them in your APIs. Here is an example of a resource controller in the file resource.php :

// include our OAuth2 Server object require_once __DIR__.'/server.php'; // Handle a request to a resource and authenticate the access token if (!$server->verifyResourceRequest(OAuth2\Request::createFromGlobals())) < $server->getResponse()->send(); die; > echo json_encode(array('success' => true, 'message' => 'You accessed my APIs!'));

Now run the following from the command line:

curl http://localhost/resource.php -d 'access_token=YOUR_TOKEN'

Note: Use the value returned in “access_token” from the previous step in place of YOUR_TOKEN

If all goes well, you should receive a response like this:

"success":true,"message":"You accessed my APIs!">

Create an Authorize Controller

Authorize Controllers are the “killer feature” of OAuth2, and allow for your users to authorize third party applications. Instead of issuing an Access Token straightaway as happened in the first token controller example, in this example an authorize controller is used to only issue a token once the user has authorized the request. Create authorize.php :

// include our OAuth2 Server object require_once __DIR__.'/server.php'; $request = OAuth2\Request::createFromGlobals(); $response = new OAuth2\Response(); // validate the authorize request if (!$server->validateAuthorizeRequest($request, $response)) < $response->send(); die; > // display an authorization form if (empty($_POST)) < exit('   
'
); > // print the authorization code if the user has authorized your client $is_authorized = ($_POST['authorized'] === 'yes'); $server->handleAuthorizeRequest($request, $response, $is_authorized); if ($is_authorized) < // this is only here so that you get to see your code in the cURL request. Otherwise, we'd redirect back to the client $code = substr($response->getHttpHeader('Location'), strpos($response->getHttpHeader('Location'), 'code=')+5, 40); exit("SUCCESS! Authorization Code: $code"); > $response->send();

Now paste the following URL in your browser

Источник

Читайте также:  Python load local file
Оцените статью