How to add custom attributes to bearer-only clients - keycloak

I'm using keycloak-connect (nodejs) for my backend with a bearer-only profile. The frontend is a client with a public profile:
1 - How can I add some private custom attributes in userInfo that are only accessible by the backend (bearer-only) ?
I'm adding some attributes to the client that can only be seen by the backend, plus I don't want to add them to the token so I wont have a huge token size.
2 - How are sessions used with keycloak-connect ? I don't see anything stored by keyclaok when I inspect my store (redis) and I didn't find anything in the documentation.
3 - When performing online validation, Is grantmanager.validateAccessToken sufficient to get the userInfo or do I also need to use grantmanager.userInfo ? because 2 requests are a little bit costly
Thank you

Related

Spring boot oauth2 integration with keycloak using Spring webflux along with multi-tenancy

I need to implement Authentication & Authorization using spring boot oauth2 with keycloak as a provider.
I also need to support muti-tenancy. I tried example with authentication using spring-boot-starter-auth2-client to authenticate, but not able to add multi-tenancy.
When I used spring-boot-starter-auth2-client, I need to configure hardcode keycloak urls(specific to one tenant) in properties and not able to support multi-tenancy.
I also analyze spring-boot-starter-auth2-resouce-server, but not clear. I understand that resouce server use for validation of token and expiry.
Note: I don't want to use keycloak adapter library which is provided by keycloak.
Could you please help me -
Where need to use spring-boot-starter-oauth2-client and spring-boot-starter-oauth2-resouce-server?
Is spring-boot-starter-oauth2-resouce-server also use to authentication?
How to authenticat user using spring-boot-starter-oauth2-client and pass to spring-boot-starter-oauth2-resouce-server for authorization.
How to implement multi-tenacy e.g. take tenant id from url and redirect user to tenant specific keycloak login page.
I tried some example but won't succeed, working example will be helpful with -
Spring Webflux + spring-boot-starter-oauth2-client+ spring-boot-starter-oauth2-resouce-server + multi-tenancy + keycloak as a provider.
Thanks & Regards,
Pravin Nawale
tried some example found on internet, but didn't work.
This question should not be answered because:
it is actually a container for many questions
quite a few are way too wide or lack precision.
But as it seems to be a first question... (break it down next time, give more details and edit your question when you get comments asking precisions)
1. Where need to use spring-boot-starter-oauth2-client and spring-boot-starter-oauth2-resouce-server?
This one is important to start with as I suspect you lack OAuth2 background, specifically regarding involved parties and how it is implemented with spring-security:
spring-boot-starter-oauth2-client is to be used with OAuth2 clients:
apps serving UI with oauth2Login (#Controllers with methods returning template names)
apps consuming REST APIs with auto-configured Spring client: WebClient, #FeignClient, RestTemplate
spring-boot-starter-oauth2-resouce-server is to be used with resource-servers: apps serving REST APIs (#RestController or #Controller with #ResponseBody)
Now, if your app has controllers for both the resources and the UI to manipulate it (with Thymeleaf or any other server-side rendering engine), then define two different security filter-chains: one for each, ordered, and with securityMatcher in the first in order to limit the routes it applies to (the second being used as fallback for unmatched routes). Sample in this answer (the sample is for servlet, but it's the exact same principles): Use Keycloak Spring Adapter with Spring Boot 3
2. Is spring-boot-starter-oauth2-resouce-server also use to authentication?
OAuth2 requests should be authorized with an Authorization header containing a Bearer access-token.
The client is responsible for acquiring such an access-token from the authorization-server before sending requests to resource-server.
Your question is not quite clear but here are a few statements which could answer:
resource-server should return 401 (unauthorized) and not 302 (redirect to login) when authorization is missing or invalid => do not configure oauth2Login in resource-server filter-chain. Again, this is client business
resource-server is responsible for resources access-control: check that access-token is valid, that the user has required authorities, etc.
3. How to authenticat user using spring-boot-starter-oauth2-client and pass to spring-boot-starter-oauth2-resouce-server for authorization.
This question is not focused enough to get a single answer: what kind of client? what kind of request? context?
I see three main cases here:
the UI is rendered on Spring server with Thymeleaf, JSF, and alike => use spring's oauth2Login and refer to its documentation to overrides defaults and implement your authorization-server selection logic
the UI is rendered in the browser (Angular, React, Vue, ...) and you are ok to make it an OAuth2 client => find a certified client lib for your framework and implement the logic in the client (angular-auth-oidc-client, for instance, supports multi-tenancy)
the UI is rendered in the browser, but you prefer to implement the Backend For Frontend pattern to hide tokens from browser, then choose a BFF (like spring-cloud-gateway with tokenRelay filter) and refer to its doc for implementing your logic in it
If that can be of any help, I have:
here a tutorial for configuring an app with a Thymeleaf UI client and REST API
there a sample repo with an Angular workspace (app configured as OIDC client + API client lib generated from OpenAPI spec) and spring-boot resource-server (using servlet, but this makes no difference to the client).
4. How to implement multi-tenacy e.g. take tenant id from url and redirect user to tenant specific keycloak login page
Note
One of key principles of OAuth2 is that identities (tokens) are emitted (issued) by trusted 3rd parties (authorization-servers) => you must configure the list of issuers your resource-servers can trust (and clients can fetch tokens from). This list is static (loaded with conf at startup).
Accept identities from various issuers on the resource-server
This is done by overriding the default ReactiveAuthenticationManagerResolver<ServerWebExchange> in your SecurityWebFilterChain configuration: http.oauth2ResourceServer().authenticationManagerResolver(authenticationManagerResolver)
I provide with thin wrappers around spring-boot-starter-oauth2-resource-server which support multi-tenancy just by defining properties. Complete sample there:
Instead of spring-boot-starter-oauth2-resource-server (which is a transient dependency):
<dependency>
<groupId>com.c4-soft.springaddons</groupId>
<artifactId>spring-addons-webflux-jwt-resource-server</artifactId>
</dependency>
Instead of all your resource-server Java conf (unless you want access control from configuration and not with method-security, in which case, you'd have to define an AuthorizeExchangeSpecPostProcessor bean here). Of course, you'll have to add here a client filter-chain with a restrictive securityMatcher if you also serve UI client with oauth2Login:
#EnableReactiveMethodSecurity
#Configuration
public class SecurityConfig {
}
Instead of spring.security.oauth2.resourceserver properties:
com.c4-soft.springaddons.security.issuers[0].location=https://localhost:8443/realms/realm-1
com.c4-soft.springaddons.security.issuers[0].authorities.claims=realm_access.roles,resource_access.client-1.roles,resource_access.client-2.roles
com.c4-soft.springaddons.security.issuers[1].location=https://localhost:8443/realms/realm-2
com.c4-soft.springaddons.security.issuers[1].authorities.claims=realm_access.roles,resource_access.client-1.roles,resource_access.client-2.roles
# Comma separated list of routes accessible to anonymous
com.c4-soft.springaddons.security.permit-all=/api/v1/public/**,/actuator/health/readiness,/actuator/health/liveness
# Fine-grained CORS configuration can be set per path as follow:
com.c4-soft.springaddons.security.cors[0].path=/api/**
com.c4-soft.springaddons.security.cors[0].allowed-origins=https://localhost,https://localhost:8100,https://localhost:4200
# this are defaults and can be omitted
com.c4-soft.springaddons.security.cors[0].allowedOrigins=*
com.c4-soft.springaddons.security.cors[0].allowedMethods=*
com.c4-soft.springaddons.security.cors[0].allowedHeaders=*
com.c4-soft.springaddons.security.cors[0].exposedHeaders=*
If you don't want to use "my" wrappers, just copy from the source, it is open.
Redirect the user to the right authorization-server from client UI
As explained at point 3., this depends on the kind of client, used framework and if BFF pattern is applied or not
5. I tried some example but won't succeed, working example will be helpful with - Spring Webflux + spring-boot-starter-oauth2-client + spring-boot-starter-oauth2-resouce-server + multi-tenancy + keycloak as a provider
With all the elements above and linked resources, you should have enough to find your own path

Quarkus, Keycloak and OIDC token refresh

I’m currently working on a PoC with multiple Quarkus services and Keycloak RBAC. Works like a charm, easily to bootstrap and start implementing features.
But I encountered an issue that I could not solve in my mind. Imagine:
User accesses a protected service
quarkus-oidc extension does fancy token obtaining by HTTP redirecting, JWT in cookie lasts 30 minutes
User is authenticated and gets returned to the web application
User works in application, fills in forms and data
Data is being stored by JWT-enriched REST calls (we do validation by hibernate-validator)
User works again, taking longer than 30 min
Wants to store another entry, but token from step 3 is now expired and API call fails
User won’t be happy, so me neither
Possible ways to solve:
Make the JWT last longer than the current 30 minutes, but that just postpones the issue and opens some security doors
Storing users’ input in local storage to restore it later after a token refresh (we also would do that to not loose users’ work)
Refresh the token „silently“ in JS without user knowing. Is there a best practice for that?
I missed something important and the internet now tells me a better architecture for my application.
Thank you internet!
Re the step 3. In Quarkus 1.5.0 adding quarkus.oidc.token.refresh-expired=true will get the ID token refreshed and the user session extended if the refresh grant has succeeded
For such use cases, I tend to prefer the reverse of JWT. I keep the user data in a shared data service (a data grid like Infinispan or Redis). So that this data is keyed by the user and available. I do control the TTL of that data in the shared data service.
It can either be specific to an app, or shared between a small number of apps. It does bring some coupling but so does the JWT property structure.
For Quarkus, there is an Infinispan client integration, a Hazelcast one, mongodb and AWS dynamoDB. And you can bring other libraries.

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.

Extend user access token in Keycloak with external data

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)

What is the best way of passing user info/profile/context via web API service

I am a newbie who is writting ASP.Net web API service for the very first time. The issue I am having is how to pass user information or different contexts via service request. For example I want to pass user context (i.e username, user preferences etc.) and lets say security context (i.e. api key, secret etc.) thru each service call. The options I found
1. using Query string
2. custom HTTP headers
3. overload authorization header to pass Jason object
4. cookie
I ditch the idea of using query string as it has 2k limitation, custom header could be ripped by proxy services, dont want to use cookie,creating a jason object of all the context and send it via auth header can work but seems like not a smart way. Any idea? what is the best way of passing those extra information.
I really appreciate if someone help me with some examples.