How do I make a generic authentication service? - java

I wrote a chain of spring applications, each of which performs some unique functionality. It is a stretch to call this combination of separated services a microservice architecture. And now, I would like to implement spring-security. However, I think it's silly to implement authorization and authentication functionality for each of the services.
Can you advise how right it is to make one more service which would serve as a common place for authorization and authentication? And already in each of the already written "microservices" I would check this authorization.
For example, I see the following path to a "microservice". The client makes a request to the common security service and gets some kind of jwt token there and with this jwt token goes to any of the services and gets authorized there. In this case, this jwt token determines what rights are granted to this user. I would like to control access to end-points within the applications themselves, and get the jwt token from the outside.
The most important question. Is it possible to implement this? If it's possible, is it the right way to do it?
I would be immensely grateful for any examples or articles on the subject!

Related

Keycloak and SpringBoot

I started playing with Keycloak, but I have a question. While reading articles, I always found examples where a client (let's say Angular) is logging in on Keycloak, it gets a bearer and then it send the bearer to the SpringBoot application. The backend, so, validates that the bearer is valid and, if so, it allows you accessing the desired endpoint.
But it's not enough in my opinion. I don't need just to login, I would need the entire functionality - let's say I have a backend application and I need a user. I could have a basic todo-application, how do I know for which backend user I am actually accesing an endpoint?
Straight question: how can I bind my own backend user (stored in the DB from backend) to the one from Keycloak?
What is the best way to do it? The only thing that I found online and into the Keycloack documenation is that I could move the logic of logging in from client (Angular) to backend (SpringBoot). Is this the way to go?
Imagine like I'm creating my manual /login endpoint on backend on which I would then call the Keycloak server (Keycloak REST client?) and I would pass myself (as a backend) the bearer to the client.
Please help me with an explanation if I'm right or wrong, what's the best practice, maybe help me with an online example, because I just found out the too easy ones.
OpenID tokens are rich
Keycloak is an OpenID provider and emits JWTs. You already have the standard OpenID info about user identity in the token (matching requested scopes), plus some Keycloak specific stuff like roles plus whatever you add with "mappers".
All the data required for User Authentication (identity) and Authorization (access-control) should be embedded in access-tokens.
How to bind user data between Keycloak and your backend
In my opinion, the best option is to leave user management to Keycloak (do not duplicate what is already provided by Keycloak). An exception is if you already have a large user database, then you should read the doc or blog posts to bind Keycloak to this DB instead of using its own.
Spring clients and resource-servers configuration
I have detailed that for Spring Boot 3 in this other answer: Use Keycloak Spring Adapter with Spring Boot 3
In addition to explaining configuration with Spring Boot client and resource-server starters, it links to alternate Spring Boot starters which are probably easier to use and more portable (while building on top of spring-boot-starter-oauth2-resource-server).
I Also have a set of tutorials from most basic RBAC to advanced access-control involving the accessed resource itself as well as standard and private OpenID claims from the token (user details) there.
Tokens private claims
For performance reason, it is a waste to query a DB (or call a web-service) when evaluating access-control rules after decoding a JWT: this happens for each request.
It is much more efficient to put this data in the tokens as private claims: this happens only once for each access-token issuance.
Keycloak provides with quite a few "mappers" you can configure to enrich tokens and also allows you to write your own. Sample project with a custom Keycloak mapper here. This is a multi-module maven project composed of:
a custom "mapper" responsible for adding a private claim to the tokens
a web-service which exposes the data used to set the value of this claim
a resource-server reading this private claim to take access-control decisions
The simplest way to do it is to consider that the job of storing users will be delegated to your Keycloak server. But you can implement some roles and checks manually with in-memory or any database of your preference too.
I invite you to follow some documentation about OAuth 2 and Keycloak, to make requests to get a valid token for a time period and to make others request inside that time period to get datas. You can use CURL to make requests or web/software tools like Postman.
Be careful, a lot of Keycloak Adapters are deprecated ones since some months.
I would echo BendaThierry's comments. Look into OAuth2 and Keycloak. The Bearer token you receive from Keycloak will have user information in it (typically in the Claims). This way you can have user preferences or features in your backend without needing to manage the authorization and authentication that Keycloak does.
There are lots of great resource include Spring's website tutorials (like https://spring.io/guides/tutorials/spring-boot-oauth2/) and Baeldung (https://www.baeldung.com/).

which oauth2 flow do I need for multiple domain with a custom login screen

I'm implementing an authentication and authorization mechanism to unify login mechanism's across three different websites using an external identity provider and OAuth2.
The requirements that are causing design implications.
- Users and permissions managed externally to the existing websites in an external identity provider.
- The user should only have to log in once.
- The login screen needs to be embedded in our application rather than using an identity providers.
I'm creating a login web application. I'm not sure which OAuth2 flow to use. I've used the Authorization code flow previously with Spring security, but that seems to need an external identity provider's login form.
Should I use the implicit flow directly from the login site's javascript? How concerned do I need to be that it's not as secure as the code flow.
Do I need to handroll a solution to call an idp's sdk to get tokens and then sling them into http headers for subsequent use by the other domains Presumably CORS will be an issue? I'll need to include the id token for the other domain to know which user it is - is it secure to pass around the id token via the resource user's browser.
thanks for any guidance, as you can tell its a bit of a muddle in my mind!

Spring (boot) + Angular (2|4) authentication options

I'm about to implement user authentication in my app.
Since it is my first Angular + Spring project i would like to know what are the possible options for authentication. I don't wait for detailed instructions, concept level is enough, so that i know where to dig.
I consider two ways of further back-end app development:
REST like;
regular spring MVC, however i don't know how to combine angular and spring in this case. Any suggestions in this regard are also appreciated.
There are various ways to accomplish this. The general idea is that the angular clients adds a credential to every request (typically in the authorization header) which a servlet Filter on the backend verifies before executing the request.
There are various standard ways to accomplish this, ranging from simple HTTP Basic Authentication (which spring security can do easily) to full fledged single sign on protocols like OAuth 2 (and its extension OpenID Connect).
I've heard that jwt has drawbacks, one of them is impossibility to block user until his jwt token is expired, which is pretty important in my case
Not necessarily. JWT is a standard for authentication, not access control. That is, it simply describes a way to identify users, but does not constrain how you make access control decisions. In particular, it is entirely possible that an authorization framework will load user permissions for every request, though doing so may not be its default configuration.

SpringBoot JWT security how to

I am trying to implement simple JWT security with token refresh in my web app. Probably, the question has been asked numerous times and I am digging for an answer but can't seem to find it after a month of searching.
I have two models for the user in the database and they should have different role type ADMIN and USER. ADMIN type needs to access his url endpoints and USER his own upon successful email and password login.
I am trying to avoid oauth because I do not need enterprise like implementation.
Could anyone refer me to a good guide that explains how stuff works or just explain by himself with a code sample? You would help me alot! Thanks.
You may want to try JJWT if you're looking for a simple to use JWT library for Java. It's well documented and easy to integrate into Spring Boot apps.
At the very least, you'll need to write your own service for generating tokens (using JJWT), a filter for pre-processing the request and generating an Authentication, and an AuthenticationProvider for performing the actual processing/validation of the token content (again with JJWT) and to populate roles/authorities or any other information that might be required by your Authentication implementation.
This method of implementing JWT based authentication does not require any components from Spring's OAuth2 implementation.
https://github.com/jwtk/jjwt
https://stormpath.com/blog/jjwt-how-it-works-why

How to secure the Rest webservice by token based authentication?

I have created few rest services using jersey implementation.
In security concerns, service can invoke by any one. So I decided to use the token based authentication system.
I wrote one filter in spring security which handles every request before its hits the server.
One login service were created so user can invoke this service by passing the username and password for valid credentials it will generates the access token and expiry date and saves it in Hashmap and DB and returned as a response to the user.
For remaining services user have to pass the generated token in header to access the JAX-RS services.
All these process are coded by us i.e., generation,storage and expiration of the token.
Since we have some security API like oauth1,oauth2 in market is it good to provide the security for rest service by above mentioned way???
Is oauth api will suits my requirement . If it is please guide me how to achieve this ?
Please help me out with valuable suggestions ???
Thanks in advance.
We've been in a similiar position before starting with our rest api. The only difference we had no exisitng code. So basically we saw 2 choices
Run our own Tokenhandling, that what you already have
Use something existing, i.e. oauth2
Our main requirement was authentification via token and we prefered an existing solution. So we just run with oauth2 in form of spring-security-oauth2, even we are not using the whole self authorization stuff.
What i like and probably had missed in an own implementation is that a token generally identifies a user and a client combination and that clients can have rights too. Its nice to have this extra layer of security in our rest api, so i can block early on before even hitting one line of our code.
In form of spring-security-oauth2 its proven code, which works and like much of spring its customizable. Example: In our first version we did use the provided JdbcTokenstore for storing the token, but as requirements changed, we just coded our own and switched it in the config.
The disadvantage of using at least spring-security-oauth2 is that the whole authorization flow is normally webbased and needs communication between the client, the user and our app. As this would not work with our clients we had to trigger the token generation, etc ourselfs, which is doable with spring, but needed some code exploration :-)
If i had to build it again with java and where already using spring, i'd go with spring-security-oauth2 and the oauth way again. But when i had an existing working solution and dont need any of the oauth stuff i would keep the homegrown solution.

Categories