How can I implement Single Sign On (SSO) multi tenancy functionality with Keycloak and Spring Boot OAuth2 clients? - spring-boot

Problem
Implementing SSO login for multiple OAuth2 providers in Spring Boot.
Setup
Two Spring Boot web applications (App1 and App2) that are configured to be OAuth2 clients. Both will communicate with a Keycloak authorization server that has two realms.
Business Requirements
Implement Single Sign-On functionality (SSO).
Multi tenancy with shared user base.
Only one user can access one tenant at any time.
I have two spring boot applications which are OAuth2 clients running in docker containers. We are setting up multiple Keycloak realms that are configured for each tenant. From the Spring side of things, we include the auto configuration properties for two providers where each provider will be mapped to a different Keycloak realm. So the properties will look as follows:
spring.security.oauth2.client.provider.realm1......
spring.security.oauth2.client.provider.realm2......
Behavior
When a user logs into the first application (App1), Spring shows a generated html page. This page shows a list of each provider configured from the application.properties as an option to login to.
A user can select one and is redirected to the Keycloak login page with the realm that was mapped from Spring's provider properties. Then when successfully logged in, the user is redirected back as expected.
We use Spring Mongo session to store the session information and we also see in the Keycloak admin client the realm that shows the active session as well.
When trying to access the other application (App2), Spring does not detect the user or session and will show the same generated html page that shows the providers to select and login to.
When clicking on the same provider (realm), Spring will then find the session and will be redirected to the requested resource and all is well. This part is what I am trying to implement without asking for the provider first. The main reason is to enforce a business requirement where a user in a session can not access more than one realm at a time.
Attempted Solution
Provide a Spring Security login controller that will have a service layer to find the mongo session and then build the OAuth2 link Spring generates when you click a provider from the list.
However, I dont have the user yet. This also becomes a problem when opening a different tab as I dont believe I have any scope to the cookies that were created from the first application as well.
The only other thing I can think of is trying to get the client ip and store that in the session so I can find it later. However, when using nginx proxy configuration, this becomes a problem as I cant seem to get the actual ip and always seem to get the proxy ip instead even with the nginx headers I have seen from documentation.
Question
Is there anyway to find the session and redirect to the requested provider programmatically?
Note: I am currently aware of the keycloak starter dependencies that are available but I was trying to see if there is a more Spring oriented solution with its general OAuth2 client security configuration.

Front end solution
User navigate to app1, app1 detects no user session (need for login), app1 redirects user to app2 with some query parameters indicating purpose of redirect.
App2 receives redirect request and check if session exist (user logged in to app2). Now you can deal with it. redirect back to app1 or display some error, etc.
User not logged in to app2 , app2 redirects back to app1 with indication "show providers"
Symmetrical behavior shall be implemented on app1 too.
Depending on security requirements query parameters can be encrypted to prevent manual url hacking.
If you need further protection Keycloak authentication can be extended with functionality to check your Session storage for already logged in users.

Related

Keycloak Single Logout Issue with multiple clients

I have built two keycloak clients (spring-client and a tomcat-client using keycloak OIDC spring boot adapter and OIDC tomcat adapter) and both are working in the same realm. I have two problems with these clients.
When I am going to sign in to those clients, I need to provide username and password for each client separately even though I am using the same browser (multiple tabs) and same username.
When i need to sign out only a single client (tomcat-client) log out and the other client (spring-boot-client) does not logout at all and keep the session until a timeout occurs.
Further when I am investigating I found that there are two separate sessions created for both clients. (see the image)
Since I am using same realm and same user I have no idea that how two sessions were created. There is another thing I noticed, tomcat-client & security-admin-console both clients are in the same session. When I logout from the keycloak admin console then tomcat client automatically logs out. The problem is only with the spring-boot client.
Also I have set each client's admin URL as the base URL of each application.
Can someone help me to sort this out.
Thank you
After lots of debugging finally I found the problem in my configuration.
In the spring boot adapter configuration file I have mentioned the Keycloak URL as http://127.0.0.1:8080/auth
In the other adapter configuration file I have mentioned it as http://localhost:8080/auth
the issue was fixed once same URL added for both adapter configurations.

Implement Keycloack Authorization server using Spring Security 5 OAuth2

I've written a software system that uses Spring Cloud Netflix. Due to Spring Security 5 not offering support for writing an Authorization Server (pls shout out here https://github.com/spring-projects/spring-security/issues/6320) I need to write my own Authorization server. I want my application to permit Social login and username/password registration, have a custom login page but also use keycloack. I don't even know from where to start, if you have any documentations or code samples please provide.
You can use the cas project. By using the overlay it is easy to set up and to customize:
https://github.com/apereo/cas-overlay-template/blob/master/README.md
It serves a frontend where your user can be redirected to and can login. After successful login, the user is redirected back to your web page. The frontend is completely customizable.
It supports all kinda of authentication providers like keycloak, database or Google/Facebook.
After basic setup you just add the dependency inside the gradle file, configure your keycloak/database/... in the application.properties and can start using it as authentication server.
It fits perfect into a microservice landscape and is curated by professionals implementing security best practice.
https://apereo.github.io/cas/6.1.x/planning/Getting-Started.html

