Download the PHP package rinvex/laravel-oauth without Composer

On this page you can find all versions of the php package rinvex/laravel-oauth. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.

FAQ

After the download, you have to make one include require_once('vendor/autoload.php');. After that you have to import the classes with use statements.

Example:
If you use only one package a project is not needed. But if you use more then one package, without a project it is not possible to import the classes with use statements.

In general, it is recommended to use always a project to download your libraries. In an application normally there is more than one library needed.
Some PHP packages are not free to download and because of that hosted in private repositories. In this case some credentials are needed to access such packages. Please use the auth.json textarea to insert credentials, if a package is coming from a private repository. You can look here for more information.

  • Some hosting areas are not accessible by a terminal or SSH. Then it is not possible to use Composer.
  • To use Composer is sometimes complicated. Especially for beginners.
  • Composer needs much resources. Sometimes they are not available on a simple webspace.
  • If you are using private repositories you don't need to share your credentials. You can set up everything on our site and then you provide a simple download link to your team member.
  • Simplify your Composer build process. Use our own command line tool to download the vendor folder as binary. This makes your build process faster and you don't need to expose your credentials for private repositories.
Please rate this library. Is it a good library?

Informations about the package laravel-oauth

Rinvex OAuth

Rinvex OAuth is an OAuth2 server and API authentication package that is simple and enjoyable to use.

Packagist Scrutinizer Code Quality Travis StyleCI License

Usage

Introduction

Rinvex OAuth provides a full OAuth2 server implementation for your Laravel application in a matter of minutes. Rinvex OAuth was inspired by and based on a lightweight modified version of Laravel Passport v10.3.1, which is built on top of the League OAuth2 server that is maintained by Andy Millington and Simon Hamp.

Note: This documentation assumes you are already familiar with OAuth2. If you do not know anything about OAuth2, consider familiarizing yourself with the general terminology and features of OAuth2 before continuing.

Rinvex OAuth Or Laravel Passport?

Before getting started, you may wish to determine if your application would be better served by Rinvex OAuth or Laravel Passport. The short answer is: use "Laravel Passport"! Rinvex OAuth is a lightweight modified version of Laravel Passport, that's simplified to fit our Rinvex Cortex projects, so the fact that you are asking what's the difference between both, and which one to choose is enough for you to go with Laravel Passport without a doubt.

However, if you are attempting to use or build Rinvex Cortex based applications, you should use Rinvex OAuth. Rinvex OAuth is required and installed by default when building APIs for Rinvex Cortex.

Installing Rinvex OAuth does NOT require Laravel Passport. It is in fact a complete lightweight replacement.

Installation

  1. To get started, install Rinvex OAuth via the Composer package manager:

  2. Rinvex OAuth registers its own database migration directory, so you should migrate your database after installing the package. The Rinvex OAuth migrations will create the tables your application needs to store OAuth2 clients and access tokens:

  3. Add the Rinvex\Oauth\Traits\HasApiTokens trait to your App\Models\User model. This trait will provide a few helper methods to your model which allow you to inspect the authenticated user's token and scopes:

  4. Finally, in your application's config/auth.php configuration file, you should set the driver option of the api authentication guard to oauth. This will instruct your application to use Rinvex OAuth's TokenGuard when authenticating incoming API requests:

Deploying Rinvex OAuth

When deploying Rinvex OAuth to your application's servers for the first time, you will likely need to run the rinvex:oauth:keys command. This command generates the encryption keys Rinvex OAuth needs in order to generate access tokens. The generated keys are not typically kept in source control:

Typically, Rinvex OAuth's keys are loaded from storage_path.

Loading Keys From The Environment

Alternatively, you may publish Rinvex OAuth's configuration file using the rinvex:publish:oauth Artisan command:

Migration Customization

If you are not going to use Rinvex OAuth's default migrations, you should export the configuration file using this command php artisan rinvex:publish:oauth --resource=migrations, and disable migrations autoload from confirg rinvex.oauth.autoload_migrations to false.

Configuration

Client Secret Hashing

All of your client secrets are hashed and will only be displayable to the user immediately after they are created. Since the plain-text client secret value is never stored in the database, it is not possible to recover the secret's value if it is lost.

Token Lifetimes

By default, Rinvex OAuth issues long-lived access tokens that expire after one year. If you would like to configure a longer / shorter token lifetime, you change default using config options. See for example rinvex.oauth.grants.Password.expire_in, you can configure other grants expiration in the same way.

