PHP code example of grimzy / security-json-service-provider

1. Go to this page and download the library: Download grimzy/security-json-service-provider library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

grimzy / security-json-service-provider example snippets


$app['security.firewalls'] = [
  'login' => [
    'pattern' => '^/api/login',
    'anonymous' => true,
    'stateless' => true,
    'json' => [
      // Default configuration
      'username_parameter' => 'username',
      'password_parameter' => 'password',
      'post_only' => true,
      'json_only' => true
    ]
  ],

  'secured' => [
    'pattern' => '^.*$',
    'stateless' => true,
    'token' => true	
  ],
];

$app['users'] = function () use ($app) {
  return new InMemoryUserProvider([
    'admin' => [
      'roles' => ['ROLE_ADMIN'],
      'password' => '5FZ2Z8QIkA7UTZ4BYkoC+GsReLf569mSKDsfods6LYQ8t+a8EW9oaircfMpmaLbPBh4FOBiiFyLfuZmTSUwzZg==',	// foo
      'enabled' => true
    ],
  ]);
};

$app['security.firewalls' => [
  'login' => [
    'pattern' => '^/api/login',
    'anonymous' => true,
    'stateless' => true,
    'json' => [
      // Default configuration
      'username_parameter' => 'username',
      'password_parameter' => 'password',
      'post_only' => true,
      'json_only' => true
    ]
  ],

  'secured' => [
    'pattern' => '^.*$',
    'stateless' => true,
    'token' => true
  ],
]];

$app->register(new Silex\Provider\SecurityServiceProvider());
$app->register(new Silex\Provider\SecurityJsonServiceProvider());

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;

$app->post('/api/login', function(Request $request) use ($app) {
  $user = $app['user'];	// Logged in user
  
  $token = $app['some.token_encoder']->encode($user);
  
  return new JsonResponse([
    'token' => $token
  ]);
};

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface;

class GandalfAuthenticationEntryPoint implements AuthenticationEntryPointInterface
{
    /**
     * {@inheritdoc}
     */
    public function start(Request $request, AuthenticationException $authException = null)
    {
        return new Response('You shall not pass!', Response::HTTP_UNAUTHORIZED);
    }
}

$app->register(new Silex\Provider\SecurityJsonServiceProvider());

// after registering the provider
$app['security.entry_point.json'] = function () use ($app) {
    return new GandalfAuthenticationEntryPoint();
};