robsontenorio / laravel-keycloak-guard

🔑 Simple Keycloak Guard for Laravel
MIT License
434 stars 141 forks source link

Service account cannot authenticate #100

Closed alanmatiasdev closed 1 year ago

alanmatiasdev commented 1 year ago

We recently migrated to using Keycloak as our central user authentication provider. I have been using the library without any problems to validate users in the apis without any problems. In fact, congratulations to you @robsontenorio.

In one of my applications, a monolith that still stores various information, I set the variable "KEYCLOAK_LOAD_USER_FROM_DATABASE" to true, due to excessive effort in refactoring the entire application to the new format.

The application worked perfectly and, this way, we won't need to rush to kill this legacy application, since the library authenticates users with the application's local database and everything works as before.

But, in a particular scenario, another application needs to fetch information from this monolith through a service account and, with the above variable set to true, the error occurs that the service account user was not found.

This behavior is correct and expected. It is defined right here.

https://github.com/robsontenorio/laravel-keycloak-guard/blob/042483a167bcdc74321dd49cb30b79c6531109bc/src/KeycloakGuard.php#L155-L166

So, how can I allow the service account to access my api when the database user search is active? Is there any way to do this? I thought about opening a pull request to include this case, but I understand that validating with this issue is a good way.

"error": {
        "message": "[Keycloak Guard] User not found. Credentials: {\"email\":\"service-account-api\"}",
        "trace": [
            {
                "file": "\/home\/company\/vendor\/robsontenorio\/laravel-keycloak-guard\/src\/KeycloakGuard.php",
                "line": 47,
                "function": "validate",
                "class": "KeycloakGuard\\KeycloakGuard",
                "type": "->"
            }
                 ]

Thanks.

robsontenorio commented 1 year ago

@bralandealmeida

ServiceAcount are not a “real” user. And for sure it will fail to fetch from database.

See line 156. You can implement your own “user fetch” method. So you can “fake” it when it is ServiceAcount.

It has a mention on README

alanmatiasdev commented 1 year ago

Thanks @robsontenorio. This worked perfectly!