Note: The expires_at columns on Rinvex OAuth's database tables are read-only and for display purposes only. When issuing tokens, Rinvex OAuth stores the expiration information within the signed and encrypted tokens. If you need to invalidate a token you should revoke it.

Overriding Default Models

You are free to extend the models used internally by Rinvex OAuth by defining your own model and extending the corresponding Rinvex OAuth model:

After defining your model, you may instruct Rinvex OAuth to use your custom model via config options rinvex.oauth.models:

Issuing Access Tokens

Using OAuth2 via authorization codes is how most developers are familiar with OAuth2. When using authorization codes, a client application will redirect a user to your server where they will either approve or deny the request to issue an access token to the client.

Managing Clients

First, developers building applications that need to interact with your application's API will need to register their application with yours by creating a "client". Typically, this consists of providing the name of their application and a URL that your application can redirect to after users approve their request for authorization.

The rinvex:oauth:client Command

The simplest way to create a client is using the rinvex:oauth:client Artisan command. This command may be used to create your own clients for testing your OAuth2 functionality. When you run the client command, Rinvex OAuth will prompt you for more information about your client and will provide you with a client ID and secret:

Redirect URLs

If you would like to allow multiple redirect URLs for your client, you may specify them using a comma-delimited list when prompted for the URL by the rinvex:oauth:client command. Any URLs which contain commas should be URL encoded:

Dashboard Interface

Since your application's users will not be able to utilize the client command, Rinvex OAuth has a companion wrapping module Cortex OAuth that provides complete backend and frontend dashboards that you may use to create clients. This saves you the trouble of having to manually code controllers for creating, updating, and deleting clients.

Check Cortex OAuth documentation for full details on the dashboard endpoints for managing clients. The dashboard interface is guarded by the web and auth middleware; therefore, it may only be called from your own application by an authenticated user.

Requesting Tokens

Redirecting For Authorization

Once a client has been created, developers may use their client ID and secret to request an authorization code and access token from your application. First, the consuming application should make a redirect request to your application's /oauth/authorize route like so:

Notes:

  • Scopes must be valid abilities, already created, and assigned to the user who is processing this authorization request.
  • Remember, if you are using Cortex OAuth, you do not need to manually define this route /oauth/authorize as it is already defined by the module.

Approving The Request

If you're using Cortex OAuth, when receiving authorization requests, Cortex OAuth will automatically display a template to the user allowing them to approve or deny the authorization request. If they approve the request, they will be redirected back to the redirect_uri that was specified by the consuming application. The redirect_uri must match the redirect URL that was specified when the client was created.

If you would like to customize the authorization approval screen, you may publish Rinvex OAuth's views using the cortex:publish:oauth Artisan command. The published views will be placed in the resources/views/vendor/cortex/oauth directory:

Sometimes you may wish to skip the authorization prompt, such as when authorizing a first-party client. You may accomplish this by extending the Client model and defining a skipsAuthorization method. If skipsAuthorization returns true the client will be approved and the user will be redirected back to the redirect_uri immediately:

Converting Authorization Codes To Access Tokens

If the user approves the authorization request, they will be redirected back to the consuming application. The consumer should first verify the state parameter against the value that was stored prior to the redirect. If the state parameter matches then the consumer should issue a POST request to your application to request an access token. The request should include the authorization code that was issued by your application when the user approved the authorization request:

This /oauth/token route will return a JSON response containing access_token, refresh_token, and expires_in attributes. The expires_in attribute contains the number of seconds until the access token expires.

Note: if you are using Cortex OAuth, you do not need to manually define the /oauth/token route as it is defined for you by the module, like /oauth/authorize. There is no need to manually define this route.

Refreshing Tokens

If your application issues short-lived access tokens, users will need to refresh their access tokens via the refresh token that was provided to them when the access token was issued:

This /oauth/token route will return a JSON response containing access_token, refresh_token, and expires_in attributes. The expires_in attribute contains the number of seconds until the access token expires.

Revoking Tokens

You may revoke access token by using the revoke method on the Rinvex\Oauth\Models\AccessToken.

Alternatively, you can achieve the same result directly by using the revokeAccessToken method on the Rinvex\Oauth\Repositories\AccessTokenRepository.

Note: Revoking access token, will revoke all associated refresh tokens as well.

You may revoke a specific refresh token by using the revoke method on the Rinvex\Oauth\Models\RefreshToken.

Purging Tokens

When tokens have been revoked or expired, you might want to purge them from the database. Rinvex OAuth's included rinvex:oauth:purge Artisan command can do this for you:

