Minimalistic token-based authorization for Laravel API endpoints.

Overview

Bearer

Latest Version on Packagist GitHub Tests Action Status GitHub Code Style Action Status Total Downloads

Minimalistic token-based authorization for Laravel API endpoints.

Installation

You can install the package via Composer:

composer require ryangjchandler/bearer

You can publish and run the migrations with:

php artisan vendor:publish --provider="RyanChandler\Bearer\BearerServiceProvider" --tag="bearer-migrations"
php artisan migrate

You can publish the config file with:

php artisan vendor:publish --provider="RyanChandler\Bearer\BearerServiceProvider" --tag="bearer-config"

Usage

Creating tokens

To create a new token, you can use the RyanChandler\Bearer\Models\Token model.

use RyanChandler\Bearer\Models\Token;

$token = Token::create([
    'token' => Str::random(32),
]);

Alternatively, you can use the RyanChandler\Bearer\Facades\Bearer facade to generate a token.

use RyanChandler\Bearer\Facades\Bearer;

$token = Bearer::generate(domains: [], expiresAt: null);

By default, Bearer uses time-ordered UUIDs for token strings. You can modify this behaviour by passing a Closure to Bearer::generateTokenUsing. This function must return a string for storage to the database.

use RyanChandler\Bearer\Facades\Bearer;

Bearer::generateTokenUsing(static function (): string {
    return (string) Str::orderedUuid();
});

Retrieving a Token instance

To retreive a Token instance from the token string, you can use the RyanChandler\Bearer\Facades\Bearer facade.

use RyanChandler\Bearer\Facades\Bearer;

$token = Bearer::find('my-token-string');

Using a token in a request

Bearer uses the Authorization header of a request to retreive the token instance. You should format it like so:

Authorization: Bearer my-token-string

Verifying tokens

To verify a token, add the RyanChandler\Bearer\Http\Middleware\VerifyBearerToken middleware to your API route.

use RyanChandler\Bearer\Http\Middleware\VerifyBearerToken;

Route::get('/endpoint', MyEndpointController::class)->middleware(VerifyBearerToken::class);

Token expiration

If you would like a token to expire at a particular time, you can use the expires_at column.

$token = Bearer::find('my-token-string');

$token->update([
    'expires_at' => now()->addWeek(),
]);

If you try to use the token after this time, it will return an error.

Limit tokens to a particular domain

Token usage can be restricted to a particular domain. Bearer uses the scheme and host from the request to determine if the token is valid or not.

$token = Bearer::find('my-token-string');

$token->update([
    'domains' => [
        'https://laravel.com',
    ],
]);

If you attempt to use this token from any domain other than https://laravel.com, it will fail and abort.

Note: domain checks include the scheme so be sure to add both cases for HTTP and HTTPS if needed.

Testing

composer test

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security Vulnerabilities

Please review our security policy on how to report security vulnerabilities.

Credits

License

The MIT License (MIT). Please see License File for more information.

You might also like...
An authorization library that supports access control models like ACL, RBAC, ABAC in Laravel.

Laravel Authorization Laravel-authz is an authorization library for the laravel framework. It's based on Casbin, an authorization library that support

A framework agnostic authentication & authorization system.

Sentinel Sentinel is a PHP 7.3+ framework agnostic fully-featured authentication & authorization system. It also provides additional features such as

An authorization library that supports access control models like ACL, RBAC, ABAC in PHP .
An authorization library that supports access control models like ACL, RBAC, ABAC in PHP .

PHP-Casbin Documentation | Tutorials | Extensions Breaking News: Laravel-authz is now available, an authorization library for the Laravel framework. P

It's authorization form, login button handler and login to your personal account, logout button
It's authorization form, login button handler and login to your personal account, logout button

Authorization-form It's authorization form, login button handler and login to your personal account, logout button Each file is: header.php - html-fil

Authentication and authorization library for Codeigniter 4

Authentication and Authorization Library for CodeIgniter 4. This library provides an easy and simple way to create login, logout, and user registratio

This is a basic Oauth2 authorization/authentication server implemented using Mezzio.
This is a basic Oauth2 authorization/authentication server implemented using Mezzio.

