Laravel
Authentication for Laravel websites with Authgear and OAuth2
Last updated
Authentication for Laravel websites with Authgear and OAuth2
Last updated
In this guide, you'll learn how to add user authentication to a Laravel app using Authgear as an OIDC provider.
Authgear supports multiple ways to allow users to log in to apps such as passwordless sign-in, phone OTP, and 2FA. In this post, we'll show you how to enable all these options in your Laravel app without worrying about the underlying logic.
How to create an Authgear Application.
How to request OAuth 2.0 authorization code from Authgear.
How to get user info from Authgear using OAuth 2.0 access code.
Link user info from Authgear with Laravel's default Breeze authentication.
To follow along with the example, you should have the following in place:
A free Authgear account. Sign up if you don't have an account yet.
A Laravel project.
The example app we'll build in this post uses the default Laravel Breeze authentication kit. This kit provides the starter code for email and password user authentication systems.
We will be using Authgear to handle and process authentication data instead of the default Breeze database. By doing so, we get all the benefits of Authgear including more security and flexibility.
In this section, we'll walk through the complete steps for building the example app.
Before we can use Authgear as an OAuth identity provider, we need to set up an application on the Authgear portal.
To do that, log in to Authgear then select a project. Next, navigate to the Applications section for your project. Create a new application or configure an existing one with OIDC Client Application as Application Type as shown below:
Once you're done, click on Save to go to the application configuration page. This page reveals the application credentials and OAuth 2.0 endpoints.
Note down details like the Client ID, Client Secret, and the endpoints as you'll use them later in your Laravel project.
While you're still on the application configuration page, scroll down to the URL section then click on Add URI. Enter localhost:8000/oauth/callback
in the text field if you will be running your Laravel app on your local machine. Once you're done, click Save.
The redirect URI we provided above should be a valid page on our Laravel app as Authgear will redirect users to the page after authorization.
Now create a new Laravel project on your computer by running the following command:
Once your project is created, open the project folder in your preferred code editor and replace the content of resources/views/welcome.blade.php
with the following code:
Alternatively, you can create a new index.blade.php
file in the resources folder and add the above code inside it. Then, update the web.php
route file to render the new file instead of welcome.blade.php
.
Next, run the php artisan serve
command in the terminal to test your application. At this point, your application should look like the following screenshot when you access localhost:8000 on a browser:
Breeze is the official user authentication starter kit for Laravel. What that means is that Breeze helps you set up the database, routes, controller, and user interface for a user registration and user login system.
To install Breeze on your Laravel project, run the following command:
After that, run the following command to enable Breeze to set up all the resources for the user authentication system in your project:
During the setup, select blade
as the stack and leave the other options as default.
Once the setup is complete, navigate around your project file structure and you should notice some new folders and files related to authentication were added. Some of these new folders/files include an Auth sub-folder in the controllers folder, another auth sub-folder inside the views folder, and some database migration files.
Before we continue, let's add an extra oauth_uid
field to the users
table migration file. This field will store a user's unique ID from Authgear after successful login.
Open the create_users_table...
file that is inside the database/migrations/
folder (this file will have a date value at the end of its name) and add the following code to a new line inside the Schema::create()
method:
Add the MySQL database DB_DATABASE
, DB_USERNAME
, and DB_PASSWORD
for the database you wish to use with your Laravel project in your Laravel project's .env
file.
Finally, create the users and other tables by running the following command:
In this step, we'll create a new route that will handle the task of redirecting users from our app to Authgear's OAuth authorization page where they can grant our app authorization to their data on Authgear. If you've used other OAuth 2.0 providers before, for example, signing in to a website using Google OAuth, you may already be familiar with an authorization page.
First, create a new controller that will handle all OAuth operations in our Laravel app by running the following command:
Before we start implementing the logic for our new controller, we need to install a PHP OAuth 2.0 client package. This package will simplify the process of interacting with Authgear's OAuth endpoints. Run the following commands to install the package:
Now, back to implementing the controller; open the new OAuthController file (from the app/Http/Controllers
folder) and add the following code to it:
Next, add your Authgear Application's Client ID, Client Secret, and the redirect URI you specified earlier to your Laravel project's .env file using the following keys:
Note: Your Authgear project URL is the hostname of any of your endpoint URLs. For example, the project URL for a project with an authorization endpoint: https://laravel-app.authgear.cloud/oauth2/authorize
will be https://laravel-app.authgear.cloud
.
Now let's create a route in our Laravel project that will call the startAuthorization()
method.
Open the routes/web.php
file and add new routes using the following code:
We've included a second route for the redirect URI (callback), we'll implement this route in the next step.
Before we continue, let's clean up some of the additional routes added by the Breeze package that we won't be needing for this example. Open the routes/auth.php
file and delete the following lines:
At this point accessing the /login
route should redirect to the Authgear authorization page.
Update the empty handleRedirect()
method in OAuthController to the following:
The above code gets the authorization code sent in the redirect URL from Authgear after user authorization and exchanges it for an access token. With this access token, our application can access protected resources like the user info endpoint.
In this step, we'll use the access token we got from the last step to get the current user's info from Authgear.
First, add the following code at the end of the handleRedirect()
method:
The getResourceOwner()
method will call Authgear's UserInfo endpoint.
If you dump the userInfo variable (dd($userInfo)
), you should get an output similar to this:
The above array contains the user's info from Authgear. We'll proceed to use this information to link the Authgear user to a default (Breeze) Laravel authentication account. As a result, our app can start a regular Laravel authenticated user session and allow access to protected routes.
To implement the above feature, find the following line in OAuthController.php:
Add the following code after the above line:
Find the complete code for the OAuthController here.
OAuth 2.0 access tokens expire after some time. The refresh token on the other hand live longer. As a result, you can use the refresh token to request a new access token. In this step, we'll do exactly that in our Laravel application.
First, app/Http/Controllers/ProfileController.php and update the content of the edit() method to the following:
The above code checks if the current access token is expired using the hasExpired()
method. If the condition is true, we call the getAccessToken()
method with the refresh token to get a new access token.
The value of the current access token is updated to the new access token.
Next, this edit() method also displays the current user's profile details from your Authgear project on the UI. To implement this, add the following code to resources/views/profile/edit.blade.php, just below the line with "<div class="max-w-7xl mx-auto sm:px-6 lg:px-8 space-y-6">
":
At this point, if we run our app and click on the login link on the landing page, we should be redirected to the Authgear authorization page. After granting authorization, we are directed to the callback route of our Laravel app. If authentication is successful we should be redirected to the default Breeze-protected dashboard page that looks like this:
To log a user out, we'll delete all existing PHP session data and then call the Authgear token revoke endpoint.
First, add a new logout function to the OAuthController.php file using the following code:
Then, open routes/web.php and update the logout route to the following:
You should try enabling the different login methods on Authgear from the Portal to enjoy features like 2FA, passwordless login, and more without updating anything on the code for your app.
Find the complete code for the example app in our Laravel Example Github repo.