You may also configure a scheduled job in your application's App\Console\Kernel class to automatically prune your tokens on a schedule:

Authorization Code Grant with PKCE

The Authorization Code grant with "Proof Key for Code Exchange" (PKCE) is a secure way to authenticate single page applications or native applications to access your API. This grant should be used when you can't guarantee that the client secret will be stored confidentially or in order to mitigate the threat of having the authorization code intercepted by an attacker. A combination of a "code verifier" and a "code challenge" replaces the client secret when exchanging the authorization code for an access token.

Creating The Client

Before your application can issue tokens via the authorization code grant with PKCE, you will need to create a PKCE-enabled client. You may do this using the rinvex:oauth:client Artisan command with the --public option:

Requesting Tokens

Code Verifier & Code Challenge

As this authorization grant does not provide a client secret, developers will need to generate a combination of a code verifier and a code challenge in order to request a token.

The code verifier should be a random string of between 43 and 128 characters containing letters, numbers, and "-", ".", "_", "~" characters, as defined in the RFC 7636 specification.

The code challenge should be a Base64 encoded string with URL and filename-safe characters. The trailing '=' characters should be removed and no line breaks, whitespace, or other additional characters should be present.

Redirecting For Authorization

Once a client has been created, you may use the client ID and the generated code verifier and code challenge to request an authorization code and access token from your application. First, the consuming application should make a redirect request to your application's /oauth/authorize route:

Converting Authorization Codes To Access Tokens

If the user approves the authorization request, they will be redirected back to the consuming application. The consumer should verify the state parameter against the value that was stored prior to the redirect, as in the standard Authorization Code Grant.

If the state parameter matches, the consumer should issue a POST request to your application to request an access token. The request should include the authorization code that was issued by your application when the user approved the authorization request along with the originally generated code verifier:

Password Grant Tokens

The OAuth2 password grant allows your other first-party clients, such as a mobile application, to obtain an access token using an email address / username and password. This allows you to issue access tokens securely to your first-party clients without requiring your users to go through the entire OAuth2 authorization code redirect flow.

Creating A Password Grant Client

