Extend authentication with custom licenses entities? - keycloak

I'm using Keycloak as an auth server behind an Nginx reverse proxy.
Leveraging the multi-tenancy and multi-roles suites my needs but I'd like to extend the authentication flow with some custom user-properties that would be ideally stored in an alternative schema/database.
These could be exemplified by:
A global subscription with an expiration date associated with one or more tenants/realms.
A license with expiration date associated with each user inside the same tenant/realm.
...
From what I've understood I could exploit a custom Authenticator SPI that checks these fields based on the user_id and add it to a custom Authentication Flow defined for each separate client inside my pool. Is this the correct use case or is there a better general approach to apply?

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

Is it possible to have multiple Keycloak realmsconnect to the same icCube server?

use case
in icCube
one server instance
icCube users only need to access the reporting
icCube is used to for a standard reporting solution for an industry vertical and can be used by multiple clients, each having their own (copy of the) structures that work with their own data
a client can grant one or more users access to their own dashboards in icCube
authorization requirement
it should be possible to link authorization to the client's identity
management system (such as AD)
for others, it should be possible to assign a local admin at the client that can give access to their own environment to whom they wih
for the rest, it should be possible for a centralized admin to maintain access
a perfect job for ...
keycloak
keycloak needs for each of the requirements a seperate realm with client (see picture)
The icCube documentation only makes mention of one Realm & client.
the question
Is it possible to use multiple keycloak realms & clients with one instance of icCube?
See also icCube documentation on keycloak integration
Right now this is not possible.
The keycloak.json file is used to connect to a Keycloak server that is going to authenticate the HTTP request. So you would need somehow a way to determine which keycloak.json file to use based on the HTTP request before using it meaning having different URL and/or URLs with a specific parameter.
Possibly the multi-tenant support could be extended to be able to configure an authentication logic per tenant with the same constraint about the URL value.
Hope that helps.

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)

Custom filter in apache shiro

I have two set of users one is anonymous and another is valid users (authenticated using cas server). So for anonymous I don't have ticket but for users I have the ticket. But I want to make the resource available to both with some nifty feature will be provided to valid users. My resources are available as REST services. Therefore between two calls (say /foo and /bar. here /foo must be called before /bar) I have to check whether the calling user is same or not?
Therefore I would like to generate a ticket for anonymous user also. so that in /bar, I can check same anonymous user has actually request /bar.
Can anyone suggest how can I solve the above problem using apache shiro.
Also as I have very little knowledge about Apache shiro, I would like to know which one is better apache shiro or spring security (in case of REST services developed using jersey 2)

Best way to define a Customized authorization policy

I am developing a project with MongoDB, I have a scenario, so that I can restrict the visibility of data to the user based on their role, for example if I have a document of the form:
{
"testme1":"fooo",
"testme2":"foobar"
}
A user with role "admin" can see both "testme1" and "testme2", whereas "guest" can see only "testme2". What is the best way to define these authorization rule dynamically, so that my wrapper api should fetch the data only as per the rule. My approach of doing is to give the user a web "UI" to define a rule and based on his declaration keep a "XML" file in my server. Please let me know if someone has a better Idea,also if their is some Database level approach to do this
There is an authorization standard that exists which you can use to define your authorization policies. This standard is called XACML, the eXtensible Access Control Markup Language. It implements an authorization model called attribute-based access control (ABAC). You can read up on both topics here:
NIST's page on attribute-based access control (ABAC)
OASIS extensible access control markup language (XACML)
XACML defines an architecture with the notion of:
a policy decision point (PDP),
a policy enforcement point (PEP), and
a policy information point (PIP).
In the typical flow, the PEP protects your data / service / API. The PEP would send an authorization request to the PDP:
Can user Alice view record #123?
The PDP would turn to the PIP to retrieve missing attributes e.g. the user's role and clearance as well as resource attributes e.g. the sensitivity of data, a whitelist or blacklist... Based on the new information, the PDP can reach a decision: Permit or Deny. Access is allowed or blocked.
With XACML there is no limit to the richness of the authorization policies. I work for a company, Axiomatics, that implements XACML, and our solutions are used in manufacturing, healthcare, banking to secure access to sensitive data in a dynamic way (e.g. managers can edit documents that they own).
XACML enables externalized authorization that is managed centrally. It also enables what I like to call any-depth authorization meaning that you can apply XACML to web APIs, business logic, presentation UIs, as well as databases.
HTH