Keycloak: How can user be filtered for a specific OIDC client by role? - keycloak

We have one realm with many users and multiple OIDC clients configured. We would like to connect another application (OIDC Client) to the realm. Unfortunately, the client cannot check for any attributes or roles to be present.
How can I configure Keycloak to authenticate with a specific OIDC-client but return failing authentication if users have not a specific role?

Generally this type of option will not work, since authorization redirects occur before you know who the user is, and therefore before you know which roles are involved.
WHAT I WOULD DO
Make an authorization redirect perform only the following job:
Signing in the user and returning the user id (sub claim), along with perhaps a couple of scopes
Then manage roles within your app - the second app should call a Web API that does this:
Get claims from the access token, and also from other sources, then use them for identification and authorization
If a user authenticates but is not entitled to use a particular app, detect this via an API call, then present an Access Denied page in the app after login.

To reach this you should implement the AuthenticatorFactory and Authenticator interfaces of Keycloak. Look here for more infos.
In the authenticate() method you will write something similar to this:
If(client == yourClient){
// Check for roles
}
Otherwise, expected behaviour in case of failure.

Related

Flask-OIDC | How to call a specific function after the user logged in

I built a login system using Flask OIDC and Keycloak. In my system, there is some endpoints decorated with oidc.require_login() that calls the Keycloak login page.
My goal is, after the user successfully logged in, my system checks if the user name exists in a specific database.
How can I set a function to be called every time someone successfully logged in with Keycloak and do this verification at the database?
According to your needs there are several ways to create the user in the backend.
The easiest way would be to just check the JWT token on every request. OIDC is based on JWT and that token is available on any request (which should already be done to find user roles etc). So your application can check that JWT and extract the username from it (see here for details about the JWT format). With the username you can check your internal database and create the user, if it doesnt exist. But at that time you'll not have access to any user credentials any more. It is just SSO and you need to trust Keycloak and the JWT... Also - you'll never be informed, if the user will be deleted in Keycloak, which could be an issue.
There is a callback API in Keycloak in form of the Admin URL per client. But the documentation is not clear. It says: It’s used by the Keycloak server to send backend requests to the application for various tasks, like logout users or push revocation policies. But I cannot find a complete list of "tasks". I saw only logout events. see Keycloak documentation and the documentation only talks about that. If I add an admin url to a test client, I did not get any requests at login time.
a different but more complicated way would be to create your own UserStorage SPI in Keycloak. It would be Java of course, but only some classes. There is an HTTP example or have a look at the LDAP user storage SPI, which supports registration too. If you choose that for your realm and a user tries to login to Keycloak (Login form), the SPI can call your backend to check the user. It also could be "used" to create the user in the backend by checking the Keycloak local storage and only if there is a local Keycloak user, call the backend. That isn't the reason, why you should implement the UserStorage SPI, but it's possible. If you think, this is a good idea, I would prefer to use your backend storage as the one and only storage or build a different one, that then could call your real backend in case of a new user. I would use this one by not using Keycloak local stored users but, by using your own database.
next (maybe last one). You can write an EventListener SPI to read all events and only filter the login events, see here and here. I think, that would be the easiest one. But be aware. In that case, the HTTP call to your backend coming from the event itself is based on a normal HTTP request (without OIDC at that time).
The last two examples create a JAR (which is explained in the links). That JAR with the SPI must be deployed in keycloaks standalone/deployments folder. The EventListener should be active by default, the UserStorage SPI must be activated per realm.
But - be aware - Keycloak/SSO/JWT - should not be used by creating users in multiple backends. Syncing the users between all backends in a SSO environment is maybe the wrong way. Most information is located in the JWT or can be called by a backend from one central user identity management. Do not store a user more then once. If you need the user reference in your backend - link just to the username or userid (string) instead of a complete entity.
There is no direct way of doing this, other sotfware like Openam, Okta allow you to trigger specific flows in a post-login configuration.
In keycloak, you can try to create your custom authn flow(using Default Identity Provider, its the only option that allow a redirect), and then select this flow in your Identity provider in post login flow.
The idea here is that after login, the user will be redirected to a link ( an api call that will verify his presence on the external database, and sent him back to keycloak once the verification is done.
More info here

Cognito User Pool and AWS Gateway - How to configure a different set of user permissions with one app client?

I am trying to understand the use of access tokens to authorize an API fronted by API Gateway.
My current understanding of the process is as follows:
After setting up a Cognito User Pool, I can define a resource server and associated scopes (e.g. https://wibble-api.com/read, https://wibble-api.com/full).
Then, I can select the allowed custom scopes for a user pool app client.
In AWS Gateway, I can create a Cognito Authorizer to authorize incoming requests.
For each AWS Gateway resource, I can go into the Method Request and select the Cognito Authorizer and determine which OAuth scopes are necessary in order to be able to execute the API method e.g. I can enter https://wibble-api.com/read, https://wibble-api.com/full to indicate that either of those two scopes are sufficient to be allowed to execute the API resource.
When using the hosted UI, the scope parameter will include all of the allowed scopes configured for that app client, and the returned access token (if using implicit grant) will contain those scopes as part of the JWT.
What I don't understand is, I have what must be a very common scenario where I want to be able to give the read-only scope to, say, a user that hasn't paid for the service, and the full scope to a user that has paid. Yet it looks like I would need to have two separate app clients if I'm going to be using the Hosted UI, because there doesn't seem to be a way to return different scopes depending on, say, what group the user has been assigned, or some other metadata in their user profile such as department, etc. I won't know what sort of user they are until after they have been authenticated, but I still need to enter the exact scope when I am authenticating. Is there a solution for this, please?

Is there a way to authorize users with existing account only?

Iam working on a flutter mobile application where i use Google SignIn for Auth, is there a way to authorize users with existing account only?
Prevent users from creating new accounts? I've looked for the same thing without finding a way to do this with any Firebase project setting.
The solution, I believe, is consider the difference between authentication and authorization. Firebase's Authentication service is aptly named. It does authentication
- validates that a user is actually who they claim to be. It does not do authorization - control what actions authenticated users are allowed to perform or what data they can access within an application. App developers have to be responsible for managing user authorization.
One way to do this is to maintain a collection of "authorized users" in Firestore, for example. When a user authenticates, your app would perform a lookup to see if the current user is actually authorized or not. Security rules can be written for Firestore and Firebase Cloud Storage to also validate that the current user is in the "authorized users" collection before allowing access to data. But this requires extra data queries to obtain this authorization info.
The authorization method I prefer is to use Custom Claims which can be assigned using the Firebase Admin library. A custom claim can be added to an existing user account that can act as a flag indicating what type of authorization they're granted. Front-end code can check the authentication token they've been issued for the custom claim to determine the authorization they've been granted. Server-side code and security rules can also check for those required custom claims within submitted requests.
Realistically, any application you build where different users might have different levels of access will require you to deal with authorization. I believe that assigning carefully thought-out custom claims is the best solution.

KEYCLOAK: Obtaining Access token by 'user name' only (without password)

I have a question regarding Keycloak and obtaining an Access Token.
Our setup is as follows:
· users are created and maintained in Keycloak
· resources, policies and permissions are also maintained in Keycloak
Our use case is:
As a third party application, I want to obtain authorization information (e.g. resource- and scope-based permissions) for a specific user by only providing the username to Keycloak, so I can allow or prohibit further actions.
To be more specific:
In our application the need to validate each request to other services based on the access token.But we have only the user name with us.
The question is now:
> How can we obtain an access token for the user by only knowing the username ?
>
Is there a solution to obtain an access token for such a user?
You don't specify in your question if the current user is logged in. Are you validating user specific actions, or you want to retrieve user roles for the application instead?
The user is logged in and he is performing some action
I suppose you're using some keycloak adapter. Then just retrieve the session object and you should have the extra info somewhere in there.
If not, you can just parse the request yourself. When using OpenId Connect, the access token is always sent for each of the requests, in the Authorization header. The token is base64 encoded, you can decode the token yourself.
The application is performing some action for some registered user, without him logged in
User access tokens are meant to provide permissions for users. As you say in your question: As a third party application, I want... so here you are not acting as a logged user, but as an application, so you need to go with client credentials instead. Just give the client permissions to list all the users and their roles (probably it's enough with the view-users role, see the link below) and log in with client credentials grant. Then you can handle fine grained permissions in your application business logic.
See also:
Keycloak Client Credentials Flow Clarification
Keycloak spring security client credential grant
How to get Keycloak users via REST without admin account
For those who really needs to impersonate a user from a client, there is a new RFC for this : token-echange.
Keycloak loosely implement it at the time of this answer
See particularly https://www.keycloak.org/docs/latest/securing_apps/#direct-naked-impersonation

keycloak - realm resolution based on username (email address)

I'm working on a multi tenant project where usernames are actually their email addresses and the domain of the email serves as a tenant identifier.
Now in keycloak I'll have different realms per tenant, but I want to have a single login page for all tenants and the actual realm that will do the authentication to be somehow resolved by the username (email address).
How do I go about doing that?
I found a thread on the mailing list (that I cant find now...) that discussed the same problem. It was something along the lines of - create a main realm that will "proxy" to the others, but I'm not quite sure how to do that.
I think Michał Łazowik's answer is on the right track, but for Single-Sign-On to work, it needs to be extended a little.
Keep in mind that because of KEYCLOAK-4593 if we have > 100 realms we may have to have multiple Keycloak servers also.
We'll need:
A separate HTTP server specifically for this purpose, auth-redirector.example.com.
An algorithm to determine the Keycloak server and realm from a username (email address).
Here would be the entire OAuth2 Authorization Code Flow:
An application discovers the user wants to log in. Before multiple realms, the realm's name would be a constant, so the application would redirect to:
https://keycloak.example.com/auth/realms/realname/protocol/openid-connect/auth?$get_params
Instead, it redirects to
https://auth-redirector.example.com/?$get_params
auth-redirector determines if it itself has a valid access token for this session, perhaps having to refresh the access token first from the Keycloak server that issued it (the user could have logged out and is trying to login as a different user that is served by a different realm).
If it has an valid access token we can determine the Keycloak server and realm from the username or email address in the access token and redirect to:
https://$keycloak_server/auth/$realm/realname/protocol/openid-connect/auth?$get_params
from here, the OAuth2 Authorization Code Flow proceeds as usual.
Else if it doesn't have a a valid access token, the auth-redirector stores the original app's $get_params as session data. It presents a form to the user asking for a username. When the user submits that, we can determine the Keycloak server and realm to use and then auth-redirector itself logs in to the Keycloak server using its own $get_params. Once the auth-redirector gets a call-back, it retrieves the access+refresh token from the Keycloak server and stores them in session data. It then, finally, redirects back to that same keycloak server and realm with the callers original $get_params (from session data). And the OAuth2 Authorization Code Flow proceeds as usual.
This is definitely a hack! But I think it could work. I'd love to try it out some day, time permitting.
Other hacks/solutions are needed for other OAuth2 flows...
The idea from the mailing list is to write a service (let's say auth-redirector.example.com) that has a single input field for email, finds realm based on domain and redirects to that realm's keycloak endpoint (e.g. auth.example.com/auth/realms/realm-name/etc…) while keeping all GET params.
You can find examples of direct login/registration URLs here: https://lists.jboss.org/pipermail/keycloak-user/2016-July/007045.html
One usability problem is that users would have to provide their email twice, I have not yet found a way to pass the username via the login URL.