App\Middleware\Auth

Auth Middleware

This class is included with the starter site and is intended as a starting point and template for authentication and provides a number of options for creating secure sites using authentication.

This class can be used as-is without any changes or you can remove features that you do not need to reduce the size of the code. If you intend on using this class with a site that has many users spending time to remove un-needed code is recommended because it’s a good practice as it will help you understand the full security of your site and various security options. A good starting point is to search for "$this->method" and "$method" and remove methods and all related code that you do not use.

By default this class uses JSON Web Tokens (JWT) with a 1 hour timeout and session cookie for the storage format. Request and Response headers using a Bearer Token are also included for authentication with API’s and Web Services. In addition to JWT this class supports Signed Cookies, Encrypted Cookies, and PHP Sessions. To change the storage format modify the private [$method] property of this class.

A new token/cookie will be sent to the client with each response so that the user can keep browswing the site as long as they remain active within the expiration time.

When first used this class will create a [.env] file with secure config settings, a SQLite database for users, and a demo admin user. LDAP can be used for network validation (for example: Windows Active Directory on a Corporate Network) instead of a database by modifying the private [$type] property of this class. To use your own database instead of SQLite search for "connectToDb" to find where SQLite is used and then modify the code.

Public functions for routing and for filtering routes:
    login($app, $lang)
    logout($app)
    hasAccess($app)

Public functions for editing users in the demo db:
    addUser($app, $login, $password)
    updateUser($app, $login, $new_password)
    deleteUser($app, $login)

See also:
    setupDemo()
    validateDbUser()
    validateLdapUser()
    How this class is used from [app/app.php], search for "Auth."

IMPORTANT - If you end up using this class without making any changes then you MUST change the password on the example Admin user to a secure/strong password. This can be done with a temporary route on your site by copying and modifying the example code below:

    $app->get('/admin/update-user', function() use ($app) {
        $auth = new \App\Middleware\Auth();
        return $auth->addUser($app, 'name', 'password');
        return $auth->updateUser($app, 'name', 'new_password');
        return $auth->deleteUser($app, 'name');
    });

Or define routes for a localhost admin user, example:

    $app->get('/auth/add/:name/:password', 'Auth.addUser')->filter('Env.isLocalhost');
    $app->get('/auth/update/:name/:new_password', 'Auth.updateUser')->filter('Env.isLocalhost');
    $app->get('/auth/delete/:name', 'Auth.deleteUser')->filter('Env.isLocalhost');

Código Fonte

GitHub

Código de Exemplo

Starter Site Middleware


// The FastSitePHP Starter Site inclui várias páginas de exemplos e fornece uma
// estrutura básica de diretório / arquivo. O site foi projetado para fornecer
// estrutura para conteúdo básico (JavaScript, CSS etc.), mantendo um tamanho
// pequeno, para facilitar a remoção de arquivos desnecessários e a
// personalização para o seu site.
//
//     https://github.com/fastsitephp/starter-site
//
// As classes de Middleware são fornecidas e podem ser modificadas para
// o seu site.
//
// Para utilizá-las especifique 'Class.method' nas funções filtro da rota
// ou quando montando arquivos adicionais.

// Exige que um usuário esteja logado para utilizar uma página
$app->get('/secure-page', 'SecureController')->filter('Auth.hasAccess');

// Exige um usuário autenticado e utilize CORS
$app
    ->get('/api/:record_type', 'ApiController.getData')
    ->filter('Cors.acceptAuth')
    ->filter('Auth.hasAccess');

// Somente rode uma rota de localhost
$app->get('/server-info', function() {
    phpinfo();
})
->filter('Env.isLocalhost');

// Somente carregue um arquivo se estiver rodando à partir de localhost
$app->mount('/sysinfo/', 'routes-sysinfo.php', 'Env.isLocalhost');

Métodos

hasAccess(Application $app)

Check if a user has access based on the Request. This function is intended to be used as a route filter function. If the user does not have access this function will return a 401 Unauthorized Response with a login page.

If the request header [Content-Type] = 'application/json' and the user does not have access then a 401 JSON Response will returned instead of the login page.

Retorna: bool

login(Application $app, $lang)

Login method. Returns a JSON response for the login page.

In the starter site template this is called from the URL:
  POST '/:lang/auth/login'

Retorna: Response

logout(Application $app)

Logout and redirect to the site root URL.

In the starter site template this is called from the URL:
  GET|POST|{ANY} '/auth/logout'

When JWT, Signed Cookies, or Encrypted Cookies are used the previously used Access Token will still be valid until it expires (or unless the site config crypto keys or settings are changed). The logout feature is simply intended for websites so a user can logout. As long as HTTPS is used then the previous token cannot be monitored and will be cleared from the browser cache on logout. This is by design because tokens are not invalidated from this class once a user logs out. If you need to track tokens per user and include additional limitations then this would be part of the logic for your app.

Retorna: Response

addUser(Application $app, $login, $password)

Add a user to the example SQLite database

Retorna: array

updateUser(Application $app, $login, $new_password)

Change the password for a user in the example SQLite database

Retorna: array

deleteUser(Application $app, $login)

Delete a user from the example SQLite database

Retorna: array