SlideShare una empresa de Scribd logo
deSymfony 30 junio - 1 julio 2017
Castellón
ASEGURANDO APIS
EN SYMFONY CON JWT
Nacho Martín
deSymfony
¡Muchas gracias a nuestros
patrocinadores!
Programo en Limenius
Casi todos los proyectos
necesitan una API
Hacemos aplicaciones a medida
con Symfony y React
JWT es una buena herramienta
para asegurarlas
Por qué es esto necesario
Por qué es esto necesario
¿Por qué no está todo inventado?
Asegurando APIs en Symfony con JWT
Esta charla va de alivios
Esta charla va de alivios
Autenticación con Cookies
Cliente
(navegador)
Servidor
BD
POST /login_check
username: "nacho",
password: "patata"
Autenticación con Cookies
Cliente
(navegador)
Servidor
BD
Obtiene usuario
Verifica credenciales
Guarda sesión
Autenticación con Cookies
Cliente
(navegador)
Servidor
BD
Envía cookie
al cliente
Set-Cookie: PHPSESSIONID=HOLA…
Autenticación con Cookies
Cliente
(navegador)
Servidor
BD
Usa cookie para
identificarse
Cookie: PHPSESSIONID=HOLA
Problemas con Cookies
Problemas con CORS
Implementación no natural en algunos clientes
Hay que protegerse contra CSRF
Requiere una gestión de sesión y pensar en cómo escalar
Mantienen un estado (sesión)
Estado en REST
[…] communication must be stateless in nature, […], such that
each request from client to server must contain all of the
information necessary to understand the request, and
cannot take advantage of any stored context on the
server. Session state is therefore kept entirely on the client.
Cómo siempre, hay razones
Requiere una gestión de sesión, y pensar en cómo escalar
¿Qué hacer con un balanceador de carga?
¿Dónde guardar las sesiones?
Asegurando APIs en Symfony con JWT
Alternativas para APIs
Asegurando APIs en Symfony con JWT
Junio 2012
JSON Web Tokens (JWT)
JOSE
JSON Object Signing and Encryption
{
JWT
JWA
JWS
JWE
JWK
JOSE
JSON Object Signing and Encryption
{
JWT
JWA
JWS
JWE
JWK
JWT solo es un formato de tokens
Pero muchas veces decimos “usar JWT”
Para referirnos a una forma de trabajar con ellos
https://www.flickr.com/photos/tokencompany/8073379662
Autenticación con JWT
Cliente
(navegador)
Servidor
BD
POST /login_check
username: "nacho",
password: "patata"
Autenticación con JWT
Cliente
(navegador)
Servidor
BD
Obtiene usuario
Verifica credenciales
Guarda sesión?
Autenticación con JWT
Cliente
(navegador)
Servidor
BD
Envía token
al cliente
{“token”:"tomaUnToken"}
Autenticación con JWT
Cliente
(navegador)
Servidor
BD
Usa token para
identificarse
Authorization: Bearer tomaUnToken
Uso en JavaScript
fetch(baseUrl + '/admin/api/recipes', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Bearer '+token,
},
body: JSON.stringify( data )
})
Almacenamiento en JavaScript
window.localStorage.setItem('access_token', token)
window.localStorage.getItem('access_token')
Almacenamiento en JavaScript
window.localStorage.setItem('access_token', token)
window.localStorage.getItem('access_token')
Ya no tenemos CSRF, ahora ojo con ataques XSS
El famoso token
eyJhbGciOiJSUzI1NiJ9.eyJyb2xlcyI6WyJST0xFX1VTRVIiXSwid
XNlcm5hbWUiOiJuYWNobyIsImlhdCI6MTQ5ODE0MjA3Niw
iZXhwIjoxNDk4MTQ1Njc2fQ
eyJhbGciOiJSUzI1NiJ9.eyJyb2xlcyI6WyJST0xFX1VTRVIiXSwid
XNlcm5hbWUiOiJuYWNobyIsImlhdCI6MTQ5ODE0MjA3Niw
iZXhwIjoxNDk4MTQ1Njc2fQ
El famoso token
eyJhbGciOiJSUzI1NiJ9.eyJyb2xlcyI6WyJST0xFX1VTRVIiXSwid
XNlcm5hbWUiOiJuYWNobyIsImlhdCI6MTQ5ODE0MjA3Niw
iZXhwIjoxNDk4MTQ1Njc2fQ
Hay un punto
El famoso token
El famoso token
eyJhbGciOiJSUzI1NiJ9.eyJyb2xlcyI6WyJST0xFX1VTRVIiXSwid
XNlcm5hbWUiOiJuYWNobyIsImlhdCI6MTQ5ODE0MjA3Niw
iZXhwIjoxNDk4MTQ1Njc2fQ
El famoso token
eyJhbGciOiJSUzI1NiJ9.eyJyb2xlcyI6WyJST0xFX1VTRVIiXSwid
XNlcm5hbWUiOiJuYWNobyIsImlhdCI6MTQ5ODE0MjA3Niw
iZXhwIjoxNDk4MTQ1Njc2fQ
{“alg":"none"}
{
“username":"nacho",
“iat":1498142076,
“exp”:1498145676
}
Base64Url
eyJhbGciOiJSUzI1NiJ9{“alg":"none"}
No está cifrado (todos lo pueden leer)
Solo está codificado
Esto solo sirve para que pueda viajar en URLs
Y en cualquier sitio donde puedan viajar strings
Base64Url
{
“username":"nacho",
“iat":1498142076,
“exp”:1498145676
}
¿Me puedo fiar de esto?
Base64Url
{
“username":"nacho",
“iat":1498142076,
“exp”:1498145676
}
¿Me puedo fiar de esto?
El token completo
eyJhbGciOiJSUzI1NiJ9.eyJyb2xlcyI6WyJST0xFX1VTRVIiXSwidXNlcm5hbWUiOiJuYWNobyIsImlhdCI6MTQ5ODE0MjA3NiwiZXh
wIjoxNDk4MTQ1Njc2fQ.jomtnO16Tik6jxU_0HmsXFxbUSyBoNTu8RVSbQ9jEKUfYEFTG8QZrsSpNl5uzlXf-
hP2zx1YmPTow1jXGyoFjV6Nk1e7pFlw2s8fSrIZpT2ZFBuVPefKhSWXYoSUHGZWtMFMU-
yghnWA6tlFD5UcJiDQ3ZlUCbLxOlDdygUoC841aR9R87otefdQUEKY_faGq1Tl-
KxJfjndG4HENgC7M52JaX5xFKmOlI1mKXqDvVOrCTil3yOcqxQv94SZjqhG5V7NLaaslMDXVl4fzJC-
WWE_Eo0xzfOSxMAZ7NBEvha207pjl8FAszQDZ0uuqxfPLqb4QnpALnFAGip4hlu28wRccAsWJQ6uSYtClrE9Kwt7Vlo4PrPX3zqMb
_YaRI1QUco6qjj2AsCf18-0f5XvgqrwSoU_73w4pgsj7rUyft9mwe3tiUYCoUP_dKFJfcz_ofHScpsWfFJ4lD4TIzpKf1LfLFwRUcpQuJdR
K8-1C_x5dJILrO2fSKZbxFCq_-
zB2UHmbH8eFQQYxIpS4eDjFDZTeFLOzruapM10taDQ8buGOyVUx9vwTJoWq9dFuqVAdhFc9h6iXNy0QzI46uvN-
en1n6KVsKTfaLecvCYhIIt32Z5mYD3YgDEeRnLZ5TIgykiVNL9SZCGphzv6h5MEs_xQyDo6XOsu92tPtbqyvI4
El token completo
eyJhbGciOiJSUzI1NiJ9.eyJyb2xlcyI6WyJST0xFX1VTRVIiXSwidXNlcm5hbWUiOiJuYWNobyIsImlhdCI6MTQ5ODE0MjA3NiwiZXh
wIjoxNDk4MTQ1Njc2fQ.jomtnO16Tik6jxU_0HmsXFxbUSyBoNTu8RVSbQ9jEKUfYEFTG8QZrsSpNl5uzlXf-
hP2zx1YmPTow1jXGyoFjV6Nk1e7pFlw2s8fSrIZpT2ZFBuVPefKhSWXYoSUHGZWtMFMU-
yghnWA6tlFD5UcJiDQ3ZlUCbLxOlDdygUoC841aR9R87otefdQUEKY_faGq1Tl-
KxJfjndG4HENgC7M52JaX5xFKmOlI1mKXqDvVOrCTil3yOcqxQv94SZjqhG5V7NLaaslMDXVl4fzJC-
WWE_Eo0xzfOSxMAZ7NBEvha207pjl8FAszQDZ0uuqxfPLqb4QnpALnFAGip4hlu28wRccAsWJQ6uSYtClrE9Kwt7Vlo4PrPX3zqMb
_YaRI1QUco6qjj2AsCf18-0f5XvgqrwSoU_73w4pgsj7rUyft9mwe3tiUYCoUP_dKFJfcz_ofHScpsWfFJ4lD4TIzpKf1LfLFwRUcpQuJdR
K8-1C_x5dJILrO2fSKZbxFCq_-
zB2UHmbH8eFQQYxIpS4eDjFDZTeFLOzruapM10taDQ8buGOyVUx9vwTJoWq9dFuqVAdhFc9h6iXNy0QzI46uvN-
en1n6KVsKTfaLecvCYhIIt32Z5mYD3YgDEeRnLZ5TIgykiVNL9SZCGphzv6h5MEs_xQyDo6XOsu92tPtbqyvI4
header.claims.signature
Pero sí está firmado (los intermediarios no lo
pueden modificar sin que nos enteremos)
No está cifrado
Header
{
“typ”:”JWT”,
“alg”:”RS256”
}
Header
{
“typ”:”JWT”,
“alg”:”RS256”
}
Tipo de token
Header
{
“typ”:”JWT”,
“alg”:”RS256”
}
Tipo de token
Algoritmo de hashing
¿Qué algoritmo usar?
JWA (rfc7518)
Diferencia simétrico/asimétrico
Simétrico: usamos la misma clave para firmar y validar.
Asimétrico: usamos distintas claves para firmar y validar.
RS256
RS384
RS512
Algoritmos
HS256
HS384
HS512
ES256
ES384
ES512
HMAC ECDSA RSA
PS256
PS384
PS348
RSASSA-PSS
none
RS256
RS384
RS512
Algoritmos
HS256
HS384
HS512
ES256
ES384
ES512
HMAC ECDSA RSA
PS256
PS384
PS348
RSASSA-PSS
none
Simétrico
RS256
RS384
RS512
Algoritmos
HS256
HS384
HS512
ES256
ES384
ES512
HMAC ECDSA RSA
PS256
PS384
PS348
RSASSA-PSS
none
Simétrico Asimétricos
RS256
RS384
RS512
Algoritmos
HS256
HS384
HS512
ES256
ES384
ES512
HMAC ECDSA
RS256
RS384
RS512
RSA
PS256
PS384
PS348
RSASSA-PSS
none
Simétrico Asimétricos
Claims
{
“username":"nacho",
“iat":1498142076,
“exp”:1498145676
}
Registered claims
jti
iss
aud
sub
iat
exp
nbf
Id del token: String
Issuer (emisor): StringOrUri
Audiencia: StringOrUri
Subject (tema): StringOrUri
Cuándo se creó: NumericDate
Cuándo expira: NumericDate
Tiempo hasta válidez: NumericDate
Custom claims
{
“username":"nacho",
“iat":1498142076,
“exp”:1498145676
}
Podemos añadir lo que queramos.
Solo hay que tener en cuenta:
Ser conciso.
Los datos no van cifrados (el cliente los ve).
Firma
Signature = algoritmo(payload, key)
Payload = Base64URL(headers)
+ ”.”
+ Base64URL(claims)
JWS (rfc7515)
JWT.IO
Importante: Usar TLS (“SSL”)
Ventajas de JWT
Caso: Mi app en JavaScript se ve distinta
dependiendo del rol del usuario
Con Cookies
Cliente Servidor
BD
Cookie: PHPSESSIONID=HOLA
Con Cookies
Cliente Servidor
BD
Cookie: PHPSESSIONID=HOLA
Tengo una cookie pero
no sé qué usuario soy
ni qué permisos tengo
Con Cookies
Cliente Servidor
BD
Cookie: PHPSESSIONID=HOLA
Con Cookies
Cliente Servidor
BD
Cookie: PHPSESSIONID=HOLA
Obtener usuario
Con Cookies
Cliente Servidor
BD
Cookie: PHPSESSIONID=HOLA
Obtener usuario
Con Cookies
Cliente Servidor
BD
Cookie: PHPSESSIONID=HOLA
Obtener usuario
Con Cookies
Cliente Servidor
BD
Cookie: PHPSESSIONID=HOLA
Obtener usuario
Con Cookies
Cliente Servidor
BD
Cookie: PHPSESSIONID=HOLA
Obtener usuario
Y ahora mostramos
Con JWT
Cliente Servidor
BD
Token: ejh9…
Con JWT
Cliente Servidor
BD
Token: ejh9…
{
“username":"nacho",
“iat":1498142076,
“exp”:1498145676
}
Con JWT
Cliente Servidor
BD
Token: ejh9…
{
“username":"nacho",
“iat":1498142076,
“exp”:1498145676
}
Tenemos todos los datos
Con JWT
Cliente
Token: ejh9…
{
“username":"nacho",
“iat":1498142076,
“exp”:1498145676
}
Tenemos todos los datos
Microservicios
Auth
Clave privada y pública
Consulta
Clave pública
Cliente
Clave pública
Pedidos
Clave pública
Microservicios
Auth
Clave privada y pública
Consulta
Clave pública
Cliente
Clave pública
Pedidos
Clave pública
{
“aud”:”consulta",
}
Microservicios
Auth
Clave privada y pública
Consulta
Clave pública
Cliente
Clave pública
Pedidos
Clave pública
{
“aud”:”consulta",
}
✘
Microservicios
Auth
Clave privada
Consulta
Cliente
Clave pública
Clave pública
Pedidos
Gateway
Soporte en PHP
Asegurando APIs en Symfony con JWT
Asegurando APIs en Symfony con JWT
lcobucci/jwt
Crear tokens
use LcobucciJWTBuilder;
use LcobucciJWTSignerKeychain;
use LcobucciJWTSignerRsaSha256;
$signer = new Sha256();
$keychain = new Keychain();
$privateKey = $keychain->getPrivateKey('file://path');
$token = (new Builder())->setIssuer('http://example.com')
->setAudience('http://example.org')
->setId('4f1g23a12aa', true)
->setIssuedAt(time())
->setNotBefore(time() + 60)
->setExpiration(time() + 3600)
->set('uid', 1)
->sign($signer, $privateKey)
->getToken();
Validar tokens
use LcobucciJWTSignerKeychain;
use LcobucciJWTSignerRsaSha256;
use LcobucciJWTValidationData;
$signer = new Sha256();
$keychain = new Keychain();
$publicKey = $keychain->getPublicKey('file://path');
$data = newValidationData();
$data->setIssuer('http://example.com');
$data->setAudience('http://example.org');
$data->setId('4f1g23a12aa');
$token->validate($data);
$token->verify($signer, $publicKey);
LexikJWTAuthenticationBundle
Instalación
composer require lexik/jwt-authentication-bundle
$bundles = array(
// ...
new LexikBundleJWTAuthenticationBundleLexikJWTAuthenticationBundle(),
// ...
);
app/config/AppKernel.php
Crear claves
$ openssl genrsa -out var/jwt/private.pem -aes256 4096
$ openssl rsa -pubout -in app/jwt/private.pem -out var/jwt/public.pem
Crear claves
$ openssl genrsa -out var/jwt/private.pem -aes256 4096
$ openssl rsa -pubout -in app/jwt/private.pem -out var/jwt/public.pem
Clave privada
Crear claves
$ openssl genrsa -out var/jwt/private.pem -aes256 4096
$ openssl rsa -pubout -in app/jwt/private.pem -out var/jwt/public.pem
Clave privada
Clave pública
Configuración
app/config/parameters.yml
app/config/config.yml
lexik_jwt_authentication:
private_key_path: %jwt_private_key_path%
public_key_path: %jwt_public_key_path%
pass_phrase: %jwt_key_pass_phrase%
token_ttl: %jwt_token_ttl%
parameters:
jwt_private_key_path: '%kernel.root_dir%/../var/jwt/private.pem'
jwt_public_key_path: '%kernel.root_dir%/../var/jwt/public.pem'
jwt_key_pass_phrase: patata
jwt_token_ttl: 3600
Configuración
app/config/parameters.yml
app/config/config.yml
lexik_jwt_authentication:
private_key_path: %jwt_private_key_path%
public_key_path: %jwt_public_key_path%
pass_phrase: %jwt_key_pass_phrase%
token_ttl: %jwt_token_ttl%
encoder:
service: lexik_jwt_authentication.encoder.lcobucci
parameters:
jwt_private_key_path: '%kernel.root_dir%/../var/jwt/private.pem'
jwt_public_key_path: '%kernel.root_dir%/../var/jwt/public.pem'
jwt_key_pass_phrase: patata
jwt_token_ttl: 3600
Configuración
app/config/parameters.yml
app/config/config.yml
lexik_jwt_authentication:
private_key_path: %jwt_private_key_path%
public_key_path: %jwt_public_key_path%
pass_phrase: %jwt_key_pass_phrase%
token_ttl: %jwt_token_ttl%
encoder:
service: lexik_jwt_authentication.encoder.lcobucci
parameters:
jwt_private_key_path: '%kernel.root_dir%/../var/jwt/private.pem'
jwt_public_key_path: '%kernel.root_dir%/../var/jwt/public.pem'
jwt_key_pass_phrase: patata
jwt_token_ttl: 3600
Probablemente será default en algún punto
firewalls:
login:
pattern: ^/api/login
stateless: true
anonymous: true
form_login:
check_path: /api/login_check
success_handler: lexik_jwt_authentication.handler.authentication_success
failure_handler: lexik_jwt_authentication.handler.authentication_failure
require_previous_session: false
api:
pattern: ^/api
stateless: true
guard:
authenticators:
- lexik_jwt_authentication.jwt_token_authenticator
Security config
app/config/security.yml
firewalls:
login:
pattern: ^/api/login
stateless: true
anonymous: true
form_login:
check_path: /api/login_check
success_handler: lexik_jwt_authentication.handler.authentication_success
failure_handler: lexik_jwt_authentication.handler.authentication_failure
require_previous_session: false
api:
pattern: ^/api
stateless: true
guard:
authenticators:
- lexik_jwt_authentication.jwt_token_authenticator
Security config
app/config/security.yml
No asigna cookies
Routing config
app/config/routing.yml
api_login_check:
path: /api/login_check
Asegurando APIs en Symfony con JWT
Extender el bundle
Eventos
JWT_CREATED: Añadir/quitar datos a claims.
JWT_DECODED: Validaciones extra.
JWT_AUTHENTICATED: Añadir datos al token de Symfony.
AUTHENTICATION_FAILURE
JWT_INVALID
JWT_NOT_FOUND
JWT_EXPIRED
}Cambiar respuestas.
AUTHENTICATION_SUCCESS
Añadir/quitar datos a payload
class JWTCreatedListener
{
public function onJWTCreated(JWTCreatedEvent $event)
{
$payload = $event->getData();
$user = $event->getUser();
if ($user->canOrder()) {
$payload['aud'] = ‘pedidos';
}
$event->setData($payload);
}
}
Comprobaciones extra
class JWTDecodedListener
{
public function onJWTDecoded(JWTDecodedEvent $event)
{
$payload = $event->getPayload();
if (!isset($payload['aud'])
|| $payload['aud'] !== 'pedidos') {
$event->markAsInvalid();
}
}
}
Añadir atributo API a Token Sf
class JWTAuthenticatedListener
{
public function onJWTAuthenticated(JWTAuthenticatedEvent $event)
{
$token = $event->getToken();
$token->setAttribute('api', true);
}
}
public function pagesAction(Request $request)
{
if ($this->get(‘security.token_storage')
->getToken()
->getAttribute(‘api')) {
return new JsonResponse('hola usuario de api');
}
}
¿Qué pasa si quiero…?
Tener diferentes estrategias en distintos firewalls
Hacer algo muy particular
Security
AuthenticationProviderInterface
Security
AuthenticationProviderInterface
UserProvider
Security
AuthenticationEntryPointInterface
AuthenticationProviderInterface
UserProvider
Security
AuthenticationListener
AuthenticationEntryPointInterface
AuthenticationProviderInterface
UserProvider
Security
AuthenticationListener
AuthenticationEntryPointInterface
AuthenticationProviderInterface
UserProvider
Security
Events
AuthenticationListener
AuthenticationEntryPointInterface
AuthenticationProviderInterface
UserProvider
Security
Events
UserInterface
AuthenticationListener
AuthenticationEntryPointInterface
AuthenticationProviderInterface
AbstractToken
UserProvider
Security
Events
UserInterface
AuthenticationListener
AuthenticationEntryPointInterface
AuthenticationProviderInterface
AbstractToken
UserProvider
Security
Voters
Events
UserInterface
UserProvider
UserProvider
👌
AuthenticationListener
AuthenticationEntryPointInterface
AuthenticationProviderInterface
AbstractToken
UserProvider
Security
Voters
Events
UserInterface
Guard 💂
👌
La interfaz GuardAuthenticator
interface GuardAuthenticatorInterface
{
public function getCredentials(Request $request);
public function getUser($credentials, UserProviderInterface $userProvider);
public function checkCredentials($credentials, UserInterface $user);
public function createAuthenticatedToken(UserInterface $user, $providerKey);
public function onAuthenticationFailure(Request $request,AuthenticationException $exception);
public function onAuthenticationSuccess(Request $request,TokenInterface $token, $providerKey);
public function supportsRememberMe();
}
La interfaz GuardAuthenticator
getCredentials
getUser
checkCredentials
createAuthenticatedToken
onAuthenticationFailure
onAuthenticationSuccess
supportsRememberMe
La interfaz GuardAuthenticator
getCredentials
getUser
checkCredentials
createAuthenticatedToken
onAuthenticationFailure
onAuthenticationSuccess
supportsRememberMe
Validar token
La interfaz GuardAuthenticator
getCredentials
getUser
checkCredentials
createAuthenticatedToken
onAuthenticationFailure
onAuthenticationSuccess
supportsRememberMe
Validar token
Obtener usuario a partir de JWT
La interfaz GuardAuthenticator
getCredentials
getUser
checkCredentials
createAuthenticatedToken
onAuthenticationFailure
onAuthenticationSuccess
supportsRememberMe
Validar token
Obtener usuario a partir de JWT
true
La interfaz GuardAuthenticator
getCredentials
getUser
checkCredentials
createAuthenticatedToken
onAuthenticationFailure
onAuthenticationSuccess
supportsRememberMe
Validar token
Obtener usuario a partir de JWT
true
Crear token de Symfony (no JWT)
La interfaz GuardAuthenticator
getCredentials
getUser
checkCredentials
createAuthenticatedToken
onAuthenticationFailure
onAuthenticationSuccess
supportsRememberMe
Devolver respuesta adecuada
Validar token
Obtener usuario a partir de JWT
true
Crear token de Symfony (no JWT)
La interfaz GuardAuthenticator
getCredentials
getUser
checkCredentials
createAuthenticatedToken
onAuthenticationFailure
onAuthenticationSuccess
supportsRememberMe
No hacer nada
Devolver respuesta adecuada
Validar token
Obtener usuario a partir de JWT
true
Crear token de Symfony (no JWT)
La interfaz GuardAuthenticator
getCredentials
getUser
checkCredentials
createAuthenticatedToken
onAuthenticationFailure
onAuthenticationSuccess
supportsRememberMe false
No hacer nada
Devolver respuesta adecuada
Validar token
Obtener usuario a partir de JWT
true
Crear token de Symfony (no JWT)
La interfaz GuardAuthenticator
getCredentials
getUser
checkCredentials
createAuthenticatedToken
onAuthenticationFailure
onAuthenticationSuccess
supportsRememberMe false
No hacer nada
Devolver respuesta adecuada
Validar token
Obtener usuario a partir de JWT
true
Crear token de Symfony (no JWT)
JWTTokenAuthenticator
use LexikBundleJWTAuthenticationBundleSecurityGuardJWTTokenAuthenticator as BaseAuthenticator;
class MiTokenAuthenticator extends BaseAuthenticator
{
}
security:
# ...
firewalls:
# ...
otra_api:
pattern: ^/otraapi
stateless: true
guard:
authenticators:
- app.mi_token_authenticator
FAQ
Oauth vs JWT? Oauth + JWT?
Usos fuera de headers
token_extractors:
authorization_header:
enabled: true
prefix: Bearer
name: Authorization
cookie:
enabled: false
name: BEARER
query_parameter:
enabled: false
name: bearer
Cuántos datos caben en un token?
https://www.flickr.com/photos/highwaysagency/6008275527
Invalidar tokens
Enlaces con caducidad
$user = $this->getUser();
$jwtManager = $this->get('lexik_jwt_authentication.jwt_manager');
$token2 = $jwtManager->create($user);
<a href="{{ path('reset_password', {'bearer':authToken.credentials}) }}”>
Reset password
</a>
Controlador
Vista
Renovar tokens
👌
Impersonar usuarios en APIs
👌
Impersonar usuarios en APIs
HEADER:
X-Switch-User: johndoe
Requests a otros dominios
👌
Ejemplo de uso con React
Asegurando APIs en Symfony con JWT
Asegurando APIs en Symfony con JWT
¡Gracias!
@nacmartin
nacho@limenius.com
http://limenius.com
Formación, consultoría
y desarrollo de proyectos

Más contenido relacionado

PPTX
Aula 01 - JavaScript: Introdução
PDF
Fundamentos do java
PPTX
SonarQube - Como avaliar seus fornecedores e garantir a qualidade de suas ent...
PDF
Arquitetura de Software Visão Geral
PPTX
ABORDAGEM DE JOGOS DIGITAIS: ANÁLISE E INVERSÃO DA MECÂNICA NO JOGO ALEX KIDD...
PDF
Introdução à Visualização de Dados (2015)
PPTX
Introdução a programação para a Internet
PDF
Introdução, instalação e configuração do SonarQube
Aula 01 - JavaScript: Introdução
Fundamentos do java
SonarQube - Como avaliar seus fornecedores e garantir a qualidade de suas ent...
Arquitetura de Software Visão Geral
ABORDAGEM DE JOGOS DIGITAIS: ANÁLISE E INVERSÃO DA MECÂNICA NO JOGO ALEX KIDD...
Introdução à Visualização de Dados (2015)
Introdução a programação para a Internet
Introdução, instalação e configuração do SonarQube

La actualidad más candente (20)

PDF
Modelos e etapas do processo de software.pdf
PDF
Road Show TI SENAC - HTML5 & CSS 3.0 - O que esperar da próxima web?
PDF
Arquitetura de Software
PDF
Introdução a JavaScript
PDF
Style Guide Best Practices
PPTX
Azure DevOps
PDF
03 - Orientação a objetos e classes em C# v1.0
PDF
Aula 05 - UML e Padrões de Projeto
PPTX
Enforcing Quality with DevOps Pipeline Gates
PDF
Arquitetura funcional em microservices, 4 anos depois
PDF
API Security Best Practices & Guidelines
PDF
How to Deploy WSO2 Enterprise Integrator in Containers
PDF
Lógica de Programação com Javascript - Aula #02
PPT
Conceitos de básicos de qualidade de software
PPT
Java modulo 01 - Introdução
PDF
Lista de exercícios em Bash (resolvida)
PDF
Tutorial Django + Python
PPTX
Quality Assurance/Testing Overview & Capability Deck
PDF
Aula 01 - Introdução ao C++
PDF
DevOps overview 2019-04-13 Nelkinda April Meetup
Modelos e etapas do processo de software.pdf
Road Show TI SENAC - HTML5 & CSS 3.0 - O que esperar da próxima web?
Arquitetura de Software
Introdução a JavaScript
Style Guide Best Practices
Azure DevOps
03 - Orientação a objetos e classes em C# v1.0
Aula 05 - UML e Padrões de Projeto
Enforcing Quality with DevOps Pipeline Gates
Arquitetura funcional em microservices, 4 anos depois
API Security Best Practices & Guidelines
How to Deploy WSO2 Enterprise Integrator in Containers
Lógica de Programação com Javascript - Aula #02
Conceitos de básicos de qualidade de software
Java modulo 01 - Introdução
Lista de exercícios em Bash (resolvida)
Tutorial Django + Python
Quality Assurance/Testing Overview & Capability Deck
Aula 01 - Introdução ao C++
DevOps overview 2019-04-13 Nelkinda April Meetup
Publicidad

Similar a Asegurando APIs en Symfony con JWT (20)

PDF
Meetup En mi local funciona - Protegiendo tu API REST con JWT en aplicaciones...
PDF
Seguridad para aplicaciones web java con json web tokens (jwt) 2020
PPTX
JWT.pptx
PPTX
GFI - Seguridad en tus APIs
PPTX
Qué es eso de OAuth y como se implementa en Symfony2 (y otros)
PDF
La importancia de la seguridad en los json payloads
PDF
Seguridad Entornos Web Open Source
PPTX
Presentacion-Oauth
PDF
Seguridad en Aplicaciones Web y Comercio Electrónico
PPTX
WSO2 API Manager y ESB la plataforma perfecta para evolucionar los servicios
PDF
Seguridad en la web
PPTX
[Webinar] Gestión Identidades y Control de Acceso en los Servicios usando WSO...
PPTX
OAuth and OpenID
PDF
OAuth 2.0 (Spanish)
PPTX
Seguridad en Apache Web Server
PDF
Seguridad de APIs en Drupal_ herramientas, mejores prácticas y estrategias pa...
PDF
Seguridad en Entornos Web Open Source
PDF
Autenticación en aplicaciones .Net web y nativas
Meetup En mi local funciona - Protegiendo tu API REST con JWT en aplicaciones...
Seguridad para aplicaciones web java con json web tokens (jwt) 2020
JWT.pptx
GFI - Seguridad en tus APIs
Qué es eso de OAuth y como se implementa en Symfony2 (y otros)
La importancia de la seguridad en los json payloads
Seguridad Entornos Web Open Source
Presentacion-Oauth
Seguridad en Aplicaciones Web y Comercio Electrónico
WSO2 API Manager y ESB la plataforma perfecta para evolucionar los servicios
Seguridad en la web
[Webinar] Gestión Identidades y Control de Acceso en los Servicios usando WSO...
OAuth and OpenID
OAuth 2.0 (Spanish)
Seguridad en Apache Web Server
Seguridad de APIs en Drupal_ herramientas, mejores prácticas y estrategias pa...
Seguridad en Entornos Web Open Source
Autenticación en aplicaciones .Net web y nativas
Publicidad

Más de Ignacio Martín (18)

PDF
Elixir/OTP for PHP developers
PDF
Introduction to React Native Workshop
PDF
Server side rendering with React and Symfony
PDF
Symfony 4 Workshop - Limenius
PDF
Server Side Rendering of JavaScript in PHP
PDF
Extending Redux in the Server Side
PDF
Redux Sagas - React Alicante
PDF
React Native Workshop - React Alicante
PDF
Redux saga: managing your side effects. Also: generators in es6
PDF
Integrating React.js with PHP projects
PDF
Introduction to Redux
PDF
Keeping the frontend under control with Symfony and Webpack
PDF
Integrando React.js en aplicaciones Symfony (deSymfony 2016)
PDF
Adding Realtime to your Projects
PDF
Symfony & Javascript. Combining the best of two worlds
PDF
Symfony 2 CMF
PDF
Doctrine2 sf2Vigo
PDF
Presentacion git
Elixir/OTP for PHP developers
Introduction to React Native Workshop
Server side rendering with React and Symfony
Symfony 4 Workshop - Limenius
Server Side Rendering of JavaScript in PHP
Extending Redux in the Server Side
Redux Sagas - React Alicante
React Native Workshop - React Alicante
Redux saga: managing your side effects. Also: generators in es6
Integrating React.js with PHP projects
Introduction to Redux
Keeping the frontend under control with Symfony and Webpack
Integrando React.js en aplicaciones Symfony (deSymfony 2016)
Adding Realtime to your Projects
Symfony & Javascript. Combining the best of two worlds
Symfony 2 CMF
Doctrine2 sf2Vigo
Presentacion git

Último (11)

PDF
AutoCAD Herramientas para el futuro, Juan Fandiño
PPTX
ORIGEN DE LA IA - GRADO 1102 INTELIGENCIA
PPTX
Conceptos basicos de Base de Datos y sus propiedades
PPTX
Tratará sobre Grafos_y_Arboles_Presentacion.pptx
DOCX
trabajo programacion.docxxdxxxddxdxxdxdxxxdxxdxdxd
PDF
Clase 3 - Presentación visual (Insertando objetos visuales) POWER POINT.pdf
PPTX
Fundamentos de Python - Curso de Python dia 1
PDF
Su punto de partida en la IA: Microsoft 365 Copilot Chat
PPTX
Implementación equipo monitor12.08.25.pptx
PPTX
sistemas de informacion.................
PPTX
Derechos_de_Autor_y_Creative_Commons.pptx
AutoCAD Herramientas para el futuro, Juan Fandiño
ORIGEN DE LA IA - GRADO 1102 INTELIGENCIA
Conceptos basicos de Base de Datos y sus propiedades
Tratará sobre Grafos_y_Arboles_Presentacion.pptx
trabajo programacion.docxxdxxxddxdxxdxdxxxdxxdxdxd
Clase 3 - Presentación visual (Insertando objetos visuales) POWER POINT.pdf
Fundamentos de Python - Curso de Python dia 1
Su punto de partida en la IA: Microsoft 365 Copilot Chat
Implementación equipo monitor12.08.25.pptx
sistemas de informacion.................
Derechos_de_Autor_y_Creative_Commons.pptx

Asegurando APIs en Symfony con JWT