Extend user access token in Keycloak with external data - jwt

We use the Keycloak service as SSO solution and provide the resulting JWT to different microservices and that works very well.
But now we have the problem that the JWT must be extended with data from an external resource when the user tries to login.
More tangible, a user has access to different markets with an unique ID as identifier, but we didn't see the management which user have access to which market inside the Keycloak service.
What could be the best solution for this problem?
After reading the docs an custom User Storage SPI is an answer, but I think that is a little bit to much..
As information we use Keycloak 3.1.0 as a standalone service with an postgres DB

The way you add extra data/information to your keycloak JWT token payloads, comes by means of adding "client-scopes" configured with the proper protocol mappers within them, that allows you to add any amount of custom extra information to your Id-token and access-token.
One example of this, would be having extra variables in your users, and then in the protocol mappers within the (newly-created) "client-scope", you can add a protocol-mappers of type "User-Attribute", so that your specific user variable will appear in your token the way you configured on your "protocol-mapper". There are many types of "protocol mappers" that'll allow you to map diverse type information to your tokens (is not just for mapping user variables).
This was addressed on this question before:
Keycloak User Storage SPI Implementation
I'm copying here the part which is relevant to you:
Origianl question was:
[How to]"Retrieve some attributes from external datasource, map it to keycloak's id and access token. Need to retrieve users unique id and add it as subject id in the jwt. That's the id, rest of the services can use to retrieve the id, when this token is passed to other services."
[Answer:]
For this, the best you can do is:
Add those user's unique data as users attributes (see them on the Admin console)
Create a "Client scope" on Keycloak, with a corresponding mapper of type "user property" to map each of those values you'd like to add (from your user data) to your Id-token and access-token. You also need to tie your client with your just created "client scope". This may sound a little bit confusing, but this video is great material and I bilieve it'll help you alot: https://www.youtube.com/watch?v=ZxpY_zZ52kU (arround min 6:30 you'll see how to add extra user info to your tokens)

Related

Keycloak: mapping user information from external IDP. How do I know attribute names?

I have 2 Keycloak instances:
KC1 which is the main Keycloak for my app
KC2 which acts as an IDP (linked to KC1 via SAML protocol)
I'm trying to retrieve users info (email, name and roles, mainly) in KC1 whenever a SSO user (from KC2) connects to my app. As far as I understand this should be done via IDP mappers.
I tried creating multiple ones with the "Attribute Importer" type with no success. The main problem is that attribute name fields are just textboxes. I don't know where to look to get the correct value I should enter here. For instance for email I tried multiple things like "email", "emailAddress", "mail", etc.. (with all possible cases, i.e. all uppercase, all lowercase, camelcase, etc.) but this is just guess work.
Is there a table somewhere telling what we should enter here? Or at least some way to see what is being sent in the claims (everything is very auto-magic so it's hard to know what's going on under the hood).
The documentation ( https://www.keycloak.org/docs/latest/server_admin/index.html#_mappers ) mentions that you can put the log level to debug to see the claims. Couldn't see them personally, so not sure about that.
Edit : found the problem for basic info (I had to create client scopes with the correct protocol, in my case SAML, and then bind it in the client on the KC2 side. Then use the SAML attribute name defined in the client scope mapper).
However, I still struggle for the roles. Do I have to create them on the KC1 side as well?
Edit 2 : Solved. For future reference, the roles can be found in the access token (not the ID token like basic user info), but they have to be mapped in KC1 to be visible there.
However, I still struggle for the roles. Do I have to create them on
the KC1 side as well?
You can't simply import the roles from KC2 directly to KC1. Instead, you have to create the roles that you want in KC1, and in the appropriate IDP configuration section (of KC1) create a External Role to Role Mapper:
Where you map the role that the user has on the external IDP (i.e., KC2) to the one that the user should have in the KC1. Do that for every role that you want to map.
For SAML IdP integrations you can try the same idea but using the Advance Attribute to Role mapper:

Making API requests to a 3rd party that requires authentication

Here is my scenario. Imagine there is a Yoga studio that uses a professional booking and reservation system that exposes an API. Through this API an application can make a reservation for a client. The API takes the client's userid and password to make the reservation. The booking API doesn't use OAuth or any social media sign-ins.
My desire is to create an Assistant Action that would retrieve the list of classes and allow the client to make a booking.
My puzzle is what design/architecture to look towards to supply the userid/password pair required by the booking API.
How have others solved this puzzle?
Should I store the userid/password as "user state" associated with the action?
First, you should have a conversation with the API provider about why they don't provide an OAuth-based solution. This is a security vulnerability waiting to happen, if it hasn't already.
Second, you need to think very carefully about your own risk profile in this case:
Google does not allow you to collect credential information (ie - passwords) through your Action.
Because of this, you must use Account Linking to authenticate them.
This means that you will need something (ie - a database or data store) to manage their account on your side.
This database would be a good place to keep the username/password you need to use for them for the API...
...but it now means that you need to take extreme care about protecting this database.
You don't really say how this API allows for accounts to be created and managed. If these accounts are just used for you (ie - the user doesn't necessarily see them), then you can mitigate some of that risk by treating the username/password as an opaque token that you manage and generate and that the user never sees.
If this is something that the user is aware of, then you'll need to approach the account linking in one of two ways:
Have them log into your service via an app or webapp using this credential info that you will need to save (ack!) and then link to the Assistant using OAuth.
Have them log into your service via an app or webapp using Google Sign-In, which will carry over to your Action. Then have them provide the credential info for the API, which you will need to save (ack!).

