What is the best way for implementing keycloak sso with existing spring-boot gateway service? - spring-boot

We're currently using jwt token based authentication in spring gateway service, where we generate token by providing username and passwords, then token is generated with required attributes.
Planning to integrate current login flow along with keycloak sso using IDP for this instance let's say azure-ad.
What would be better way to implement it, keeping the flow in sync with normal credential flow for generating JWT tokens at gateway?
As of now, We've tried the flow where user is sent to IDP's login screen, login event is captured on keycloak and sent to custom event handler (SPI), SPI fetches user attributes and generates token from project's user database and adds to keycloak specific db if it's not there.

Related

Spring boot API with both Oauth 2.0/OpenID Connect and internal authentication?

I'm having a hard time figuring a good way to implement Oauth 2.0 and OpenID Connect authentication alongside an existing internal email+password authentication for a B2B Web app's API using Spring security.
We have a backend REST API that is a Spring Boot servlet application which currently authenticates users with OAuth 1.0 and the password grant. The front-end is an Angular single-page app through which users must log in with their username and password. The API's /oauth/token endpoint then delivers an opaque access token to be used for fetching secured resources that are then displayed within the app.
We'd like to add the possibility to log in using external authentication with OpenID connect, which is a perfect opportunity for switching to OAuth 2.0 and JWT tokens. Our API would then accept JWT tokens it delivered as well as external JWT tokens emitted by accepted issuers.
Reading and validating JWT tokens won't be a problem using Spring security's OAuth Resource Server. However things get complicated with how to make the classic username+password login flow work with JWT tokens.
We thought about delivering JWT access tokens the same way we used to with our old OAuth 1.0 tokens. The thing is, newer OAuth specifications advise against using the password grant, plus it simply isn't supported in the Spring authorization server project we're planning to use. The authorization-code flow w/ PKCE seems like too much for this case as we do not want the back-end API to render a login form but use credentials entered in the existing login form that is part of the single-page app.
I've read a lot about not using OAuth for 1st party login since its primary use is for external authentication, but again, that doesn't apply since we also want 3rd party authentication.
What would be a secure way to implement a Spring boot authorization server that can deliver JWT access tokens to a 1st party client in exchange for a user's credentials, all this using the existing log in page, and given the password grant type no longer being supported?
I thought about implementing a preliminary step that would be a POST request with Basic authentication to a /login endpoint that just returns a 200 HTTP status, then proceeding to the /oauth2/authorize request that would deliver the authorization code immediately without redirecting since my session is authenticated.
I'll be happy to provide more details if needed. Here are the resources I'm using for this project.
What about setting up an authorization-server capable of identity federation?
In such configuration, the authorization-server is responsible for providing with identities, proxying one or more sources (your existing user database for instance, plus maybe Google, Facebook, Github, etc.)
Keycloak does it for instance.
From the client point of view (your Angular app), the authorization-server is used to get:
access-token: put in Authorization header of requests to secured resource-server(s) (can be a JWT or an opaque string, doesn't matter, clients should not try to extract data from access-tokens)
refresh-token: send to authorization-server to renew access-token before it expires
id-token: get user-profile data (email, username, profile picture, etc.)
You should have a look at https://github.com/damienbod/angular-auth-oidc-client for connecting an Angular app to an OIDC authorization-server.
From resource-server point of view, access-tokens are the source ofr setting-up security-context, either by decoding and validating a JWT locally or with token introspection on authorization-server.
Have a look at those tutorials for such resource-servers configuration.

OAuth2 SSO with User Roles and Permissions

I am going to deploy a small spring boot application on a server running on my company network. Its a Spring boot application and i need to implement the Authentication/Authorization using an existing OAtuh2 authentication server .
Now the requirement says:  If i am already logged in to my network, it should do an SSO sign-in to the application using a token from existing oAuth server that is being used. If not logged into the network,  it should not allow me to get to the application. 
Also I  wanted to know if i can extract various roles and permissions associated with a user from an oAuth2 token as i need to populate data based on user Permissions . Is this possible to extract this info from an oAuth token or  Is this possible  only possible via a JWT token?  Which will be the best approach to solve this?

What is the advantage of providing a Tokenized Authentication in an application with Spring Boot Backend over SecurityContextHolder?

I was getting started with Spring Boot and Angular 7 and I came across user authentication.
Let's assume the following: I have a frontend with Angular 7 and a Backend with Spring Boot that offers API's that can be accessed via HTTP.
So I know that usually the frontend authenticates the user with e.g. JWT that stores all necessary information about the user that might be needed. But I came across the SecurityContextHoler of Spring Boot Security:
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
This allows me to simply access granted Authorities and so on. So I thought about the following:
Using JWT for the frontend grants the following advantages (as far as I know):
* Users can identify when using API's
* Users may be prevented from certain UI-Elements (based on roles stored in JWT)
* Modification prevention due to checksum (invalid token afterwards)
Now I could also add a check in my Controller in the Backend that checks the SecurityContextHolder for user permission (something like a Service that checks the current context permissions vs the needed permission and returns true/false). Wouldn't that be even more save, since it is in the backend (so in my inmagination everything that runs server-sided is always a little more save than what runs client-sided)?
I can store information in the frontend (like roles and a username) to use them for the UI-based-access prevention to still have the same advantages as JWT provides, but I do not have the "effort" of implementing the JWT creation.
But obviously it is not common to do it that way (at least I never saw it), so what is the advantage of the Tokenization?
They are not mutually exclusive. You would use what you call "Tokenized Authentication", like an oAuth2 Bearer token most likely in a JWT when the Authentication is performed by a separate system from your Spring Boot backend. For example, you may be using Okta, Keycloak, Google or Facebook to authenticate the user.
At a minimum, your Spring Boot backend stores the username extracted from the JWT in the Authentication. You can get Spring Boot to extract any roles in the token and add those to Authentication::grantedAuthorites. If your backend system, has it's own set of roles in addition to what's in the token, then the backend could implement a PrincipalExtractor to load a UserDetails object for this user from the database as the Principal and merge the roles in the token with those store in the local database.
You'll probably want to security certain methods in your backend with method security annotations like #PreAuthorize(), since you shouldn't trust the front end. The method security will check permissions, like hasRole("ADMIN") or hasPermission(object, 'READ') using the Principal object in SecurityContextHolder.getContext().getAuthentication();
In the end, the token assures the backend the user accessing it is who they say they are, i.e. Authentication, but does not necessarily tell the backend what they are Authorized to do. Yes, if you control the Authentication server you can include roles in the JWT, but roles don't usually provide as fine a grained control as is required.
Independent of what level of security you implement, the token is translated into an Authorization so you can use the Spring Security framework to manage access within your backend code.
There are 3 type of token in spring security OAuth2:
1. InMemory token Store
2.JWT token store
3.JDBC token store
So now you’re talking the JWT token store. The most powerful of JWT token store is prevent the authorization server load against to the database for checking such as role,token expired so it is related database load performance. Since all the information such as: role,username, token expire ,etc include in token itself. So the authorization server or other resource sever may using the public key to verify this token itself without invoke to data store.
Hope helpful! ☺️

REST service using Spring Security and Firebase Authentication

Is there a simple way to integrate Firebase Authentication with Spring Security (for a REST service)?
From what I've read, I'll probably need to use a JWT token (obtained via Firebase), use that to authenticate the Spring service, and finally verify the token within the service via Firebase. But I can't find any (simple) documentation on using JWT with Spring Security.
I'd also like to be able to provide an /auth/login endpoint that uses Basic Auth rather than JWT so that I can obtain a JWT token via Firebase using email/password credentials. But this would mean enabling Basic Auth at one endpoint in the service and JWT Auth at all others. Not sure that's possible.
Short answer: no.
Long answer: you should create your own JWT, regardless of Firebase. When you receive a JWT from Firebase, verify its integrity. Then, issue your own based on the data in the token. Then you only need to adapt it to various OAuth providers. This way you can avoid round trips to firebase on each request.
For authenticating the user on each request (stateless auth), you add a filter with highest precedence. From the http request you are filtering, get the JWT and verify its integrity. If it's all good, set the authentication in the SecurityContextHolder.

External OAuth2 integration with own OAuth2 spring server

I'm trying to integrate Facebook OAuth2 authentication with my own OAuth2 server. Just to be clear the scenario is the following:
I have a OAuth2 Server that is responsible for authenticating our users. I implemented a custom AuthenticationProvider that checks for the credentials provided and builds a UserDetails object if successful.
I also have a rest-api that is also a ResourceServer (runs in a different application). So users after being authenticated they can access our rest-api providing therefore the token.
The token information is shared using JDBC.
Everything works fine as expected, but now I want to add external authentication providers such as Facebook.
My question is: what's the best way to do this? What's the expected flow? From the top of my head I would imagine something like:
User authenticates with facebook
Facebook provides a token
User sends the token to our OAuth2 server
I check the token validity with facebook
I authenticate the user using the authentication provider
The server gets back to the user with a new token issued by my OAuth2 server which the user will use from now on to ask for resources
Is this right? If so, how can I send the facebook token to my OAuth2 server? Is there some kind of standard? Should I make up new parameters for that? For instance I will be needing some way to differentiate facebook authentications from user/password ones.
Am I suppose to use my own AuthenticationProvider to validate this facebook user? It seems strange then return a UserDetails object that doesn't have a password...
Also, how to register users and auto log them in? Do I have to expose an endpoint of my own or is there some OAuth2 magic for that as well?
Any thoughts?
Facebook has some very good documentation on this with the correct flow and how you should handle the process.
https://developers.facebook.com/docs/facebook-login/manually-build-a-login-flow/v2.2
You are on the right track, and I think the facebook documentation should help clear up any questions you may be having.
Additional Information is here:
https://developers.facebook.com/docs/facebook-login/v2.2

Resources