Présentation pour meetup d'AFUP : https://www.meetup.com/fr-FR/afup-paris-php/events/253944518/
Le code : https://github.com/vria/symfony-security-component-use
Sécurisation de vos applications web à l’aide du composant Security de SymfonyVladyslav Riabchenko
L'authentification et l’autorisation sont omniprésents dans les applications web. Cependant la sécurisation des applications Symfony semble assez compliquée surtout pour les débutants. Je vous propose d'examiner le composant Security de Symfony pour comprendre comment la couche d'authentification est organisée et comment les règles d'autorisation sont implémentées. Nous verrons les classes qui se cachent derrière la configuration dans votre security.yml.
- Symfony 1.1 focuses on internal refactoring and removing singleton patterns
- Singletons like sfConfigCache and sfContext that were globally accessible are removed
- Dependencies between components are cleaned up
- An sfEventDispatcher is added based on the Cocoa Notification Center to decouple components and allow flexible event handling
- Core classes like sfRequest, sfResponse, sfUser, and sfStorage are introduced to represent the web workflow in object-oriented terms and allow mocking for testing
- This refactoring paves the way for Symfony 2.0 by shifting to a more decoupled and testable architecture
Speed up your developments with Symfony2Hugo Hamon
Symfony2 is a PHP full-stack framework that provides tools and components to speed up web development. It emphasizes separation of concerns, standards compliance, and best practices. Symfony2 allows developers to create Request-Response applications using its routing, templating, validation, forms, database abstraction, and other features in a decoupled and reusable way. It also provides debugging tools, code generators, and other utilities to improve developer productivity.
UK Symfony Meetup, November 2012
Original presentation: https://docs.google.com/presentation/pub?id=1PLcqTby6yqSbfWlMIDHknH852DU6DO6OAgQJOtSEdsg&start=false&loop=false&delayms=3000
Symfony components in the wild, PHPNW12Jakub Zalas
Symfony is a set of reusable and decoupled PHP components designed to solve common web development problems. While as a framework it might not be the best for some of your projects, you can always build on top of its solid foundation of well written, tested and flexible components.
Original presentation: https://docs.google.com/presentation/pub?id=136blt1DWJ95yuEdpmjz9dIqgg38VwEXBQlY7bu0Op8w&start=false&loop=false&delayms=3000
The document discusses developing PHP applications that run from the command line interface rather than a web server. It covers using the $ARGC and $ARGV variables to access command line arguments, and introduces more advanced libraries like Symfony Console and Zend Console that provide features like commands, options, and help output for building robust CLI applications and tools.
This document describes building a single page application for authentication against multiple third party services like Facebook and Windows Live using OAuth2 and without page reloads. It discusses using an OAuth adapter and service-specific adapters to handle the different OAuth grant types and flows. Key parts of the implementation include injecting a session service, opening authentication as a promise, handling the redirect flow with a popup window, and reading the access token from the hash fragment or popup message.
Sécurisation de vos applications web à l’aide du composant Security de SymfonyVladyslav Riabchenko
L'authentification et l’autorisation sont omniprésents dans les applications web. Cependant la sécurisation des applications Symfony semble assez compliquée surtout pour les débutants. Je vous propose d'examiner le composant Security de Symfony pour comprendre comment la couche d'authentification est organisée et comment les règles d'autorisation sont implémentées. Nous verrons les classes qui se cachent derrière la configuration dans votre security.yml.
- Symfony 1.1 focuses on internal refactoring and removing singleton patterns
- Singletons like sfConfigCache and sfContext that were globally accessible are removed
- Dependencies between components are cleaned up
- An sfEventDispatcher is added based on the Cocoa Notification Center to decouple components and allow flexible event handling
- Core classes like sfRequest, sfResponse, sfUser, and sfStorage are introduced to represent the web workflow in object-oriented terms and allow mocking for testing
- This refactoring paves the way for Symfony 2.0 by shifting to a more decoupled and testable architecture
Speed up your developments with Symfony2Hugo Hamon
Symfony2 is a PHP full-stack framework that provides tools and components to speed up web development. It emphasizes separation of concerns, standards compliance, and best practices. Symfony2 allows developers to create Request-Response applications using its routing, templating, validation, forms, database abstraction, and other features in a decoupled and reusable way. It also provides debugging tools, code generators, and other utilities to improve developer productivity.
UK Symfony Meetup, November 2012
Original presentation: https://docs.google.com/presentation/pub?id=1PLcqTby6yqSbfWlMIDHknH852DU6DO6OAgQJOtSEdsg&start=false&loop=false&delayms=3000
Symfony components in the wild, PHPNW12Jakub Zalas
Symfony is a set of reusable and decoupled PHP components designed to solve common web development problems. While as a framework it might not be the best for some of your projects, you can always build on top of its solid foundation of well written, tested and flexible components.
Original presentation: https://docs.google.com/presentation/pub?id=136blt1DWJ95yuEdpmjz9dIqgg38VwEXBQlY7bu0Op8w&start=false&loop=false&delayms=3000
The document discusses developing PHP applications that run from the command line interface rather than a web server. It covers using the $ARGC and $ARGV variables to access command line arguments, and introduces more advanced libraries like Symfony Console and Zend Console that provide features like commands, options, and help output for building robust CLI applications and tools.
This document describes building a single page application for authentication against multiple third party services like Facebook and Windows Live using OAuth2 and without page reloads. It discusses using an OAuth adapter and service-specific adapters to handle the different OAuth grant types and flows. Key parts of the implementation include injecting a session service, opening authentication as a promise, handling the redirect flow with a popup window, and reading the access token from the hash fragment or popup message.
The document discusses PHP and Cassandra. It provides an introduction to Cassandra including what it is, where it came from, and its key advantages. It then discusses how to model data in Cassandra and provides examples of creating a keyspace and column family. The document also discusses different PHP libraries for interacting with Cassandra like PHPCassa and using Thrift directly. It provides examples of basic operations like insert, select, delete and more using these different PHP libraries.
This document discusses Symfony 2.0 and its new features.
[1] Symfony 2.0 will require PHP 5.3 and features a new lightweight request handling system. Key components like the event dispatcher and dependency injection container have been extracted into standalone packages.
[2] The request handler is responsible for dispatching events, loading controllers, and ensuring requests are converted to responses. It is very lightweight, being under 100 lines of code.
[3] Symfony 2.0 aims to be highly flexible and optimized for performance. Benchmark tests show the new request handling system can be up to 10 times faster than Symfony 1.x.
This document discusses various vulnerabilities in PHP coding practices and provides examples of how each vulnerability can be exploited as well as how to fix them. It covers remote file inclusion, local file inclusion, local file disclosure, SQL injection, remote command execution, remote code execution, cross-site scripting, authentication bypass, and cross-site request forgery vulnerabilities. For each vulnerability, it provides a basic PHP code example to demonstrate the issue, how an attacker could exploit it, and recommendations on how to fix the vulnerable code, such as sanitizing user inputs, using prepared statements, and implementing authentication systems. The goal is to help PHP developers write more secure code and avoid common vulnerabilities.
This document demonstrates how to use Blackfire Player to test web APIs and applications. It shows how to:
1. Install and run Blackfire Player to define and run test scenarios against a web API.
2. Integrate Blackfire to collect performance metrics and reports during tests.
3. Dockerize the testing process to easily run the same tests against environments like staging.
The document discusses building applications without frameworks by using Symfony components independently. It describes how to handle HTTP requests and responses with the HttpFoundation component, map URLs to routes with the Routing component, manage service dependencies with DependencyInjection, and build an application kernel and controllers to tie it all together without relying on an existing framework.
Respect\Validation is a PHP validation library that provides over 100 validation rules and fluent validation methods. It allows validating data using intuitive method chaining and provides custom validation messages. The library has over 175,000 installations via Composer and averages 13,000 new installations per month. It can be used to validate data from $_POST in several frameworks like Zend, Symfony, and Laravel. The library also supports custom validation rules, internationalization, and unit testing of rules.
The symfony platform: Create your very own framework (PHP Quebec 2008)Fabien Potencier
The document discusses how to use Symfony classes to build your own custom web framework. It describes how common PHP global variables and functions can be replaced with Symfony request, response, user and event dispatcher objects to abstract away dependencies and add object-oriented behaviors. The document provides examples of initializing these Symfony classes and using them to process a request similarly to how it was done procedurally with PHP globals previously.
This document discusses securing PHP applications. It covers best practices for securing input data, preventing vulnerabilities like SQL injection and cross-site scripting (XSS), and properly validating all user input. It also provides recommendations for secure file permissions, error handling, and hiding sensitive configuration details.
Like many others, WordPress has been my personal blogging tool for a long time. A powerful tool for easy publishing! That is what everyone wants.
Large sites like TechCrunch and TheNextWeb use it exactly for that reason. And more enterprises seem to discover it as good solution to their too-expensive publication tools. But keeping those WordPress instances running requires skills and knowledge.
Because of WordPress extendibility and its very active community, you can do this too. This tutorial will teach you how use Ansible, Composer, WP-CLI, WP REST API, and Elasticsearch can push WordPress from a personal blogging tool into an enterprise-worthy level application. Out with FTP based SCM ... in with automated deployment, dependency management, and utterly fast search.
The document provides an overview of the Symfony2 framework from its creator Fabien Potencier. It discusses several key aspects in 3 or less sentences:
- Symfony2 is not yet ready for production but is estimated to reach stable status in March 2011. Some developers are already using pre-release versions.
- The translation component allows translating text and handling pluralization. Template engines like Twig can be used to integrate translations into views.
- Forms can be customized by overriding rendering blocks for different field types in custom templates applied to individual forms or globally.
- Security features like authentication, authorization, and protecting against attacks are integrated. Users can be loaded from different
Shows how to be an oauth consumer and provider from PHP - OAuth 1 - including handling of tokens, secrets, and handling the workflow for devices. Also covers the workflow for OAuth 2
This document provides biographical information about Fabien Potencier and discusses his upcoming presentation titled "PHP 5.3 in practice". It notes that Fabien is the founder of Sensio, a consulting company specialized in web technologies, and the creator of several open source projects including Symfony. The presentation will cover reasons for migrating to PHP 5.3 such as improved speed and lower memory usage, how PHP 5.3 affects design patterns like the singleton, and new features like namespaces and anonymous functions.
The REST API is an awesome plugin to expose your data from the WordPress core. But … the standard implementation might not fit your specific case.
Just like the WordPress core, you'll be able to extend it to your specific needs. I'll show you how to handle authentication, introduce caching strategies, alter custom post types, or even change the default way of communication altogether.
Slides from the GTA-PHP meetup about the new features in PHP 7. Slides had corresponding RFC pages linked to them in the speaker notes, but they don't seem to correspond to pages here so I've made the original keynote file available at http://gtaphp.org/presentations/NewInPHP7.zip and a PowerPoint version at http://gtaphp.org/presentations/NewInPHP7.pptx.
The document discusses Symfony2, an open-source PHP web application framework. It provides an overview of its components including routing, dependency injection, and templating. It also describes how Symfony uses an MVC architecture and emphasizes loose coupling and flexibility.
The document provides an overview of Symfony2, an open-source PHP web application framework. It describes Symfony2 as a set of decoupled and cohesive components including routing, templating, form handling, and more. It also outlines Symfony2's support for modern best practices like dependency injection and an object-oriented approach to web application development using the Model-View-Controller pattern.
This document provides an overview of dependency injection and describes how to build a simple dependency injection container in PHP 5.3 using anonymous functions (lambdas). It discusses how the container can be used to manage parameters, describe object creation through lambdas, handle object scoping, and provide a unified interface. The container allows decoupling object dependencies and makes configuration and customization natural. Anonymous functions allow capturing context and scope, which is leveraged to implement features like shared instances. Overall, the document shows how lambdas can power a fully-featured yet concise dependency injection container in PHP.
This document discusses various techniques for debugging and customizing SOAP requests and responses using PHP's SOAP extension (ext/soap). It covers topics like:
- Debugging SOAP calls by enabling tracing and accessing request/response data
- Adding authentication headers to SOAP requests
- Overriding the endpoint location for individual calls
- Intercepting calls to modify requests or responses
- Mapping complex XML types to PHP classes
- Setting custom XML schema types
The document discusses best practices for unit and functional testing PHP applications using PHPUnit. It covers setting up test directories and configuration files, creating test cases, making requests with the test client, and using assertions to validate responses. Functional tests are recommended over unit tests for application controllers. Techniques like request insulation and profiling responses are also described.
Les web-services sont aujourd'hui au centre des SI de nos entreprises. Ils permettent de transmettre l'information entre des systèmes hétérogènes, à la fois au sein de l’entreprise mais également à l'extérieur, notamment et de plus en plus vers des systèmes mobiles. Or exposer cette information, potentiellement critique, pose la question de la sécurisation de ces échanges. Cette présentation sera l'occasion de présenter JWT, d'expliquer son fonctionnement et son implémentation au sein d'un projet Symfony 3.
How to Build an Indivo X Personal Health AppBen Adida
Indivo X allows developers to build personal health apps that integrate with Indivo health records. The four key steps to building an app are: 1) defining the app's scope and functionality, 2) implementing authentication and authorization via OAuth, 3) making REST API calls to read and write data, and 4) using provided UI widgets for features like auto-complete and sharing/audit controls. The process aims to make app development simple while enabling access to rich health record data.
The document discusses PHP and Cassandra. It provides an introduction to Cassandra including what it is, where it came from, and its key advantages. It then discusses how to model data in Cassandra and provides examples of creating a keyspace and column family. The document also discusses different PHP libraries for interacting with Cassandra like PHPCassa and using Thrift directly. It provides examples of basic operations like insert, select, delete and more using these different PHP libraries.
This document discusses Symfony 2.0 and its new features.
[1] Symfony 2.0 will require PHP 5.3 and features a new lightweight request handling system. Key components like the event dispatcher and dependency injection container have been extracted into standalone packages.
[2] The request handler is responsible for dispatching events, loading controllers, and ensuring requests are converted to responses. It is very lightweight, being under 100 lines of code.
[3] Symfony 2.0 aims to be highly flexible and optimized for performance. Benchmark tests show the new request handling system can be up to 10 times faster than Symfony 1.x.
This document discusses various vulnerabilities in PHP coding practices and provides examples of how each vulnerability can be exploited as well as how to fix them. It covers remote file inclusion, local file inclusion, local file disclosure, SQL injection, remote command execution, remote code execution, cross-site scripting, authentication bypass, and cross-site request forgery vulnerabilities. For each vulnerability, it provides a basic PHP code example to demonstrate the issue, how an attacker could exploit it, and recommendations on how to fix the vulnerable code, such as sanitizing user inputs, using prepared statements, and implementing authentication systems. The goal is to help PHP developers write more secure code and avoid common vulnerabilities.
This document demonstrates how to use Blackfire Player to test web APIs and applications. It shows how to:
1. Install and run Blackfire Player to define and run test scenarios against a web API.
2. Integrate Blackfire to collect performance metrics and reports during tests.
3. Dockerize the testing process to easily run the same tests against environments like staging.
The document discusses building applications without frameworks by using Symfony components independently. It describes how to handle HTTP requests and responses with the HttpFoundation component, map URLs to routes with the Routing component, manage service dependencies with DependencyInjection, and build an application kernel and controllers to tie it all together without relying on an existing framework.
Respect\Validation is a PHP validation library that provides over 100 validation rules and fluent validation methods. It allows validating data using intuitive method chaining and provides custom validation messages. The library has over 175,000 installations via Composer and averages 13,000 new installations per month. It can be used to validate data from $_POST in several frameworks like Zend, Symfony, and Laravel. The library also supports custom validation rules, internationalization, and unit testing of rules.
The symfony platform: Create your very own framework (PHP Quebec 2008)Fabien Potencier
The document discusses how to use Symfony classes to build your own custom web framework. It describes how common PHP global variables and functions can be replaced with Symfony request, response, user and event dispatcher objects to abstract away dependencies and add object-oriented behaviors. The document provides examples of initializing these Symfony classes and using them to process a request similarly to how it was done procedurally with PHP globals previously.
This document discusses securing PHP applications. It covers best practices for securing input data, preventing vulnerabilities like SQL injection and cross-site scripting (XSS), and properly validating all user input. It also provides recommendations for secure file permissions, error handling, and hiding sensitive configuration details.
Like many others, WordPress has been my personal blogging tool for a long time. A powerful tool for easy publishing! That is what everyone wants.
Large sites like TechCrunch and TheNextWeb use it exactly for that reason. And more enterprises seem to discover it as good solution to their too-expensive publication tools. But keeping those WordPress instances running requires skills and knowledge.
Because of WordPress extendibility and its very active community, you can do this too. This tutorial will teach you how use Ansible, Composer, WP-CLI, WP REST API, and Elasticsearch can push WordPress from a personal blogging tool into an enterprise-worthy level application. Out with FTP based SCM ... in with automated deployment, dependency management, and utterly fast search.
The document provides an overview of the Symfony2 framework from its creator Fabien Potencier. It discusses several key aspects in 3 or less sentences:
- Symfony2 is not yet ready for production but is estimated to reach stable status in March 2011. Some developers are already using pre-release versions.
- The translation component allows translating text and handling pluralization. Template engines like Twig can be used to integrate translations into views.
- Forms can be customized by overriding rendering blocks for different field types in custom templates applied to individual forms or globally.
- Security features like authentication, authorization, and protecting against attacks are integrated. Users can be loaded from different
Shows how to be an oauth consumer and provider from PHP - OAuth 1 - including handling of tokens, secrets, and handling the workflow for devices. Also covers the workflow for OAuth 2
This document provides biographical information about Fabien Potencier and discusses his upcoming presentation titled "PHP 5.3 in practice". It notes that Fabien is the founder of Sensio, a consulting company specialized in web technologies, and the creator of several open source projects including Symfony. The presentation will cover reasons for migrating to PHP 5.3 such as improved speed and lower memory usage, how PHP 5.3 affects design patterns like the singleton, and new features like namespaces and anonymous functions.
The REST API is an awesome plugin to expose your data from the WordPress core. But … the standard implementation might not fit your specific case.
Just like the WordPress core, you'll be able to extend it to your specific needs. I'll show you how to handle authentication, introduce caching strategies, alter custom post types, or even change the default way of communication altogether.
Slides from the GTA-PHP meetup about the new features in PHP 7. Slides had corresponding RFC pages linked to them in the speaker notes, but they don't seem to correspond to pages here so I've made the original keynote file available at http://gtaphp.org/presentations/NewInPHP7.zip and a PowerPoint version at http://gtaphp.org/presentations/NewInPHP7.pptx.
The document discusses Symfony2, an open-source PHP web application framework. It provides an overview of its components including routing, dependency injection, and templating. It also describes how Symfony uses an MVC architecture and emphasizes loose coupling and flexibility.
The document provides an overview of Symfony2, an open-source PHP web application framework. It describes Symfony2 as a set of decoupled and cohesive components including routing, templating, form handling, and more. It also outlines Symfony2's support for modern best practices like dependency injection and an object-oriented approach to web application development using the Model-View-Controller pattern.
This document provides an overview of dependency injection and describes how to build a simple dependency injection container in PHP 5.3 using anonymous functions (lambdas). It discusses how the container can be used to manage parameters, describe object creation through lambdas, handle object scoping, and provide a unified interface. The container allows decoupling object dependencies and makes configuration and customization natural. Anonymous functions allow capturing context and scope, which is leveraged to implement features like shared instances. Overall, the document shows how lambdas can power a fully-featured yet concise dependency injection container in PHP.
This document discusses various techniques for debugging and customizing SOAP requests and responses using PHP's SOAP extension (ext/soap). It covers topics like:
- Debugging SOAP calls by enabling tracing and accessing request/response data
- Adding authentication headers to SOAP requests
- Overriding the endpoint location for individual calls
- Intercepting calls to modify requests or responses
- Mapping complex XML types to PHP classes
- Setting custom XML schema types
The document discusses best practices for unit and functional testing PHP applications using PHPUnit. It covers setting up test directories and configuration files, creating test cases, making requests with the test client, and using assertions to validate responses. Functional tests are recommended over unit tests for application controllers. Techniques like request insulation and profiling responses are also described.
Les web-services sont aujourd'hui au centre des SI de nos entreprises. Ils permettent de transmettre l'information entre des systèmes hétérogènes, à la fois au sein de l’entreprise mais également à l'extérieur, notamment et de plus en plus vers des systèmes mobiles. Or exposer cette information, potentiellement critique, pose la question de la sécurisation de ces échanges. Cette présentation sera l'occasion de présenter JWT, d'expliquer son fonctionnement et son implémentation au sein d'un projet Symfony 3.
How to Build an Indivo X Personal Health AppBen Adida
Indivo X allows developers to build personal health apps that integrate with Indivo health records. The four key steps to building an app are: 1) defining the app's scope and functionality, 2) implementing authentication and authorization via OAuth, 3) making REST API calls to read and write data, and 4) using provided UI widgets for features like auto-complete and sharing/audit controls. The process aims to make app development simple while enabling access to rich health record data.
The document discusses OAuth 2.0 libraries for PHP and Ruby. For PHP, it describes thephpleague/oauth2-client library which allows configuring 3 endpoint URLs and implementing the OAuth flow with conditional checks. For Ruby, it mentions omniauth/omniauth libraries like omniauth-twitter which simplify implementation by handling most complexity, with differences only in the 3 URLs. It also describes Doorkeeper for developing OAuth servers in Ruby on Rails, which works with Devise and allows registering client apps and users through predefined functions.
DEF CON 27 - ALVARO MUNOZ / OLEKSANDR MIROSH - sso wars the token menaceFelipe Prado
The document discusses various ways that authentication tokens can be abused to bypass security protections. It describes how some implementations of token parsing and signature verification are vulnerable to arbitrary code execution or information disclosure attacks due to inconsistencies in how signing keys and security tokens are resolved from token metadata. Specific attacks are demonstrated against Windows Communication Foundation, Windows Identity Foundation, and SharePoint Server due to differences in how key and token resolution are handled for signature verification versus token authentication.
CIS 2012 - Going Mobile with PingFederate and OAuth 2scotttomilson
Scott Tomilson discusses integrating mobile applications with PingFederate using OAuth 2. He covers OAuth 2 terminology, common grant types for mobile including authorization code, implicit, and resource owner password credentials. The presentation includes demonstrations of obtaining authorization codes and access tokens on mobile devices. Topics like secure token handling, single sign-on approaches, and challenges of combining native apps with browsers are also covered.
The document discusses implementing role-based security in .NET applications. It describes creating a web application with a login page, configuring forms authentication, generating authentication tickets for authenticated users, constructing GenericPrincipal and FormsIdentity objects, and testing the role-based functionality. Key steps include using the GenericPrincipal class to provide role-based authorization checking, attaching the principal object to the HTTP context to relate it to the current request, and confirming the principal object contains the correct identity and role information on subsequent pages.
Michael Peacock gave a presentation on Symfony components and related libraries. The presentation [1] introduced several Symfony components including routing, event dispatching, forms, validation, security, and HTTP foundation, [2] discussed related libraries like Pimple and Twig, and [3] covered how to install the components using Composer.
Implementing application security using the .net frameworkLalit Kale
This document provides an overview of application security features in the Microsoft .NET Framework. It covers code access security, role-based security using identities and principals, cryptography services for encryption and signing, securing ASP.NET web applications using forms authentication and validation controls, and securing ASP.NET web services using message-level security standards. The document also includes demonstrations of implementing these various security techniques in .NET applications and web services.
Building a Microgateway in Ballerina_KubeCon 2108Ballerina
API gateways play a critical role in modern enterprise architecture. As microservices strengthen their hold on modern-day application architectures, cloud native API gateways are high in demand. Ballerina, being a programming language designed to address and simplify the complexities of heavily distributed systems primarily built on microservice architectures, provides a rich set of language features and a smart compiler that makes it a good choice of technology to build a cloud native API gateway.
WP Passkey: Passwordless Authentication on WordPressWordPress
Passkeys are a safer and easier alternative to passwords. With passkeys, users can sign in to apps and websites with a biometric sensor (such as a fingerprint or facial recognition), PIN, or pattern, freeing them from having to remember and manage passwords.
The document describes how to build a cross-domain API called @anywhere that allows Twitter functionality to be embedded on third-party sites. It discusses using postMessage to enable cross-domain communication and implementing an RPC layer to wrap Twitter's REST API. It also covers how to handle authentication and authorization using OAuth, passing the access token back to the embedding page securely using the window.name polling technique. The goal is to provide a secure, frictionless, and unobtrusive way to access Twitter APIs from any domain.
Java Web Programming [9/9] : Web Application SecurityIMC Institute
This document provides an overview of web application security. It discusses general security issues like authentication, authorization, data integrity and confidentiality. It then describes different web-tier authentication schemes like BASIC, DIGEST, FORM and CLIENT-CERT. Finally, it covers declarative and programmatic authorization approaches for access control at the web-tier.
How to implement authorization in your backend with AWS IAMProvectus
AWS Dev Day Kyiv 2019
Track: Backend & Architecture
Session: ""How to implement authorization in your backend with AWS IAM""
Speaker: Stas Ivaschenko, AWS solutions architect at Provectus
Level: 400
Video: https://www.youtube.com/watch?v=4Jje_WJ4V7Q
AWS Dev Day is a free, full-day technical event where new developers will learn about some of the hottest topics in cloud computing, and experienced developers can dive deep on newer AWS services.
Provectus has organized AWS Dev Day Kyiv in close collaboration with Amazon Web Services: 800+ participants, 18 sessions, 3 tracks, a really AWSome Day!
Now, together with Zeo Alliance, we're building and nurturing AWS User Group Ukraine — join us on Facebook to stay updated about cloud technologies and AWS services: https://www.facebook.com/groups/AWSUserGroupUkraine
"
Securing your Pulsar Cluster with Vault_Chris KelloggStreamNative
Learn how to secure a Pulsar cluster with Hashicorp Vault and deploy it on Kubernetes. Vault provides a secure way to generate tokens and store sensitive data and Pulsar has a pluggable architecture for authentication, authorization and secret management. This talk will walk through how to create custom plugins for Vault, integrate them with Pulsar and then deploy a Pulsar cluster on Kubernetes.
Spring Security is a powerful and highly customizable authentication and authorization framework for Spring-based applications. It provides authentication via mechanisms like username/password, LDAP, and SSO. Authorization can be implemented through voting-based access control or expression-based access control at the web (URL) level and method level. It includes filters, providers, and services to handle authentication, authorization, logout, and remember-me functionality. Configuration can be done through XML or Java configuration with support for common annotations.
OAuth 2.0 – A standard is coming of age by Uwe FriedrichsenCodemotion
OAuth is a widespread web-based standard. It’s purpose is to provide safe inter-application access to web resources without having to reveal passwords or other sensible credentials across the wire or to third party applications. After lots of tough discussions for two and a half years version 2.0 of this standard has been released – finally.
This session gives you an introduction to OAuth 2.0. You will understand its concepts as well as its limitations and pitfalls. You will also learn how it feels to write your own OAuth 2.0 based application based on real-life code examples.
This document discusses OAuth2 and OpenID Connect for authentication. It begins by outlining goals of understanding OAuth, OpenID Connect concepts, and integrating them with Spring Security. It then explains key OAuth2 concepts like tokens, scopes, and flows. It describes OpenID Connect and how it builds on OAuth2 to provide authentication. It provides examples of configuring Spring Security for OAuth2 and OpenID Connect login, including registering a client and configuring the application.
This document discusses various techniques for managing state in ASP.NET applications, including client-side and server-side options. On the client side, it covers view state, control state, hidden fields, cookies, and query strings. On the server side, it discusses application state, session state, and profile properties. For each technique, it provides code samples and recommendations on when to use each option based on factors like security, performance, and data persistence. It aims to help developers choose the best state management approach for different situations.
Web authentication and authorization has come a long way in the last ten years. In this talk we'll look at where we've come from and how to OAuth and OIDC solved the problems we faced.
Similar to Sécurisation de vos applications web à l’aide du composant Security de Symfony (20)
SOLID : les principes à l’origine du succès de Symfony et de vos applicationsVladyslav Riabchenko
SOLID est un acronyme représentant cinq principes de bases de la programmation orientée objet permettant le développement de logiciels fiables, évolutifs et robustes. Le framework Symfony est un excellent support pour illustrer chacun de ces principes. Nous verrons ainsi que SOLID est à l’origine de sa flexibilité, sa fiabilité mais aussi de sa maintenabilité et son évolutivité. Nous verrons également comment appliquer ces principes pour améliorer son code métier et perfectionner l’architecture de son application.
Intervention sur le versionning sémantique et contraintes de versions dans composer.json pour la soirée de veille technologique à Webnet le 28/11/2017.
This document summarizes an presentation about dependency injection in Symfony 3.3 or greater. It discusses the service container and how it is used to instantiate services and inject their dependencies. It covers how to configure services and their dependencies, including using autowiring to simplify configuration. It also discusses autoconfiguring services as forms or commands. Finally, it presents options like _defaults and grouped declarations that can reduce configuration size.
Most important New features of Oracle 23c for DBAs and Developers. You can get more idea from my youtube channel video from https://youtu.be/XvL5WtaC20A
E-Invoicing Implementation: A Step-by-Step Guide for Saudi Arabian CompaniesQuickdice ERP
Explore the seamless transition to e-invoicing with this comprehensive guide tailored for Saudi Arabian businesses. Navigate the process effortlessly with step-by-step instructions designed to streamline implementation and enhance efficiency.
Project Management: The Role of Project Dashboards.pdfKarya Keeper
Project management is a crucial aspect of any organization, ensuring that projects are completed efficiently and effectively. One of the key tools used in project management is the project dashboard, which provides a comprehensive view of project progress and performance. In this article, we will explore the role of project dashboards in project management, highlighting their key features and benefits.
Hand Rolled Applicative User ValidationCode KataPhilip Schwarz
Could you use a simple piece of Scala validation code (granted, a very simplistic one too!) that you can rewrite, now and again, to refresh your basic understanding of Applicative operators <*>, <*, *>?
The goal is not to write perfect code showcasing validation, but rather, to provide a small, rough-and ready exercise to reinforce your muscle-memory.
Despite its grandiose-sounding title, this deck consists of just three slides showing the Scala 3 code to be rewritten whenever the details of the operators begin to fade away.
The code is my rough and ready translation of a Haskell user-validation program found in a book called Finding Success (and Failure) in Haskell - Fall in love with applicative functors.
Consistent toolbox talks are critical for maintaining workplace safety, as they provide regular opportunities to address specific hazards and reinforce safe practices.
These brief, focused sessions ensure that safety is a continual conversation rather than a one-time event, which helps keep safety protocols fresh in employees' minds. Studies have shown that shorter, more frequent training sessions are more effective for retention and behavior change compared to longer, infrequent sessions.
Engaging workers regularly, toolbox talks promote a culture of safety, empower employees to voice concerns, and ultimately reduce the likelihood of accidents and injuries on site.
The traditional method of conducting safety talks with paper documents and lengthy meetings is not only time-consuming but also less effective. Manual tracking of attendance and compliance is prone to errors and inconsistencies, leading to gaps in safety communication and potential non-compliance with OSHA regulations. Switching to a digital solution like Safelyio offers significant advantages.
Safelyio automates the delivery and documentation of safety talks, ensuring consistency and accessibility. The microlearning approach breaks down complex safety protocols into manageable, bite-sized pieces, making it easier for employees to absorb and retain information.
This method minimizes disruptions to work schedules, eliminates the hassle of paperwork, and ensures that all safety communications are tracked and recorded accurately. Ultimately, using a digital platform like Safelyio enhances engagement, compliance, and overall safety performance on site. https://safelyio.com/
Artificia Intellicence and XPath Extension FunctionsOctavian Nadolu
The purpose of this presentation is to provide an overview of how you can use AI from XSLT, XQuery, Schematron, or XML Refactoring operations, the potential benefits of using AI, and some of the challenges we face.
Microservice Teams - How the cloud changes the way we workSven Peters
A lot of technical challenges and complexity come with building a cloud-native and distributed architecture. The way we develop backend software has fundamentally changed in the last ten years. Managing a microservices architecture demands a lot of us to ensure observability and operational resiliency. But did you also change the way you run your development teams?
Sven will talk about Atlassian’s journey from a monolith to a multi-tenanted architecture and how it affected the way the engineering teams work. You will learn how we shifted to service ownership, moved to more autonomous teams (and its challenges), and established platform and enablement teams.
Preparing Non - Technical Founders for Engaging a Tech AgencyISH Technologies
Preparing non-technical founders before engaging a tech agency is crucial for the success of their projects. It starts with clearly defining their vision and goals, conducting thorough market research, and gaining a basic understanding of relevant technologies. Setting realistic expectations and preparing a detailed project brief are essential steps. Founders should select a tech agency with a proven track record and establish clear communication channels. Additionally, addressing legal and contractual considerations and planning for post-launch support are vital to ensure a smooth and successful collaboration. This preparation empowers non-technical founders to effectively communicate their needs and work seamlessly with their chosen tech agency.Visit our site to get more details about this. Contact us today www.ishtechnologies.com.au
UI5con 2024 - Bring Your Own Design SystemPeter Muessig
How do you combine the OpenUI5/SAPUI5 programming model with a design system that makes its controls available as Web Components? Since OpenUI5/SAPUI5 1.120, the framework supports the integration of any Web Components. This makes it possible, for example, to natively embed own Web Components of your design system which are created with Stencil. The integration embeds the Web Components in a way that they can be used naturally in XMLViews, like with standard UI5 controls, and can be bound with data binding. Learn how you can also make use of the Web Components base class in OpenUI5/SAPUI5 to also integrate your Web Components and get inspired by the solution to generate a custom UI5 library providing the Web Components control wrappers for the native ones.
Malibou Pitch Deck For Its €3M Seed Roundsjcobrien
French start-up Malibou raised a €3 million Seed Round to develop its payroll and human resources
management platform for VSEs and SMEs. The financing round was led by investors Breega, Y Combinator, and FCVC.
3. Symfony 3
1. Symfony
2. Authentification artisanale
3. Firewall
4. Token anonyme
5. User provider
6. Authentication provider
7. HTTP Basic
8. Formulaire de connexion
Plan
4. Symfony 4
Authentification est un processus permettant à l’application de s’assurer que la requête
a été faite par un utilisateur légitime.
C’est une confirmation de son identité grâce à des identifiants.
Identification est une sélection d’utilisateur grâce à son identifiant.
Autorisation est une vérification des droits d’accès d’un utilisateur sur une ressource en
se basant sur une politique d’accès.
5. Auth simple 5
Authentifier chaque requête à l’application à l’aide d’un identifiant et d’un
mot de passe.Tâche 1
Front controller
Token
public/index.php reçoit toutes les requêtes client quelque soit le
path et les paramètres
HttpFoundation
Composant de Symfony qui fournit la couche orientée-objet pour
HTTP : Request, Response, Session, etc.
Conserve des données sur l’utilisateur :
• Objet d’utilisateur
• Username
• Credentials
• Roles
• Authentifié ou pas
6. SymfonyComponentSecurityCoreAuthenticationToken
6
Security listeners
Token Conserve des données sur l’utilisateur
+ getUser()
+ getUsername()
+ getCredentials()
+ isAuthenticated()
+ getRoles()
TokenInterface
+ getProviderKey()
UsernamePasswordToken
+ getSecret()
AnonymousToken
Listeners qui extraient les identifiants et les vérifient.
Ils créent ensuite un Token puis le stockent dans le Token storage.
Token storage Objet/service qui contient un Token
Auth simple
7. 7
// public/index.php
use SymfonyComponentHttpFoundationRequest;
use SymfonyComponentSecurityCoreAuthenticationTokenStorageTokenStorage;
use SymfonyComponentHttpFoundationResponse;
$request = Request::createFromGlobals(); // HTTP request
$tokenStorage = new TokenStorage(); // Service that stores user token
// Call security listener on every request.
$securityListener = new AppSecuritySecurityListener($tokenStorage);
$securityListener->onRequest($request);
// Any code you can imagine to generate a response.
// You can deny access if no token were set.
$token = $tokenStorage->getToken();
$response = new Response(
'Request uri: '.$request->getRequestUri().'<br>'
.'Token: '.(is_object($token) ? get_class($token) : gettype($token)).'<br>'
.'Username: '.($token ? $token->getUsername(): 'NULL')
);
$response->send(); // Send response
Auth simple
8. 8
use SymfonyComponentHttpFoundationRequest;
use SymfonyComponentSecurityCoreAuthenticationTokenStorageTokenStorageInterface;
use SymfonyComponentSecurityCoreAuthenticationTokenUsernamePasswordToken;
class SecurityListener
{
private $tokenStorage;
public function __construct(TokenStorageInterface $tokenStorage)
{
$this->tokenStorage = $tokenStorage;
}
public function onRequest(Request $request)
{
$user = $request->query->get('auth_user');
$password = $request->query->get('auth_pw');
if ($user === 'vlad' && $password === 'pass') {
// Credentials are valid.
// Create a token with user object, credentials, provider key and roles
$token = new UsernamePasswordToken($user, $password, 'main', ['ROLE_USER']);
// Save it to token storage
$this->tokenStorage->setToken($token);
}
}
}
Auth simple
9. Firewall 9
Centraliser l’authentification dans un firewall afin de pouvoir utiliser
plusieurs systèmes d’authentification.Tâche 2
HttpKernel
Le composant de Symfony qui fournit un processus structuré pour
convertir Request en Response en utilisant EventDispatcher.
EventDispatcher
Le composant de Symfony qui permet aux composants de
communiquer entre eux à l’aide d’événements.
Request ResponseResolve controller Execute controller
EXCEPTIONEvent Dispatcher
10. // public/index.php
use SymfonyComponentEventDispatcherEventDispatcher;
use SymfonyComponentHttpFoundationRequest;
use SymfonyComponentHttpKernelHttpKernel;
use SymfonyComponentSecurityCoreAuthenticationTokenStorageTokenStorage;
$request = Request::createFromGlobals(); // HTTP request.
$tokenStorage = new TokenStorage(); // Service that stores user token.
$dispatcher = new EventDispatcher();
// Controller creates a response to send to the user.
$controller = new AppController($request, $tokenStorage);
$controllerResolver = new AppControllerResolver([$controller, 'defaultAction']);
// kernel is in charge of converting a Request into a Response by using the event dispatcher.
$kernel = new HttpKernel($dispatcher, $controllerResolver);
// We will add security listeners to dispatcher in few minutes.
$response = $kernel->handle($request);
$response->send();
10Firewall
Le Front controller crée $kernel et lui demande de traiter la requête.
11. 11
Kernel demande à ControllerResolver de renvoyer le contrôleur en fonction de la
requête. C’est l’emplacement idéal pour la logique de Routing.
use SymfonyComponentHttpFoundationRequest;
use SymfonyComponentHttpKernelControllerControllerResolverInterface;
class ControllerResolver implements ControllerResolverInterface
{
/** @var callable */
private $default;
public function __construct(callable $default)
{
$this->default = $default;
}
public function getController(Request $request)
{
return $this->default;
}
}
Firewall
12. 12
class Controller
{
/** @var Request */
private $request;
/** @var TokenStorageInterface */
private $tokenStorage;
public function defaultAction()
{
$token = $this->tokenStorage->getToken();
return new Response(
'Request uri: '.$this->request->getRequestUri().'<br>'
.'Token: '.(is_object($token) ? get_class($token) : gettype($token)).'<br>'
.'Username: '.($token ? $token->getUsername(): 'NULL')
);
}
}
La méthode Controller::defaultAction est un contrôleur qui sera exécuté par Kernel.
Firewall
13. SymfonyComponentSecurityHttp
13
- map: array
+ getListeners(Request $request)
Firewall
- map: FirewallMap
+ onKernelRequest(GetResponseEvent $event)
FirewallMap
RequestMatcher
- path: string
=>
][
Le firewall est un listener de l’événement
REQUEST.
Il permet d’implémenter des stratégies
d’authentification en fonction de la
requête.
FirewallMap renvoie les listeners
configurés pour le requête spécifique.
ListenerInterface
+ handle(GetResponseEvent $event) , …
Firewall
14. 14
RequestMatcher
- path = ^/back
- ips = [192.0.0.4]
=>
][ BasicAuthenticationListener
RequestMatcher
- path: ^/customer
=>
][ ContextListener
,
SimpleFormAuthenticationListener
RequestMatcher =>
][AnonymousAuthenticationListener
Utiliser l’authentification HTTP basic pour toutes les requêtes qui commencent par /back
Authentifier les requêtes qui commencent par /customer à l’aide d’un formulaire classique
Authentifier toutes les autres requêtes comme anonymes
Firewall
15. 15
// public/index.php
use SymfonyComponentHttpFoundationRequestMatcher;
use SymfonyComponentSecurityHttpFirewall;
use SymfonyComponentSecurityHttpFirewallMap;
// ...
// Create main security listener that handles authentication.
$securityListener = new AppSecurityMainSecurityListener($tokenStorage);
// Create firewall map and add main security listener under URLs starting with "/main".
$firewallMap = new FirewallMap();
$firewallMap->add(new RequestMatcher('^/main'), [$securityListener]);
// Create firewall and add it to dispatcher.
$firewall = new Firewall($firewallMap, $dispatcher);
$dispatcher->addSubscriber($firewall);
// ...
Firewall attends l’événement REQUEST pour exécuter MainSecurityListener si le path de
la requête commence par /main.
Firewall
16. 16
use SymfonyComponentHttpKernelEventGetResponseEvent;
use SymfonyComponentSecurityCoreAuthenticationTokenStorageTokenStorageInterface;
use SymfonyComponentSecurityCoreAuthenticationTokenUsernamePasswordToken;
use SymfonyComponentSecurityHttpFirewallListenerInterface;
class MainSecurityListener implements ListenerInterface
{
/** @var TokenStorageInterface */
private $tokenStorage;
public function handle(GetResponseEvent $event)
{
$request = $event->getRequest();
$user = $request->query->get('auth_user');
$password = $request->query->get('auth_pw');
if ($user === 'vlad' && $password === 'pass') {
$token = new UsernamePasswordToken($user, $password, 'main', ['ROLE_USER']);
$this->tokenStorage->setToken($token);
}
}
}
MainSecurityListener implémente désormais ListenerInterface.
Firewall
17. App
SymfonyComponentSecurityHttpFirewall
anon. 17
Permettre aux utilisateurs de s’authentifier comme des anonymes.Tâche 3
RequestMatcher
- path = ^/main =>
][
MainSecurityListener
AnonymousAuthenticationListener
// public/index.php
use SymfonyComponentHttpFoundationRequestMatcher;
use SymfonyComponentSecurityHttpFirewallMap;
use SymfonyComponentSecurityHttpFirewallAnonymousAuthenticationListener;
// ...
// Create a security listener that adds anonymous token if none is already present.
$anonListener = new AnonymousAuthenticationListener($tokenStorage, 'secret');
// Create firewall map and add main security listener under URLs starting with "/main".
$firewallMap = new FirewallMap();
$firewallMap->add(new RequestMatcher('^/main'), [$securityListener, $anonListener]);
18. User provider 18
Abstraire le moyen de récupération des utilisateurs et déplacer cette logique
en dehors des security listeners.Tâche 4
SymfonyComponentSecurityCoreUser
UserProviderInterface
+ loadUserByUsername($username): UserInterface
+ refreshUser(UserInterface $user)
+ supportsClass($class)
Security Listener
- userProvider
+ loadUserByUsername($username):User
UserInterface
+ getUsername()
+ getRoles()
+ getPassword()
+ getSalt()
+ eraseCredentials()
+ isEnabled()
UserInMemoryUserProvider
19. 19
use SymfonyComponentHttpKernelEventGetResponseEvent;
use SymfonyComponentSecurityCoreAuthenticationTokenUsernamePasswordToken;
use SymfonyComponentSecurityCoreExceptionUsernameNotFoundException;
use SymfonyComponentSecurityCoreUserUserProviderInterface;
use SymfonyComponentSecurityHttpFirewallListenerInterface;
class MainSecurityListener implements ListenerInterface
{
/** @var UserProviderInterface */
private $userProvider;
public function handle(GetResponseEvent $event)
{
$request = $event->getRequest();
$username = $request->query->get('auth_user');
$password = $request->query->get('auth_pw');
try {
$user = $this->userProvider->loadUserByUsername($username);
if ($user->getPassword() === $password) {
$token = new UsernamePasswordToken($user, $password, 'main', $user->getRoles());
$this->tokenStorage->setToken($token);
}
} catch (UsernameNotFoundException $e) {
}
}
}
User provider
20. 20
// public/index.php
use SymfonyComponentEventDispatcherEventDispatcher;
use SymfonyComponentHttpFoundationRequestMatcher;
use SymfonyComponentSecurityHttpFirewallMap;
use SymfonyComponentSecurityHttpFirewall;
use SymfonyComponentSecurityCoreUserInMemoryUserProvider;
// ...
// Create user provider that will be used by authentication listener.
$mainUserProvider = new InMemoryUserProvider([
'vlad' => ['password' => 'pass', 'roles' => ['ROLE_USER’]],
]);
// Create main security listener that handles authentication.
$mainSecurityListener = new AppSecurityMainSecurityListener($tokenStorage, $mainUserProvider);
// Create firewall map and add main security listener under URLs starting with "/main".
$firewallMap = new FirewallMap();
$firewallMap->add(new RequestMatcher('^/main'), [$mainSecurityListener, $anonListener]);
// ...
User provider
Création d’un user provider pour main security listener.
21. App
21Auth provider
Ajouter l’encodage du mot de passe, n’accepter que des utilisateurs activés.
Déplacer la logique d’authentification en dehors des security listeners.Tâche 5
- tokenStorage
- authenticationManager
SymfonyComponentSecurityCoreAuthentication
AuthenticationManagerInterface
+ authenticate(TokenInterface $token)
MainSecurityListener
̶ Être rappelé par Firewall pendant l’événement
REQUEST
̶ Extraire l’identifiant et le mot de passe
̶ Créer le token non authentifié
̶ Passer le token à l’authentification manager
̶ Mettre le token authentifié dans le token storage
̶ Récupérer l’utilisateur grâce à l’identifiant et à
l’aide de user provider
̶ Vérifier le mot de passe à l’aide de password
encoder
̶ Vérifier les autres paramètres
̶ Renvoyer le token authentifié
$token->setAuthenticated(true)
créer un nouveau token
25. 25Auth provider
use SymfonyComponentSecurityCoreAuthenticationAuthenticationManagerInterface;
use SymfonyComponentSecurityCoreAuthenticationTokenUsernamePasswordToken;
use SymfonyComponentSecurityCoreExceptionAuthenticationException;
class MainSecurityListener implements ListenerInterface
{
/** @var AuthenticationManagerInterface */
private $authenticationManager;
public function handle(GetResponseEvent $event)
{
// Extract authentication credentials.
if ($username && $credentials) {
try {
// Token is not authenticated because no role is passed.
$token = new UsernamePasswordToken($username, $credentials, 'main');
// Try to authenticate the token.
// If there is an authentication error an AuthenticationException is thrown.
$token = $this->authenticationManager->authenticate($token);
// Add authenticated token to storage.
$this->tokenStorage->setToken($token);
} catch (AuthenticationException $e) {}
}
}
}
26. 26Auth provider
use SymfonyComponentSecurityCoreAuthenticationProviderDaoAuthenticationProvider;
use SymfonyComponentSecurityCoreEncoderBCryptPasswordEncoder;
// Create user provider that will be used by authentication listener.
$mainUserProvider = new InMemoryUserProvider([
'vlad' => [
'password' => '$2y$10$zDUW3BF4T5ZVloDZqp0SN.1Ic4DG3xfxHUDXWkkpvaP0G8qXnq', // encoded 'pass'
'roles' => ['ROLE_USER'],
'enabled' => true
]
]);
// And object that checks whether a user is non-locked, enabled, not expired, etc.
$mainUserChecker = new SymfonyComponentSecurityCoreUserUserChecker();
// A factory that specifies encoding algorithm to each user class.
$encoderFactory = new SymfonyComponentSecurityCoreEncoderEncoderFactory([
SymfonyComponentSecurityCoreUserUser::class => new BCryptPasswordEncoder(10)
]);
// Create a provider to which security listener will delegate an authentication.
$mainAuthProvider = new DaoAuthenticationProvider(
$mainUserProvider, $mainUserChecker, 'main', $encoderFactory
);
// Create main security listener that handles authentication.
$mainSecurityListener = new AppSecurityMainSecurityListener($tokenStorage, $mainAuthProvider);
27. 27HTTP basic auth
Mettre en place l’authentification HTTP, laisser passer seulement les
utilisateurs connectés.Tâche 6
SymfonyComponentSecurityHttpFirewall
- tokenStorage
- authenticationManager
BasicAuthenticationListener
- tokenStorage
- accessDecisionManager
AccessListener
RequestMatcher
- path: ^/main
=>
Extraire l’identifiant et le mot de
passe de l'en-tête Authorization.
Créer le token, l'authentifier, le
sauvegarder dans token storage.
Lancer une exception si les
credentials ne sont pas valides. Lancer une exception si le token
n’est pas présent ou s’il ne
respecte pas les règles d’accès.
28. 28
SymfonyComponentSecurityHttpEntryPoint
+ start(Request $request, $authException): Response
AuthenticationEntryPointInterface
- realmName: string
BasicAuthenticationEntryPoint
Lors de l'exception d’authentification (accès anonyme ou identifiants non valides) il faut
aider l’utilisateur à (re-)commencer l’authentification.
SymfonyComponentSecurityHttpFirewall
- tokenStorage
- authenticationManager
- authenticationEntryPoint
BasicAuthenticationListener
Event Dispatcher
- Kernel::EXCEPTION => [...]
- authenticationEntryPoint
ExceptionListener
HTTP basic auth
29. 29
use SymfonyComponentHttpFoundationRequestMatcher;
use SymfonyComponentSecurityHttpAccessMap;
use SymfonyComponentSecurityHttpFirewallMap;
use SymfonyComponentSecurityHttpFirewallBasicAuthenticationListener;
use SymfonyComponentSecurityHttpFirewallAccessListener;
use SymfonyComponentSecurityHttpEntryPointBasicAuthenticationEntryPoint;
use SymfonyComponentSecurityCoreAuthorizationAccessDecisionManager;
// Entry point helps user to authenticate.
$basicAuthenticationEntryPoint = new BasicAuthenticationEntryPoint('Secured area');
// Create HTTP basic security listener that extracts credentials from headers (RFC 7617).
$mainSecurityListener = new BasicAuthenticationListener(
$tokenStorage, $mainAuthProvider, 'main', $basicAuthenticationEntryPoint
);
// Access listener will throw an exception when no token is already present.
$accessDecisionManager = new AccessDecisionManager();
$accessMap = new AccessMap();
$accessListener = new AccessListener(
$tokenStorage, $accessDecisionManager, $accessMap, $mainAuthProvider
);
// Create firewall map and add main security listener under URLs starting with "/main".
$firewallMap = new FirewallMap();
$firewallMap->add(new RequestMatcher('^/main'), [$mainSecurityListener, $accessListener]);
// ...
HTTP basic auth
30. 30
use SymfonyComponentSecurityHttpHttpUtils;
use SymfonyComponentSecurityCoreAuthenticationAuthenticationTrustResolver;
use SymfonyComponentSecurityCoreAuthenticationTokenAnonymousToken;
use SymfonyComponentSecurityCoreAuthenticationTokenRememberMeToken;
use SymfonyComponentHttpKernelKernelEvents;
// ...
// ExceptionListener catches authentication exception and converts them to Response instance.
// In this case it invites user to enter its credentials by returning 401 response.
$authTrustResolver = new AuthenticationTrustResolver(AnonymousToken::class, RememberMeToken::class);
$httpUtils = new HttpUtils();
$exceptionListener = new ExceptionListener(
$tokenStorage, $authTrustResolver, $httpUtils, 'main', $basicAuthenticationEntryPoint
);
$dispatcher->addListener(KernelEvents::EXCEPTION, array($exceptionListener, 'onKernelException'), 1);
// ...
HTTP basic auth
31. 31Formulaire de connexion
Mettre en place l’authentification par le formulaire de connexion pour une
autre partie de site.Tâche 7
SymfonyComponentSecurityHttpFirewall
- tokenStorage
- userProviders
ContextListener
- tokenStorage
- accessDecisionManager
- options
- successHandler
- failureHandler
UsernamePasswordFormAuthenticationListener
RequestMatcher
- path: ^/front
=>
+ handle(GetResponseEvent $event)
+ onKernelResponse(FilterResponseEvent $event)
+ handle(GetResponseEvent $event)
Récupérer le token d’une session
lors de l’événement REQUEST.
Sauvegarder le token dans une
session lors de l’événement
RESPONSE.
Authentifier l’utilisateur
seulement quand le formulaire de
connexion est envoyé
(POST sur /front/login_check).
32. 32Formulaire de connexion
use SymfonyComponentHttpFoundationResponse;
class Controller
{
public function loginFormAction()
{
return new Response(<<<END
<form action="/front/login_check" method="POST">
<input type="text" name="_username" placeholder="username">
<input type="password" name="_password" placeholder="password">
<input type="submit">
</form>
END
);
}
public function defaultAction()
{
$token = $this->tokenStorage->getToken();
$user = $token ? $token->getUser() : null;
// ...
}
}
Nouvelle action pour visualiser le formulaire de conexion : POST sur /front/login_check.
33. 33Formulaire de connexion
use SymfonyComponentHttpFoundationRequest;
use SymfonyComponentHttpKernelControllerControllerResolverInterface;
class ControllerResolver implements ControllerResolverInterface
{
/** @var callable[] */
private $routes;
/** @var callable */
private $default;
public function getController(Request $request)
{
foreach ($this->routes as $pattern => $controller) {
if (preg_match($pattern, $request->getPathInfo())) {
return $controller;
}
}
return $this->default;
}
}
La nouvelle action sera appelée quand la requête est faite sur /font/login.
34. 34Formulaire de connexion
// public/index.php
use SymfonyComponentEventDispatcherEventDispatcher;
use SymfonyComponentHttpKernelHttpKernel;
// ...
// Controller creates a response to send to the user.
$controller = new AppController($request, $tokenStorage);
$controllerResolver = new AppControllerResolver(
['/^/front/login$/' => [$controller, 'loginFormAction']],
[$controller, 'defaultAction']
);
// Kernel is in charge of converting a Request into a Response by using the event dispatcher.
$kernel = new HttpKernel($dispatcher, $controllerResolver);
// ...
La nouvelle action sera appelée quand la requête est faite sur /font/login.
35. 35Formulaire de connexion
// public/index.php
use SymfonyComponentSecurityHttpFirewallContextListener;
// ...
// ContextListener retrieves previously authenticated token from the session during REQUEST event.
// It also saves token during RESPONSE event.
$contextListener = new ContextListener(
$tokenStorage, [$mainUserProvider], 'front', null, $dispatcher
);
// ...
Context security listener :
36. 36Formulaire de connexion
use SymfonyComponentSecurityHttpAuthenticationDefaultAuthenticationSuccessHandler;
use SymfonyComponentSecurityHttpAuthentication DefaultAuthenticationFailureHandler;
use SymfonyComponentSecurityHttpFirewallUsernamePasswordFormAuthenticationListener;
use SymfonyComponentSecurityHttpSessionSessionAuthenticationStrategy;
$sessionAuthenticationStrategy = new SessionAuthenticationStrategy(SessionAuthenticationStrategy::MIGRATE);
$successHandler = new DefaultAuthenticationSuccessHandler(
$httpUtils, ['default_target_path' => '/front/success’]
);
$failureHandler = new DefaultAuthenticationFailureHandler(
$kernel, $httpUtils, ['login_path' => '/front/login’]
);
// Listens for login form being send (POST to '/front/login_check').
// It extracts credentials, creates token, authenticates it and puts it to the token storage.
$formAuthListener = new UsernamePasswordFormAuthenticationListener(
$tokenStorage,
$frontAuthProvider,
$sessionAuthenticationStrategy,
$httpUtils,
'front',
$successHandler, // Redirect user to '/front/success' if credentials are valid
$failureHandler, // Redirect user to '/front/login' if credentials are invalid
['check_path' => '/front/login_check’, 'post_only' => true] // Act only on POST to '/front/login_check'
);
37. 37Formulaire de connexion
// public/index.php
use SymfonyComponentHttpFoundationRequestMatcher;
use SymfonyComponentSecurityHttpFirewallMap;
// ...
$firewallMap = new FirewallMap();
$firewallMap->add(new RequestMatcher('^/main'), [$mainSecurityListener, $accessListener]);
$firewallMap->add(new RequestMatcher('^/front'), [$contextListener, $formAuthListener]);
// ...
Ajout de security listeners dans le Firewall :
38. Merci pour votre attention
Le code de cette présentation :
https://github.com/vria/symfony-security-component-use