bekirozturk / symfony-oauth2-bundle
A Symfony bundle for OAuth2 authentication, providing an easy way to integrate OAuth2 login with PKCE support. Designed for secure and reusable OAuth2 integrations in Symfony applications.
Installs: 4
Dependents: 0
Suggesters: 0
Security: 0
Stars: 0
Watchers: 1
Forks: 0
Open Issues: 0
Type:symfony-bundle
Requires
- php: >=7.2.5
- symfony/framework-bundle: ^5.4
- symfony/http-client: ^5.4
- symfony/security-bundle: ^5.4
Requires (Dev)
- symfony/phpunit-bridge: ^5.4
- symfony/test-pack: ^1.0
README
Navigation
TR
Bu bundle, OAuth2 kimlik doğrulama işlemlerini Symfony uygulamanıza entegre etmenizi sağlar.
TR Kurulum
Composer ile yükleyin:
composer require bekirozturk/symfony-oauth2-bundle
TR Konfigürasyon
Bundle, Symfony Flex tarafından otomatik olarak config/bundles.php
dosyasına eklenecektir. Eğer otomatik olarak eklenmemişse, manuel olarak aşağıdaki satırı ekleyebilirsiniz:
return [ // ... Symfony\Bundle\OAuth2Bundle\SymfonyOAuth2Bundle::class => ['all' => true], ];
.env
dosyanızda aşağıdaki değişkenleri tanımlayın:
Önemli Not: Aşağıdaki değişkenlerin değerlerini SSO sağlayıcınızdan (Identity Provider) almanız gerekmektedir. Bu bilgiler SSO entegrasyonu için gerekli olan endpoint URL'leri ve kimlik bilgileridir.
# SSO sağlayıcısından almanız gereken kimlik bilgileri OAUTH_CLIENT_ID=your_client_id # SSO uygulamanızın client ID'si OAUTH_CLIENT_SECRET=your_client_secret # SSO uygulamanızın client secret'ı # SSO sağlayıcısının endpoint URL'leri (SSO sağlayıcısından alınmalıdır) OAUTH_AUTHORIZE_URL=http://sso-provider/oauth2/authorize # Yetkilendirme endpoint'i OAUTH_TOKEN_URL=http://sso-provider/oauth2/token # Token endpoint'i OAUTH_USERINFO_URL=http://sso-provider/api/userinfo # Kullanıcı bilgileri endpoint'i # SSO sağlayıcısı tarafından desteklenen ve size verilen değerler OAUTH_SCOPE=your_scope # İzin istenen kapsamlar (örn: "openid profile email") OAUTH_CODE_CHALLENGE_METHOD=S256 # PKCE metodu (genellikle S256) OAUTH_RESPONSE_TYPE=code # Response type (genellikle "code") OAUTH_GRANT_TYPE=authorization_code # Grant type (genellikle "authorization_code") # Sizin uygulamanızın callback URL'i (SSO sağlayıcısına bildirmeniz gerekir) OAUTH_REDIRECT_URI=http://localhost/oauth2/check
Önemli Not:
OAUTH_REDIRECT_URI
değeri, SSO entegrasyonu sırasında SSO sağlayıcısına bildirmeniz gereken callback URL'idir. Bu URL, kullanıcı başarılı bir şekilde kimlik doğrulaması yaptıktan sonra SSO sağlayıcısının kullanıcıyı yönlendireceği adrestir. SSO sağlayıcısının güvenlik ayarlarında bu URL'i izin verilen redirect URI'lar listesine eklemeniz gerekmektedir.- Diğer tüm endpoint URL'leri ve konfigürasyon değerleri SSO sağlayıcınız tarafından size verilmelidir. Bu değerler SSO sağlayıcısının OAuth2 sistemine göre değişiklik gösterebilir.
TR Docker
Eğer uygulamanızı Docker ortamında çalıştırıyorsanız ve SSO sunucunuz da yerel makinenizde (localhost) çalışıyorsa, aşağıdaki adımları takip edin:
- Docker container'ınızın host makineye erişebilmesi için
docker-compose.yml
dosyanızda PHP servisine aşağıdaki ayarı ekleyin:
services: php: # ... diğer ayarlar ... extra_hosts: - "host.docker.internal:host-gateway" # Host makineye erişim için gerekli
.env
dosyanızda aşağıdaki konfigürasyonu kullanın:
# SSO sağlayıcısından almanız gereken kimlik bilgileri OAUTH_CLIENT_ID=your_client_id OAUTH_CLIENT_SECRET=your_client_secret # Docker içinden host makineye erişim için host.docker.internal kullanın OAUTH_AUTHORIZE_URL=http://host.docker.internal:9002/oauth2/authorize OAUTH_TOKEN_URL=http://host.docker.internal:9002/oauth2/token OAUTH_USERINFO_URL=http://host.docker.internal:9002/api/userinfo # Callback URL'i host makineden erişileceği şekilde ayarlayın OAUTH_REDIRECT_URI=http://localhost/oauth2/check # Diğer ayarlar OAUTH_SCOPE=your_scope OAUTH_CODE_CHALLENGE_METHOD=S256 OAUTH_RESPONSE_TYPE=code OAUTH_GRANT_TYPE=authorization_code
Önemli Not:
- Docker container'ından host makineye erişmek için
localhost
yerinehost.docker.internal
kullanılmalıdır.OAUTH_REDIRECT_URI
değeri, tarayıcıdan erişileceği içinlocalhost
olarak kalmalıdır.- Port numaralarını (örnekte 9002) kendi SSO sunucunuzun çalıştığı porta göre ayarlayın.
TR Kullanım
OAuth2 login sayfasına yönlendirmek için:
// Controller'ınızda use Symfony\Bundle\OAuth2Bundle\Controller\AuthController; return $this->redirectToRoute('oauth2_authorize');
veya Twig template'inizde:
<a href="{{ path('oauth2_authorize') }}">OAuth2 ile Giriş Yap</a>
TR Rotalar
Bundle aşağıdaki rotaları tanımlar:
/oauth2/authorize
: OAuth2 sunucusuna yönlendirme (oauth2_authorize)/oauth2/check
: OAuth2 sunucusundan dönüş noktası (oauth2_check)/oauth2/success
: Başarılı kimlik doğrulama sonrası yönlendirme (app_oauth2_success)
TR Özelleştirme
Bundle, başarılı kimlik doğrulama sonrası /oauth2/success
endpoint'ine yönlendirir. Bu endpoint'i kendi ihtiyaçlarınıza göre özelleştirebilirsiniz. Örneğin:
// src/Controller/SymfonyOauth2Controller.php namespace App\Controller; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Routing\Annotation\Route; class SymfonyOauth2Controller extends AbstractController { #[Route('/oauth2/success', name: 'app_oauth2_success')] public function success(): Response { // Session'dan kullanıcı bilgilerini al $userInfo = $this->get('session')->get('oauth2_user_info'); // Kullanıcı bilgilerini kullanarak kendi login mantığınızı uygulayın // Örneğin: // - Kullanıcıyı veritabanında kontrol edin // - Yeni kullanıcı oluşturun // - Oturum açın // - Başka bir sayfaya yönlendirin return $this->render('oauth2/success.html.twig', [ 'user_info' => $userInfo ]); } }
TR Kaldırma
Bundle'ı kaldırdığınızda, aşağıdaki dosyaları manuel olarak silmeniz gerekir:
# Konfigürasyon dosyalarını sil rm config/packages/symfony_oauth2.yaml rm config/routes/symfony_oauth2.yaml # Controller dosyasını sil rm src/Controller/SymfonyOauth2Controller.php
Ardından bundle'ı composer.json'dan kaldırın:
composer remove bekirozturk/symfony-oauth2-bundle
TR Servisler
Bundle aşağıdaki servisleri sağlar:
OAuth2Service
OAuth2Service, SSO entegrasyonu için gerekli temel metodları sağlar:
use Symfony\Bundle\OAuth2Bundle\Service\OAuth2Service; class YourController { private $oauthService; public function __construct(OAuth2Service $oauthService) { $this->oauthService = $oauthService; } public function someAction() { // SSO yetkilendirme URL'ini oluşturma $state = bin2hex(random_bytes(16)); $codeVerifier = bin2hex(random_bytes(32)); $authUrl = $this->oauthService->getAuthorizationUrl($state, $codeVerifier); // Access token alma $tokenData = $this->oauthService->requestAccessToken($code, $codeVerifier); // Kullanıcı bilgilerini alma $userInfo = $this->oauthService->getUserInfo($tokenData['access_token']); } }
OAuth2Service şu metodları sağlar:
getAuthorizationUrl(string $state, string $codeVerifier)
: PKCE destekli OAuth2 yetkilendirme URL'ini oluştururrequestAccessToken(string $code, string $codeVerifier)
: Authorization code ile access token alırgetUserInfo(string $accessToken)
: Access token kullanarak kullanıcı bilgilerini getirir
License / Lisans
MIT
EN
This bundle allows you to integrate OAuth2 authentication into your Symfony application.
EN Installation
Install with Composer:
composer require bekirozturk/symfony-oauth2-bundle
EN Configuration
The bundle will be automatically added to your config/bundles.php
by Symfony Flex. If not, you can add it manually:
return [ // ... Symfony\Bundle\OAuth2Bundle\SymfonyOAuth2Bundle::class => ['all' => true], ];
- Define the following variables in your
.env
file:
Important Note: You need to obtain the following values from your SSO provider (Identity Provider). These are the endpoint URLs and credentials required for SSO integration.
# Credentials from your SSO provider OAUTH_CLIENT_ID=your_client_id # Your SSO application's client ID OAUTH_CLIENT_SECRET=your_client_secret # Your SSO application's client secret # SSO provider endpoint URLs (must be obtained from SSO provider) OAUTH_AUTHORIZE_URL=http://sso-provider/oauth2/authorize # Authorization endpoint OAUTH_TOKEN_URL=http://sso-provider/oauth2/token # Token endpoint OAUTH_USERINFO_URL=http://sso-provider/api/userinfo # User info endpoint # Values supported and provided by your SSO provider OAUTH_SCOPE=your_scope # Requested scopes (e.g., "openid profile email") OAUTH_CODE_CHALLENGE_METHOD=S256 # PKCE method (usually S256) OAUTH_RESPONSE_TYPE=code # Response type (usually "code") OAUTH_GRANT_TYPE=authorization_code # Grant type (usually "authorization_code") # Your application's callback URL (must be registered with SSO provider) OAUTH_REDIRECT_URI=http://localhost/oauth2/check
Important Note:
- The
OAUTH_REDIRECT_URI
value must be registered with your SSO provider. This URL is where the SSO provider will redirect users after successful authentication. You need to add this URL to the list of allowed redirect URIs in your SSO provider's security settings.- All other endpoint URLs and configuration values must be provided by your SSO provider. These values may vary depending on the OAuth2 system of your SSO provider.
EN Docker
If you're running your application in Docker and your SSO server is running on your local machine (localhost), follow these steps:
- Add the following configuration to your PHP service in
docker-compose.yml
:
services: php: # ... other settings ... extra_hosts: - "host.docker.internal:host-gateway" # Required for host machine access
- Use the following configuration in your
.env
file:
# Credentials from your SSO provider OAUTH_CLIENT_ID=your_client_id OAUTH_CLIENT_SECRET=your_client_secret # Use host.docker.internal for accessing host machine from Docker OAUTH_AUTHORIZE_URL=http://host.docker.internal:9002/oauth2/authorize OAUTH_TOKEN_URL=http://host.docker.internal:9002/oauth2/token OAUTH_USERINFO_URL=http://host.docker.internal:9002/api/userinfo # Set callback URL as it will be accessed from browser OAUTH_REDIRECT_URI=http://localhost/oauth2/check # Other settings OAUTH_SCOPE=your_scope OAUTH_CODE_CHALLENGE_METHOD=S256 OAUTH_RESPONSE_TYPE=code OAUTH_GRANT_TYPE=authorization_code
Important Note:
- Use
host.docker.internal
instead oflocalhost
to access the host machine from Docker container.- Keep
OAUTH_REDIRECT_URI
aslocalhost
since it will be accessed from the browser.- Adjust port numbers (9002 in the example) according to your SSO server's port.
EN Usage
To redirect to the OAuth2 login page:
// In your controller use Symfony\Bundle\OAuth2Bundle\Controller\AuthController; return $this->redirectToRoute('oauth2_authorize');
or in your Twig template:
<a href="{{ path('oauth2_authorize') }}">Login with OAuth2</a>
EN Routes
The bundle defines the following routes:
/oauth2/authorize
: Redirect to OAuth2 server (oauth2_authorize)/oauth2/check
: OAuth2 server callback endpoint (oauth2_check)/oauth2/success
: Successful authentication redirect endpoint (app_oauth2_success)
EN Customization
After successful authentication, the bundle redirects to the /oauth2/success
endpoint. You can customize this endpoint according to your needs. For example:
// src/Controller/SymfonyOauth2Controller.php namespace App\Controller; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Routing\Annotation\Route; class SymfonyOauth2Controller extends AbstractController { #[Route('/oauth2/success', name: 'app_oauth2_success')] public function success(): Response { // Get user info from session $userInfo = $this->get('session')->get('oauth2_user_info'); // Implement your own login logic using user info // For example: // - Check user in database // - Create new user // - Log in // - Redirect to another page return $this->render('oauth2/success.html.twig', [ 'user_info' => $userInfo ]); } }
EN Uninstall
When uninstalling the bundle, you need to manually remove the following files:
# Remove configuration files rm config/packages/symfony_oauth2.yaml rm config/routes/symfony_oauth2.yaml # Remove controller file rm src/Controller/SymfonyOauth2Controller.php
Then remove the bundle from composer.json:
composer remove bekirozturk/symfony-oauth2-bundle
EN Services
The bundle provides the following services:
OAuth2Service
OAuth2Service provides the core methods needed for SSO integration:
use Symfony\Bundle\OAuth2Bundle\Service\OAuth2Service; class YourController { private $oauthService; public function __construct(OAuth2Service $oauthService) { $this->oauthService = $oauthService; } public function someAction() { // Generate SSO authorization URL $state = bin2hex(random_bytes(16)); $codeVerifier = bin2hex(random_bytes(32)); $authUrl = $this->oauthService->getAuthorizationUrl($state, $codeVerifier); // Get access token $tokenData = $this->oauthService->requestAccessToken($code, $codeVerifier); // Get user information $userInfo = $this->oauthService->getUserInfo($tokenData['access_token']); } }
OAuth2Service provides the following methods:
getAuthorizationUrl(string $state, string $codeVerifier)
: Generates PKCE-enabled OAuth2 authorization URLrequestAccessToken(string $code, string $codeVerifier)
: Gets access token using authorization codegetUserInfo(string $accessToken)
: Gets user information using access token
License / Lisans
MIT