Mezzio-OAuth2-Authorization-Authentication-Server This is a basic OAuth2 authorization/authentication server implemented using Mezzio. I have found so

EvaOAuth provides a standard interface for OAuth1.0(a) / OAuth2.0 client authorization, it is easy to integrate with any PHP project by very few lines code.

EvaOAuth EvaOAuth provides a standard interface for OAuth1.0 / OAuth2.0 client authorization, it is easy to integrate with any PHP project by very few

EvaOAuth provides a standard interface for OAuth1.0(a) / OAuth2.0 client authorization, it is easy to integrate with any PHP project by very few lines code.

EvaOAuth EvaOAuth provides a standard interface for OAuth1.0 / OAuth2.0 client authorization, it is easy to integrate with any PHP project by very few

Comments
  • Add support for increase the expiration time

    Add support for increase the expiration time

    This PR add a couple of methods to interact with the expiration date of the token based on the Carbon\Carbon api. E.G,

    <?php
    
    use RyanChandler\Bearer\Facades\Bearer;
    
    $token = Bearer::generate(domains: ['https://google.com'], expiresAt: now()->subMinutes(2));
    
    $token->expired; // true
    
    $token->addDays(2);
    
    $token->expired; // false
    
    $token->save();
    

    Methods added:

    <?php
    
    $token->addMinutes(int $minutes);
    
    $token->addHours(int $hours);
    
    $token->addDays(int $days);
    
    $token->addWeeks(int $weeks);
    
    $token->addMonths(int $months);
    

    I hope it is useful.

    opened by gregorip02 3
Releases(v0.5.0)
Owner
Ryan Chandler
Ryan Chandler
Un proyecto que crea una API de usuarios para registro, login y luego acceder a su información mediante autenticación con JSON Web Token

JSON WEB TOKEN CON LARAVEL 8 Prueba de autenticación de usuarios con una API creada en Laravel 8 Simple, fast routing engine. License The Laravel fram

Yesser Miranda 2 Oct 10, 2021
Manage authorization with granular role-based permissions in your Laravel Apps.

Governor For Laravel Manage authorization with granular role-based permissions in your Laravel apps. Goal Provide a simple method of managing ACL in a

GeneaLabs, LLC 149 Dec 23, 2022
🔐 JSON Web Token Authentication for Laravel & Lumen

Documentation Documentation for 1.* here For version 0.5.* See the WIKI for documentation. Supported by Auth0 If you want to easily add secure authent

Sean Tymon 10.7k Dec 31, 2022
🔐 JSON Web Token Authentication for Laravel & Lumen

Credits This repository it a fork from original tymonsdesigns/jwt-auth, we decided to fork and work independent because the original one was not being

null 490 Dec 27, 2022
A simple library to work with JSON Web Token and JSON Web Signature

JWT A simple library to work with JSON Web Token and JSON Web Signature based on the RFC 7519. Installation Package is available on Packagist, you can

Luís Cobucci 6.8k Jan 3, 2023
Implements a Refresh Token system over Json Web Tokens in Symfony

JWTRefreshTokenBundle The purpose of this bundle is manage refresh tokens with JWT (Json Web Tokens) in an easy way. This bundles uses LexikJWTAuthent

Marcos Gómez Vilches 568 Dec 28, 2022
JSON Web Token (JWT) for webman plugin

JSON Web Token (JWT) for webman plugin Json web token (JWT), 是为了在网络应用环境间传递声明而执行的一种基于JSON的开放标准((RFC 7519).该token被设计为紧凑且安全的,特别适用于分布式站点的单点登录(SSO)场景。

 ShaoBo Wan(無尘) 25 Dec 30, 2022
Declarative style of authorization and validation in laravel.

Laravel Hey Man Readability Counts. In fact, Readability is the primary value of your code !!! ?? Heyman continues where the other role-permission pac

Iman 860 Jan 1, 2023
Files Course Laravel Micro Auth and Authorization

About Laravel Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experie

EspecializaTi 8 Oct 22, 2022
Easy, native Laravel user authorization.

An easy, native role / permission management system for Laravel. Index Installation Migration Customization Model Customization Usage Checking Permiss

DirectoryTree 5 Dec 14, 2022