Before your application can issue tokens via the password grant, you will need to create a password grant client. You may do this using the rinvex:oauth:client Artisan command with the --password option. If you are using [Cortex OAuth](https://github.com/rinvex/cortex-oauth) and you have already run the cortex:install:oauth command, you do not need to run this command:

Requesting Tokens

Once you have created a password grant client, you may request an access token by issuing a POST request to the /oauth/token route with the user's email address and password. Remember, If you are using Cortex OAuth, this route is already registered for you, so there is no need to define it manually. If the request is successful, you will receive an access_token and refresh_token in the JSON response from the server:

**Note: Remember, access tokens are long-lived by default. However, you are free to configure your maximum access token lifetime if needed.

Requesting All Scopes

When using the password grant or client credentials grant, you may wish to authorize the token for all of the scopes supported by your application. You can do this by requesting the * scope. If you request the * scope, the can method on the token instance will always return true. This scope may only be assigned to a token that is issued using the password or client_credentials grant:

Customizing The User Type

If your application uses more than one authentication guards, you may specify which guard the password grant client uses by providing a --user_type option when creating the client via the artisan rinvex:oauth:client --password command. The given guard name should match a valid guard defined in your application's config/auth.php configuration file. You can then protect your route using middleware to ensure that only users from the guard is authorized.

Customizing The Username Field

When authenticating using the password grant, Rinvex OAuth will use the email attribute of your authenticatable model as the "username". However, you may customize this behavior by defining a findForOAuth method on your model:

Customizing The Password Validation

When authenticating using the password grant, Rinvex OAuth will use the password attribute of your model to validate the given password. If your model does not have a password attribute or you wish to customize the password validation logic, you can define a validateForOAuthPasswordGrant method on your model:

Implicit Grant Tokens

The implicit grant is similar to the authorization code grant; however, the token is returned to the client without exchanging an authorization code. This grant is most commonly used for JavaScript or mobile applications where the client credentials can't be securely stored. You can enable the grant by publishing config file using this command php artisan rinvex:publish:oauth --resource=config, then enabling that grant option. It is disabled by default, and not recommended to use since other grants are more secure.

Once the grant has been enabled, developers may use their client ID to request an access token from your application. The consuming application should make a redirect request to your application's /oauth/authorize route like so:

Note: Remember, if you are using Cortex OAuth, you do not need to manually define this route /oauth/authorize as it is already defined by the module.

Client Credentials Grant Tokens

The client credentials grant is suitable for machine-to-machine authentication. For example, you might use this grant in a scheduled job which is performing maintenance tasks over an API.

Before your application can issue tokens via the client credentials grant, you will need to create a client credentials grant client. You may do this using the --client_credentials option of the rinvex:oauth:client Artisan command:

Next, to use this grant type, you need to add the CheckClientCredentials middleware to the $routeMiddleware property of your app/Http/Kernel.php file:

Note: Remember, if you are using Cortex OAuth, you do not need to manually register this middleware CheckClientCredentials as it is already registered for you by the module.

Then, attach the middleware to a route:

To restrict access to the route to specific scopes, you may provide a comma-delimited list of the required scopes when attaching the client middleware to the route:

Retrieving Tokens

To retrieve a token using this grant type, make a request to the /oauth/token endpoint:

Note: Remember, if you are using Cortex OAuth, you do not need to manually define this route /oauth/token as it is already registered for you by the module.

Personal Access Tokens

Sometimes, your users may want to issue access tokens to themselves without going through the typical authorization code redirect flow. Allowing users to issue tokens to themselves via your application's UI can be useful for allowing users to experiment with your API or may serve as a simpler approach to issuing access tokens in general.

Creating A Personal Access Client

Before your application can issue personal access tokens, you will need to create a personal access client. You may do this by executing the rinvex:oauth:client Artisan command with the --personal_access option. If you are using [Cortex OAuth](https://github.com/rinvex/cortex-oauth) and you have already run the cortex:install:oauth command, you do not need to run this command:

After creating your personal access client, place the client's ID and plain-text secret value in your application's .env file:

You can also configure this through the config file, by publishing it first using this command php artisan rinvex:publish:oauth --resource=config, then updating the relevant option:

Managing Personal Access Tokens

Once you have created a personal access client, you may issue tokens for a given user using the createToken method on the App\Models\User model instance. The createToken method accepts the name of the token as its first argument and an optional array of scopes as its second argument:

Protecting Routes

Via Middleware

Rinvex OAuth includes an authentication guard that will validate access tokens on incoming requests. Once you have configured the api guard to use the oauth driver, you only need to specify the auth:api middleware on any routes that should require a valid access token:

Multiple Authentication Guards

If your application authenticates different types of users that perhaps use entirely different Eloquent models, you will likely need to define a guard configuration for each user provider type in your application. This allows you to protect requests intended for specific user providers. For example, given the following guard configuration the config/auth.php configuration file:

The following route will utilize the api:member guard, which uses the members user provider, to authenticate incoming requests:

Note: For more information on using multiple user providers with Rinvex OAuth, please consult the password grant documentation.

Passing The Access Token

When calling routes that are protected by Rinvex OAuth, your application's API consumers should specify their access token as a Bearer token in the Authorization header of their request. For example, when using the Guzzle HTTP library:

Token Scopes

Scopes allow your API clients to request a specific set of permissions when requesting authorization to access an account. For example, if you are building an e-commerce application, not all API consumers will need the ability to place orders. Instead, you may allow the consumers to only request authorization to access order shipment statuses. In other words, scopes allow your application's users to limit the actions a third-party application can perform on their behalf.

Defining Scopes

Scopes are using the underlying abilities defined by silber/bouncer package, which means each scope id must match a valid ability id in your system, and this is where Rinvex OAuth majorly differs than Laravel Passport. Please check creating abilities documentation first before utilizing the scopes feature of Rinvex OAuth.

That way, you've one centralized place to manage all access permissions to all resources.

Note: Remember that the user issuing a new access token, must have the same API request scopes, otherwise access will be prohibited

Default Scope

If a client does not request any specific scopes, you may configure your Rinvex OAuth server to attach default scope(s) to the token in your config file. First you'll need to publish config file:

Then you can update the config option:

Assigning Scopes To Tokens

When Requesting Authorization Codes

When requesting an access token using the authorization code grant, consumers should specify their desired scopes as the scope query string parameter. The scope parameter should be a space-delimited list of scopes:

When Issuing Personal Access Tokens

If you are issuing personal access tokens using the App\Models\User model's createToken method, you may pass the array of desired scopes as the second argument to the method:

Checking Scopes

Rinvex OAuth includes two middleware that may be used to verify that an incoming request is authenticated with a token that has been granted a given scope. To get started, add the following middleware to the $routeMiddleware property of your app/Http/Kernel.php file:

Note: Remember, if you are using Cortex OAuth, you do not need to manually register these middleware CheckScopes and CheckForAnyScope as they're already registered for you by the module.

Check For All Scopes

The scopes middleware may be assigned to a route to verify that the incoming request's access token has all of the listed scopes:

Check For Any Scopes

The scope middleware may be assigned to a route to verify that the incoming request's access token has at least one of the listed scopes:

Checking Scopes On A Token Instance

Once an access token authenticated request has entered your application, you may still check if the token has a given scope as follows:

Consuming Your API With JavaScript

When building an API, it can be extremely useful to be able to consume your own API from your JavaScript application. This approach to API development allows your own application to consume the same API that you are sharing with the world. The same API may be consumed by your web application, mobile applications, third-party applications, and any SDKs that you may publish on various package managers.

Typically, if you want to consume your API from your JavaScript application, you would need to manually send an access token to the application and pass it with each request to your application. However, Rinvex OAuth includes a middleware that can handle this for you. All you need to do is add the CreateFreshApiToken middleware to your web middleware group in your app/Http/Kernel.php file:

Note: You should ensure that the CreateFreshApiToken middleware is the last middleware listed in your middleware stack.

This middleware will attach a laravel_token cookie to your outgoing responses. This cookie contains an encrypted JWT that Rinvex OAuth will use to authenticate API requests from your JavaScript application. The JWT has a lifetime equal to your session.lifetime configuration value. Now, since the browser will automatically send the cookie with all subsequent requests, you may make requests to your application's API without explicitly passing an access token:

Customizing The Cookie Name

If needed, you can customize the laravel_token cookie's name using the corresponding config option. First you'll need to publish the config file using this command php artisan rinvex:publish:oauth --resource=config, then you can modify as follows:

CSRF Protection

When using this method of authentication, you will need to ensure a valid CSRF token header is included in your requests. The default Laravel JavaScript scaffolding includes an Axios instance, which will automatically use the encrypted XSRF-TOKEN cookie value to send a X-XSRF-TOKEN header on same-origin requests.

Note: If you choose to send the X-CSRF-TOKEN header instead of X-XSRF-TOKEN, you will need to use the unencrypted token provided by csrf_token().

Changelog

Refer to the Changelog for a full history of the project.

Support

The following support channels are available at your fingertips:

Contributing & Protocols

Thank you for considering contributing to this project! The contribution guide can be found in CONTRIBUTING.md.

Bug reports, feature requests, and pull requests are very welcome.

Security Vulnerabilities

If you discover a security vulnerability within this project, please send an e-mail to [email protected]. All security vulnerabilities will be promptly contacted.

About Rinvex

Rinvex is a software solutions startup, specialized in integrated enterprise solutions for SMEs established in Alexandria, Egypt since June 2016. We believe that our drive The Value, The Reach, and The Impact is what differentiates us and unleash the endless possibilities of our philosophy through the power of software. We like to call it Innovation At The Speed Of Life. That’s how we do our share of advancing humanity.

License

This software is released under The MIT License (MIT).

(c) 2016-2022 Rinvex LLC, Some rights reserved.


All versions of laravel-oauth with dependencies

PHP Build Version
Package Version
Requires php Version ^8.1.0
ext-json Version *
firebase/php-jwt Version ^6.4.0
illuminate/auth Version ^10.0.0 || ^11.0.0
illuminate/console Version ^10.0.0 || ^11.0.0
illuminate/contracts Version ^10.0.0 || ^11.0.0
illuminate/cookie Version ^10.0.0 || ^11.0.0
illuminate/database Version ^10.0.0 || ^11.0.0
illuminate/http Version ^10.0.0 || ^11.0.0
illuminate/support Version ^10.0.0 || ^11.0.0
league/oauth2-server Version ^8.5.0
lcobucci/jwt Version ^5.0.0
nyholm/psr7 Version ^1.7.0
phpseclib/phpseclib Version ^3.0.0
psr/http-message Version ^2.0.0
rinvex/laravel-support Version ^7.0.0
rinvex/tmp-josephsilber-bouncer Version ^1.0.0
symfony/http-foundation Version ^6.2.0
symfony/psr-http-message-bridge Version ^2.2.0
symfony/console Version ^6.2.0
Composer command for our command line client (download client) This client runs in each environment. You don't need a specific PHP version etc. The first 20 API calls are free. Standard composer command

The package rinvex/laravel-oauth contains the following files

Loading the files please wait ....