{"id":14974715,"url":"https://github.com/rootinc/laravel-azure-middleware","last_synced_at":"2025-04-05T08:06:10.559Z","repository":{"id":46230033,"uuid":"94790939","full_name":"rootinc/laravel-azure-middleware","owner":"rootinc","description":null,"archived":false,"fork":false,"pushed_at":"2023-07-13T13:23:21.000Z","size":109,"stargazers_count":95,"open_issues_count":11,"forks_count":38,"subscribers_count":10,"default_branch":"master","last_synced_at":"2025-03-29T07:05:21.356Z","etag":null,"topics":["azure","azure-active-directory","laravel","laravel-framework","php"],"latest_commit_sha":null,"homepage":null,"language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/rootinc.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2017-06-19T15:17:35.000Z","updated_at":"2025-03-06T19:59:33.000Z","dependencies_parsed_at":"2024-06-19T00:19:42.448Z","dependency_job_id":"5d6696ef-d536-4f41-917b-b79ce3b4fcf0","html_url":"https://github.com/rootinc/laravel-azure-middleware","commit_stats":{"total_commits":56,"total_committers":16,"mean_commits":3.5,"dds":0.75,"last_synced_commit":"252cefa4efc545cfa284c14ddfd0599078c3ee3c"},"previous_names":[],"tags_count":26,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rootinc%2Flaravel-azure-middleware","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rootinc%2Flaravel-azure-middleware/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rootinc%2Flaravel-azure-middleware/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rootinc%2Flaravel-azure-middleware/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/rootinc","download_url":"https://codeload.github.com/rootinc/laravel-azure-middleware/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247305933,"owners_count":20917208,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["azure","azure-active-directory","laravel","laravel-framework","php"],"created_at":"2024-09-24T13:50:58.720Z","updated_at":"2025-04-05T08:06:10.531Z","avatar_url":"https://github.com/rootinc.png","language":"PHP","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Laravel Azure Middleware\n\nProvides Azure Authentication Middleware for a Laravel App.  If you like this, checkout \u003ca href=\"https://github.com/rootinc/laravel-saml2-middleware\"\u003eLaravel Saml Middleware\u003c/a\u003e\n\n## Normal Installation\n\n1. `composer require rootinc/laravel-azure-middleware`\n2. run `php artisan vendor:publish --provider=\"RootInc\\LaravelAzureMiddleware\\AzureServiceProvider\"` to install config file to `config/azure.php`\n3. In our routes folder (most likely `web.php`), add\n```php\nRoute::get('/login/azure', '\\RootInc\\LaravelAzureMiddleware\\Azure@azure')\n    -\u003ename('azure.login');\nRoute::get('/login/azurecallback', '\\RootInc\\LaravelAzureMiddleware\\Azure@azurecallback')\n    -\u003ename('azure.callback');\n```\n\u003e NOTE: Only need the route names if configuring `redirect_uri` in the portal.\n4. In our `App\\Http\\Kernel.php` add `'azure' =\u003e \\RootInc\\LaravelAzureMiddleware\\Azure::class,` most likely to the `$routeMiddleware` array.\n5. In our `.env` add `AZURE_TENANT_ID, AZURE_CLIENT_ID, AZURE_CLIENT_SECRET and AZURE_RESOURCE`.  We can get these values/read more here: https://portal.azure.com/ (Hint: AZURE_RESOURCE should be https://graph.microsoft.com)\n6. As of 0.8.0, we added `AZURE_SCOPE`, which are permissions to be used for the request.  We can read more about these here: https://docs.microsoft.com/en-us/graph/api/resources/users?view=graph-rest-1.0\n7. We also added an optional `AZURE_DOMAIN_HINT` that can be used to help users know which email address they should login with.  More info here: https://azure.microsoft.com/en-us/updates/app-service-auth-and-azure-ad-domain-hints/\n8. Within our app on https://portal.azure.com/ point `reply url` to the `/login/azurecallback` route with the full url (ex: http://thewebsite.com/login/azurecallback).\n9. Add the `azure` middleware to your route groups on any routes that needs protected by auth and enjoy :tada:\n10. If you need custom callbacks, see [Extended Installation](#extended-installation).\n\n\u003eNOTE: ~~You may need to add premissions for (legacy) Azure Active Directory Graph~~ As of 0.8.0, we are using v2 of Azure's login API, which allows us to pass scopes, or permissions we'd like to use.\n\n## Routing\n\n`Route::get('/login/azure', '\\RootInc\\LaravelAzureMiddleware\\Azure@azure')-\u003ename('azure.login');` First parameter can be wherever you want to route the azure login.  Change as you would like.\n\n`Route::get('/login/azurecallback', '\\RootInc\\LaravelAzureMiddleware\\Azure@azurecallback')-\u003ename('azure.callback');` First parameter can be whatever you want to route after your callback.  Change as you would like.\n\n`Route::get('/logout/azure', '\\RootInc\\LaravelAzureMiddleware\\Azure@azurelogout')-\u003ename('azure.logout);` First parameter can be whatever you want to route after your callback.  Change as you would like.\n\n\u003e NOTE: Only need the route names if configuring `redirect_uri` in the portal.\n\n### Front End\n\nIt's best to have an Office 365 button on your login webpage that routes to `route('azure.login')`.  This can be as simple as an anchor tag like this `\u003ca href=\"{{ route('azure.login') }}\" class=\"officeButton\"\u003e\u003c/a\u003e`\n\n## Extended Installation\n\nThe out-of-the-box implementation let's you login users.  However, let's say we would like to store this user into a database, as well as login the user in with Laravel Auth.  There are two callbacks that are recommended to extend from the Azure class called `success` and `fail`. The following provides information on how to extend the Root Laravel Azure Middleware Library:\n\n1. To get started (assuming we've followed the [Normal Installation](#normal-installation) directions), create a file called `AppAzure.php` in the `App\\Http\\Middleware` folder.  You can either do this through `artisan` or manually.\n2. Add this as a starting point in this file:\n\n```php\n\u003c?php\n\nnamespace App\\Http\\Middleware;\n\nuse Illuminate\\Http\\Request;\n\nuse RootInc\\LaravelAzureMiddleware\\Azure as Azure;\nuse Microsoft\\Graph\\Graph;\nuse Microsoft\\Graph\\Model;\n\nuse Auth;\n\nuse App\\Models\\User;\n\nclass AppAzure extends Azure\n{\n    protected function success(Request $request, $access_token, $refresh_token, $profile)\n    {\n        $graph = new Graph();\n        $graph-\u003esetAccessToken($access_token);\n\n        $graph_user = $graph-\u003ecreateRequest(\"GET\", \"/me\")\n                      -\u003esetReturnType(Model\\User::class)\n                      -\u003eexecute();\n\n        $email = strtolower($graph_user-\u003egetUserPrincipalName());\n\n        $user = User::updateOrCreate(['email' =\u003e $email], [\n            'name' =\u003e $graph_user-\u003egetGivenName() . ' ' . $graph_user-\u003egetSurname(),\n        ]);\n\n        Auth::login($user, true);\n\n        return parent::success($request, $access_token, $refresh_token, $profile);\n    }\n}\n```\n\nThe above gives us a way to add/update users after a successful handshake.  `$profile` contains all sorts of metadata that we use to create or update our user.  More information here: https://docs.microsoft.com/en-us/azure/active-directory/develop/active-directory-protocols-oauth-code#jwt-token-claims . The default implementation redirects to the intended url, or `/`, so we call the parent here.  Feel free to not extend the default and to redirect elsewhere.\n\n3. Our routes need to be updated to the following:\n\n```php\nRoute::get('/login/azure', '\\App\\Http\\Middleware\\AppAzure@azure')\n    -\u003ename('azure.login');\nRoute::get('/login/azurecallback', '\\App\\Http\\Middleware\\AppAzure@azurecallback')\n    -\u003ename('azure.callback');\nRoute::get('/logout/azure', '\\App\\Http\\Middleware\\AppAzure@azurelogout')\n    -\u003ename('azure.logout');\n```\n\n4. Finally, update `Kernel.php`'s `azure` key to be `'azure' =\u003e \\App\\Http\\Middleware\\AppAzure::class,`\n\n## Other Extending Options\n\n#### Callback on Every Handshake\n\nAs of v0.4.0, we added a callback after every successful request (handshake) from Azure.  The default is to simply call the `$next` closure.  However, let's say we want to update the user.  Here's an example of how to go about that:\n\n```php\n\u003c?php\n\nnamespace App\\Http\\Middleware;\n\nuse Illuminate\\Http\\Request;\n\nuse Closure;\n\nuse RootInc\\LaravelAzureMiddleware\\Azure as Azure;\n\nuse Auth;\nuse Carbon\\Carbon;\n\nuse App\\User;\n\nclass AppAzure extends Azure\n{\n    protected function handlecallback(Request $request, Closure $next, $access_token, $refresh_token)\n    {\n        $user = Auth::user();\n\n        $user-\u003eupdated_at = Carbon::now();\n\n        $user-\u003esave();\n\n        return parent::handlecallback($request, $next, $access_token, $refresh_token);\n    }\n}\n```\n\nBuilding off of our previous example from [Extended Installation](#extended-installation), we have a user in the Auth now (since we did `Auth::login` in the success callback).  With the user model, we can update the user's `updated_at` field.  The callback should call the closure, `$next($request);` and return it.  In our case, the default implementation does this, so we call the parent here.\n\n#### Custom Redirect\n\nAs of v0.6.0, we added the ability to customize the redirect method.  For example, if the session token's expire, but the user is still authenticated with Laravel, we can check for that with this example:\n\n```php\n\u003c?php\n\nnamespace App\\Http\\Middleware;\n\nuse Illuminate\\Http\\Request;\n\nuse RootInc\\LaravelAzureMiddleware\\Azure as Azure;\n\nuse Auth;\n\nclass AppAzure extends Azure\n{\n    protected function redirect(Request $request)\n    {\n        if (Auth::user() !== null)\n        {\n            return $this-\u003eazure($request);\n        }\n        else\n        {\n            return parent::redirect($request);\n        }\n    }\n}\n```\n\n#### Different Login Route\n\nAs of v0.4.0, we added the ability to change the `$login_route` in the middleware.  Building off [Extended Installation](#extended-installation), in our `AppAzure` class, we can simply set `$login_route` to whatever.  For example:\n\n```php\n\u003c?php\n\nnamespace App\\Http\\Middleware;\n\nuse RootInc\\LaravelAzureMiddleware\\Azure as Azure;\n\nclass AppAzure extends Azure\n{\n    protected $login_route = \"/\";\n}\n```\n\nThe above would now set `$login_route` to `/` or root.\n\n#### Getting / Overriding the Azure Route\n\nAs of v0.7.0, we added the ability to get the Azure URL.  For example, let's say we wanted to modify the Azure URL so that it also passed the user's email to Azure as a parmater.  Building off [Extended Installation](#extended-installation), in our `AppAzure` class, we could do something like this:\n\n```php\n\u003c?php\n\nnamespace App\\Http\\Middleware;\n\nuse Illuminate\\Http\\Request;\n\nuse RootInc\\LaravelAzureMiddleware\\Azure as Azure;\n\nuse Auth;\n\nclass AppAzure extends Azure\n{\n    //we could overload this if we wanted too.\n    public function getAzureUrl()\n    {\n        $url = $this-\u003ebaseUrl . config('azure.tenant_id') . $this-\u003eroute2 . \"authorize?response_type=code\u0026client_id=\" . config('azure.client.id') . \"\u0026domain_hint=\" . urlencode(config('azure.domain_hint')) . \"\u0026scope=\" . urldecode(config('azure.scope'));\n\n        return Route::has('azure.callback') ? $url . '\u0026redirect_uri=' . urlencode(route('azure.callback')) : $url;\n    }\n\n    public function azure(Request $request)\n    {\n        $user = Auth::user();\n\n        $away = $this-\u003egetAzureUrl();\n\n        if ($user)\n        {\n            $away .= \"\u0026login_hint=\" . $user-\u003eemail;\n        }\n\n        return redirect()-\u003eaway($away);\n    }\n}\n```\n\n#### Using in a Multi-Tenanted Application\n\nIf the desired use case requires a multi-tenanted application you can simply provide `common` in the .env file instead of a Tenant ID. eg. `AZURE_TENANT_ID=common`.\n\nThis works by sending your end users to the generic login routes provided by Microsoft and for all intents and purposes shouldn't appear any different for development either. It should be known that there some inherent drawbacks to this approach as mentioned by in the MS Dev docs here:\n\u003e When a single tenant application validates a token, it checks the signature of the token against the signing keys from the metadata document. This test allows it to make sure the issuer value in the token matches the one that was found in the metadata document.\n\u003eBecause the /common endpoint doesn’t correspond to a tenant and isn’t an issuer, when you examine the issuer value in the metadata for /common it has a templated URL instead of an actual value...\n\nAdditional information regarding this can be found [here](https://docs.microsoft.com/en-us/azure/active-directory/develop/howto-convert-app-to-be-multi-tenant#update-your-code-to-handle-multiple-issuer-values).\n\n## Testing with Laravel Azure Middleware\n\nAs of v0.7.0, we added integration with Laravel's tests by calling `actingAs` for HTTP tests or `loginAs` with Dusk.  This assumes that we are using the `Auth::login` method in the success callback, shown at [Extended Installation](#extended-installation).  There is no need to do anything in our `AppAzure` class, unless we needed to overwrite the default behavior, which is shown below:\n\n```php\n\u003c?php\n\nnamespace App\\Http\\Middleware;\n\nuse Illuminate\\Http\\Request;\n\nuse RootInc\\LaravelAzureMiddleware\\Azure as Azure;\n\nuse Auth;\n\nclass AppAzure extends Azure\n{\n    //this is the default behavior\n    //overwrite to meet your needs\n    protected function handleTesting(Request $request, Closure $next)\n    {\n        $user = Auth::user();\n\n        if (!isset($user))\n        {\n            return $this-\u003eredirect($request, $next);\n        }\n\n        return $this-\u003ehandlecallback($request, $next, null, null);\n    }\n}\n```\n\nThe above will call the class's redirect method, if it can't find a user in Laravel's auth.  Otherwise, the above will call the class's handlecallback method.  Therefore, tests can check if the correct redirection is happening, or that handlecallback is working correctly (which by default calls `$next($request);`).\n\n## Contributing\n\nThank you for considering contributing to the Laravel Azure Middleware! To encourage active collaboration, we encourage pull requests, not just issues.\n\nIf you file an issue, the issue should contain a title and a clear description of the issue. You should also include as much relevant information as possible and a code sample that demonstrates the issue. The goal of a issue is to make it easy for yourself - and others - to replicate the bug and develop a fix.\n\n## License\n\nThe Laravel Azure Middleware is open-sourced software licensed under the [MIT license](http://opensource.org/licenses/MIT).\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frootinc%2Flaravel-azure-middleware","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Frootinc%2Flaravel-azure-middleware","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frootinc%2Flaravel-azure-middleware/lists"}