Capture IDP User attributes in SAP cloud foundry app via SDK UserAccesor API

I wanted to capture user attributes coming from SAP IDP(Identity & Authentication tenant service like department,salutation ,company etc ,via UserAccessor SDK api,but although those attributes are set and has value in IDP user and all the integration with IDP and sub account is in place post authentication ,user attributes object is empty ,i am only able to retrieve specific attributes like first names ,last name,email address ,user groups etc via JWT and UserAccessor api ,but no luck with other attributes ,in IDP i have mentioned these attributes as well under assertion attributes in SAP Identity authentication tenant .
Please guide and help in this matter .
Thanks Siddharth
Update: As we have now identified the problem, I will update my answer to reflect that. The original answer below is outdated:
Okay so the problem is that you haven't mapped any additional user attributes from your Identity Provider (IdP) to your JWT. As far as I'm aware there are three things you will need to do:
You need to create attributes in your xs-security.json (the file you used to configure your XSUAA service instance). This documentation should explain how to do that.
You need to configure which attributes are exposed by your IdP (in your case the SAP Identity & Authentication service. This documentation looks like a good place to start looking).
You need to map the attributes exposed by your IdP to the attributes defined in your xs-security.json. You will probably need to reconfigure (i.e. delete, recreate and rebind) your XSUAA service instance with the updated config, before you can do this step. Then, navigate to your application in the Cloud Platform Cockpit, from the left toolbar click "Security > Roles" and create your mapping.
Let me know if this works for you!
Original Answer:
As far as I'm aware the default IdP does not support SAML. Without SAML, I'm not sure whether you can propagate any attributes from your IdP into the JWT.
Please also check out this discussion for more information.

Keycloak add extra claims from database / external source

I have not been able to divine the way I might add extra claims from my application database. Given my limited understanding, I see two ways:
After successful authentication have keycloak pull extra claims from the application database somehow. This app database is postgres, for example.
Have the application update the jwt with extra claims using a shared key.
I would like some feedback both paths. I feel that the fist option may be safer. However I am not sure where to begin that implementation journey.
Answering my own question here. I cross-posted this question to the Keycloak users mailing list here (http://lists.jboss.org/pipermail/keycloak-user/2017-April/010315.html) and got an answer that seems reasonable.
This is pasted from the answer I received there.
I use the first option. I do it with a protocol mapper, which is a convenient place to do it because there the token is already built by keycloak but hasn't been signed yet. This is the procedure :
User logs in
My custom protocol mapper gets called, where I overwrite the transformAccessToken method
Here I log in the client where the protocol mapper is in into keycloak, as a service. Here don't forget to use another client ID instead the one you're building the protocol mapper for, you'll enter an endless recursion otherwise.
I get the access token into the protocol mapper and I call the rest endpoint of my application to grab the extra claims, which is secured
Get the info returned by the endpoint and add it as extra claims

How to scope and persist claims to different clients in IdentityServer 3?

I'm new to IdentityServer3 and have multiple MVC clients where users have claims which potentially could conflict and give undesired authorization.
Here is an example with two clients able to send emails and notifications to the users. A user might have access to both applications but should only be able to recieve notifications in Application A. How can we prevent the user from recieving notifications in Application B?
Application A
Claim Type: ApplicationFunctionality Claim Value:
RecieveNotifications
Claim Type: ApplicationFunctionality Claim Value: RecieveEmails
Application B
Claim Type: ApplicationFunctionality Claim Value: RecieveEmails
Would a resonable solution be to implement somekind of logic in a class using the IUserService interface?
Would it be correct to use claims in the way I described above across multiple clients, where we sometimes reuse claims for cross-client functionality. I guess it would require me to namespace the claims (perhaps using the requested scope name the client sends to IdentityServer) in order to distinguish claims for different clients and prevent unauthorized access between the clients.
Here is an example of user claim types/claim values:
Name: John Doe
Email: john.doe#acme.com
PreferedLanguages: English,Swedish,Spanish
ApplicationFunctionality: ClientA.RecieveEmails
ApplicationFunctionality: ClientB.RecieveEmails
ApplicationFunctionality: ClientA.RecieveNotifications
ApplicationFunctionality: ClientB.RecieveNotifications
ApplicationFunctionality: ClientA.ViewBackorders
ApplicationFunctionality: ClientA.DeleteBackorder
ApplicationFunctionality: ClientB.SearchProductInformation
CompanyID: 1145
CompanyID: 6785
CompanyName: Acme Inc
ApplicationLicense: ClientA.PayingNormalUser
ApplicationLicense: ClientB.FreeUser
A user from Company Acme Inc have several CompanyID's which is used when filtering data we request from webservices\databases in the data layer. The user have access to multiple applications where he/she could have different levels of functionality depending on what license they have bought in the applications. Some functionality exist in multiple clients but that doesn't mean the user are authorized to same functionality in all clients he/she have access to.
I would appreciate some guidelines about claims, or perhaps point me to some good resources about the subject. I have read that claims primary is used for identity related information (email, name, department, favorite color, shoe size etc), but if no role\permissions style claims should be used with claims then how should information about what a user is authorized to do in the clients be persisted and how should data be filtered in webservices/databases (resource providers) so the user only sees data he/she are authorized to see?
My first thoughts where that the id_token and access token would be convenient to use since they are issued by the STS (IdentityServer) and then later persisted in cookies. The STS would first be required to perform lookup of user account in Active Directory which contains user identity related information together with an lookup (using the username of the Active Directory user account) in custom database containing information about role\permissions and claims of the user.
How should I persist the roles/permissions and claims of a user if not using cookie persisted tokens provided by IdentityServer?
Clients (applications) and users can have their own set of claims. It looks like you want to have applications which have access to different resources. This is where you should use scopes. Basically define two scopes which define action on that resource (this is one common way of doing it) ie one for 'reading' emails and one for 'writing' emails (eg emails.read and emails.write) subsequently the other scopes can be backorders.read and backorders.delete. It's just good practice to have consistent naming here.
Ok now since weve defined those two scopes, you can now define two clients, one which has only the emails.read scope and the other one has both the read and write scopes. All this means is that one client has access to more resources than the other.
All the user identity claims should stick to the user itself. Application/client specific should never be associated with the user. Name,Email,ApplicationLicense, and PreferredLanguages are all valid claims for the user because they describe the user itself and what can be asserted about them.
For "complex" authorization you may want to look at this sample for some ideas on how to set up compound security policies or authorization.
It sounds like you want to expose a different value to different clients for the same claim. This seems like a logical thing to want to do, especially if you are integrating with clients that are not within your control and thus cannot dictate to them what to expect in each claim, or what scopes to request. A simple example might be the "roles" claim - you may wish to send different values depending on the app that's making the request. If you're joining someone else's enterprise, perhaps with multiple OpenID Connect Providers, you don't always have a choice over the scopes or claim names.
I feel that Nat Sakimura eludes to this in the OpenID Connect FAQ video, https://www.youtube.com/watch?v=Kb56GzQ2pSk (1 minute 40s), the idea that an entity might want to expose a different identity to different clients.
In terms of implementation, we've added a table with [identityId, clientId, attributeName, attributeValue] to allow us to store the same identity attribute for different clients. In our case, these identity attributes become claims in the outgoing JWT. As most attributes about a user are global (i.e. not client specific), we treat the data in this table as overrides to a base set, which saves duplicating the same data for each client unnecessarily. The iUserService.GetProfileDataAsync() method has access to the Client, so can tailor its response depending on the consumer of the data.