Make Keycloak authentication work with own JWT tokens generation - spring-boot

There's a Keycloak (KC) server in my company, and I'm working on some app.
The Backend is Spring Boot 2.6.6, Front-end is AngularJs.
When user presses 'Log In' button, user gets redirected to KeyCloak login page and enters
credentials. This part is implemented already and working fine.
But then comes a tricky part: I need to return to front-end JWT token with some granted authorities, and those authorities will depend of what application gets from it's DB for every particular user. All other endpoints will have #PreAuthorize with needed authority.
So, I can't get JWT from KC, because KC doesn't know anything about app's vision to user's granted authorities.
Can you please help with some ideas how to achieve this? Because I'm trying to implement this and getting doubts about possibility to achieve this.
One of the errors I'm getting is:
Found WebSecurityConfigurerAdapter as well as SecurityFilterChain. Please select just one.
Thank you

Keycloak is OAuth2 and OpenID Connect(OIDC) protocol complaint. Which means you can use already defined patterns of authorization flows in OAuth2.
Auth2 has implementation of a step by step authorization logic called Authorization Code Flow -which is one of many but I believe is the most suitable one for your use case-. RFC docs of this flow explain it pretty well and you can find them here. You should also look at how Keycloak implementations are done.
Learning and implementing this flow on your project will provide an industry standard solution.

Related

Spring Boot Security registration and logging for website with roles, how to do it?

I have a difficulty in understanding Spring Security and any tutorial I found was not tailored to my needs. So maybe I'll explain what I think and what I want to accomplish.
I want to create a website with Kotlin/Java backend and frontend in React. This website would need to have users with different roles (user, admin).
And (I think) the thing I need is some kind of backend that has 2 endpoints:
register (to create users in database)
login (to, based on username and password, fetch user info and role) - as some kind of token? This returned token would be then used by frontend to display specific options (i.e. do not display "ban user" for regular users) and it also would be sent to backend for checking if the person who requests for specific endpoint really should be able to call this endpoint (i.e. it should be forbidden for regular users to use "ban user" endpoint)
What should I read about, what keywords should I look into to achieve this?
For purely the Spring Boot part of the implementation, the following should do
(/register) Signup/Register endpoint taking all required parameters for your business logic. e.g Username , Password , Full Name as well the roles
(/login) For logging in , you need a token forwarded to the front end, which will then use this token in the header for the session. JWT tokens seems like what you need(sample below). For the other part of your requirement, you can keep the user object (with roles) in the session as well as check user role on the backend in the "ban user" endpoint and process accordingly.
JWT Authentication with Spring Boot
I found a good starting point in the following sample
https://github.com/bezkoder/spring-boot-spring-security-jwt-authentication
For a more complete example
https://www.bezkoder.com/spring-boot-react-jwt-auth/
Credits to
https://www.bezkoder.com/
I have come a cross Youtube Video that covers all the scenarios that your looking for and extra, with Email verification links as well. i hope this will definitely help you
Java Tutorial - Complete User Login and Registration Backend + Email Verification

Client side authentication without redirection to Keycloak

Pretty simple question, spend a lot of time searching around.
Spring Boot 1.4.x application, with Spring Security, tried to use Keycloak for user management / authentication / authorisation, all works fantastic!
How do I avoid redirecting to Keycloak login form?
How do I implement my own authentication worlflow based on username-password input?
I see that I can ask for access-token and refresh-token, but should I implement all that token magic myself or there is some famous library people use?
Any github or examples would help. Thanks!
You might have a look into the Ressource Owner Password Credentials grant. It boils down to set the "Direct Access Grants Enabled " for your Keycloak client and implement the login logic yourself.
But please, PLEASE make sure to read this first: https://www.scottbrady91.com/OAuth/Why-the-Resource-Owner-Password-Credentials-Grant-Type-is-not-Authentication-nor-Suitable-for-Modern-Applications
You could also use some openid connect - libraries and get the data you need for the endpoints from the .well-known endpoint of your realm.

Spring Security + JWT: How to enrich Authentication/Principal after successful login?

I’ve got a question which seems popular, but I couldn’t find the answer. Well there’s a lot of information about it but I’m not sure what the best way is. So here’s the scenario.
We have a Single Page Application (SPA) and a RESTful Web Service (API). We use an external authentication/authorization service provider via OAuth2/JWT. But I need to persist the user ID (provided by the external authentication provider) on the database on the server side after successful login. And also I need to enrich the Authentication/Principal object in security context after successful login (for example by adding email).
There's a lot on the web about this scenario. But we have SDK for authentication/authorization already and it works perfectly (no custom code, etc). I just need to add something to the authentication object. What is the correct way to do it? Thanks.
For the record, this is what we did:
As I said there's already a SDK doing all the heavy lifting of authentication mechanics. We just need to enrich the authentication object after successful authentication. So we wrapped the AuthenticationProvider (implemented in the SDK) in our implementation (inspired by PreAuthenticatedAuthenticationProvider) and after successful authentication, we enriched the result using our UserDetails implementation (inspired by PreAuthenticatedGrantedAuthoritiesUserDetailsService). The rest was straight forward.
PS: please let me know if you don't like the idea.

Spring4 Security - how to secure restful api with access token only, no login required

I have met a seemly easy, but actual pretty difficult situation for me, hope you can help.
WE need to provide secured rest api, but we have difference service, for example, authentication service, execution service. I now need to secure execution service.
I am using spring4 boot to boost, it seemed natural that using spring security, and then provide a customer userdetail service,but then when I start implement it, I met this big problem.
ExecutionService is not responsible for login purpose, so it won't provide a login form and consequently, it won't save token at all. What it needs to do is only checking header info, if it sees token in the header, it will use some decode algorithm to decode that token and then check if user is qualified to continue to not.
In all the posts on line regarding spring security, it all require a token storage, that means, user login first and then save token in memory, and then when user comes again, just check that token.
Can anyone help me to figure out,
1) how to use spring security to check request header info;
2) when see token in header, use a customized function to check validity of that header and then authenticate the user based on the checking result?
Thanks in advance

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