Spring Boot REST service – End User Authentication vs APP (REST client) Authentication

I have gone through many posts and articles but didn't find a straightforward solution for the case below which I have to implement.
Platform: Spring Boot 2.x.x (Spring Security 5.x.x) with embed Tomcat
Solution: REST service that consume many client apps and many end users.
I have to implement a REST end point /api/search which accessible for many client application. As an example, web application APP-X (Angular), web application APP-Y(Jquery/Bootstrap) and mobile application APP-Z (IOS). All three clients are separate entities (both technical perspective and business perspective).
So I have to authenticate above application using onetime token. Therefore I planned to go for Spring OAuth2 by enabling #EnableAuthorizationServer and #EnableResourceServer. For each app client I’ll generate a token and they can use it when they connect with my REST service. Is this approach correct?
Apart from the app clients system has capability to register and login functionality for end users. Also my end point (/api/search) can access both anonymous users and users who registered under ROLE_REGUSER role. And through the security context, I need to access the user details as usual user authentication.
This is the place I got stuck. How can I handle the following points together using Spring Security 5.x.x (Spring Boot 2.x.x).
I. Both client apps and end users authentications.
II. Allow access for anonymous users and registered users for same end point.
I have attached small diagram to elaborate the above scenario.
Thanks
I found a solution when I upgraded my spring security version to 5.2. In version 5.2, they have depreciated #EnableAuthorizationServer and #EnableResourceServer. So I had to move with an external authorization provider who supports auth2. I chose AWS Cognito, and fulfill the above requirement, using the user pool option.
In AWS Cognito
I created a user pool.
Then created two app clients in the same user pool.
One app client configured as support to the client credentials flow.
The second app client configured as support to the user authentication flow.
In client applications
Retrieve access token directly from AWS Cognito using client credentials and used to secure all API calls.
If a user login at any stage, retrieve access token directly from AWS Cognito using the authorization code and replace any existing access token.
The advantage is, the resources server can validate any access token that generated related to the same user pool.
In resources server (backend API/Spring Boot)
Validate access token.

Authenticate user within Spring Boot + Vaadin application

I am building a Spring Boot application with Vaadin as front end. The application uses a third party library to authenticate the user with his identity card via SAML.
After this authentication the user is redirected back to my service and I can fetch the authentication result and optional attributes.
My question is, how can I implement the protection of specific Vaadin views within my application based on the authentication via the user's ID card and how do I set the user as authenticated appropriately?
I am new to Spring Security and the majority of its examples shows authentication via a login form with username and password which does not fit in this case.
You can find two approaches to secure your Spring Vaadin Application with either filter based (so only Spring Security) security, or a hybrid approach in this Github repository: https://github.com/peholmst/SpringSecurityDemo
You can also find blogposts about both approaches here:
Filter Based Security
Hybrid Approach
For you especially the Filter based approach could be interesting. You could implement a Filter checking the token (or whatever) you get from your login server and then allow/deny certain pages on your server for certain roles.

How to integrate keycloak in Spring Boot with a different context root and reverse proxy

We are currently developing a microservice application using Spring Boot 1.4 and Keycloak 2.5.0 (configured as openid-connect service) using the Keycloak Spring Adapter (not the Spring Boot adapter).
All of our microservices are put behind a load balancer and an additional reverse proxy as the application will be hosted on an existing domain behind a context root (so the root of our application is http://foo.bar/foobar/ and the rest services are http://foo.bar/foobar/rest/).
We are facing a couple of problems with Keycloak in this given scenario:
Keycloak forward to /sso/login if a sign-in is needed. This is in our case unwanted behaviour because http://foo.bar/sso/login will not exist. I have found a way to change the forward but there is no way to make Keycloak listen to the same url; we end up with a 404 in this case.
After signing in, Keycloak redirects back to the /sso/login url with the correct tokens, but if this is not the same server, the request fails and it redirects us to http://foo.bar/. Since every microservice exposes /sso/login, this can be in fact a completely different server.
If keycloak is hosted on the same domain, we end up in a redirect loop. We would also like to have Keycloak hosted on the same domain and on the context root http://foo.bar/foobar/auth/ .
We've already tried using the "token-store": "cookie" but this did not resolve the problem.
Is there a way to resolve these problems or is Keycloak maybe not the correct solution for our use-case ?
Update 05/05/2017:
Move my answer from here to an answer
We are now up and running with Keycloak so I'll briefly explain what we did. The front-end of our application runs Angular2 and we created a custom login page in the Angular application itself (so it's not a theme for Keycloak) which will directly query the Keycloak API for an OAuth2 Bearer token. The front-end will send this token on each request in the Authorization header (as per the OAuth standards).
On the service side we have configured keycloak as a bearer-only solution (bearer-only: true in the keycloak.json), this way the application just returns a 401 or a 403 instead of forwarding to the login page.
Using this configuration the user will never see anything from the /sso/login page and there is also no redirect issue anymore.
TLDR; the use-case I described was also not realistic, calling a REST URL and then forwarding to a login page is kind of bad stuff :)

Resources