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

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.

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/).

How do I make a generic authentication service?

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!

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.

User Token authentication Spring MVC RESTful API

I would like to secure our REST API with user token.
User does an initial request to the API to obtain an access token (must provide own credentials - login and password)
Service find the user by provided credentials
If is a user found, service creates an unique token with time expiration and returns it back to the user (token expiration can be defined as now() + 15minutes - is it enough? What is a standard expiration time for such tokens?)
User must provide this token in all his requests OR asks for new token when is expiring and API process original request
I would like to ask you - is there in Spring framework native support for such authentication flow - I'll be happy with some simple example or URL to Spring doc? If so, what do I need to use? I have studied Spring docs and read many tutorials, and It seems there is a support for everything and I need to know what is the best for my issue.
For token-based authorisation to resources, one framework that will inevitably come-up will be oAuth
oAuth will help you achieve exactly the workflow that you desire e.g. that a user can authenticate and then be given a token to access a defined set of resources via an API. It is however fairly heavyweight and it is definitely worth taking the time to understand how it works and that it exactly fits the picture of your requirements.
The "official" site is here. There are two versions of oAuth, so again this will help you to understand which the the right one for you.
As for Spring Security integration, there is a Spring Security oAuth project. The documentation for this is pretty good both at the level of how the integration works with Spring Security, but also in terms of helping you understand that oAuth is the right solution for your project.

Why should i use JAAS against hand-written security?

I got hand-written security, simple servlet-filter which redirect not-authorized user to their login pages. Login controller redirect them to the requested URL after successfull authentication or their main page. This approach work fine, the only disadvantage, that I have to pass User object which is stored in the HttpSession through stacktrace to EJB beans.
Now I rewrote some code and use Spring-security as http based authentication. It is integrated automatically with Glassfish JAAS.
I don't need to pass User through stacktrace anymore, invocation sessionContext.getCallerPrincipal() is enough. But the principal object return me only userName, not userId, so i have to perform addition select if i need userId for example.
1) Is there anyway to extend Principal object, so it can store more properties ?
2) Why i should use JAAS or Spring Security or another security framework, why not just hand writen servlet filter ?
2) Using a standard security mechanism like JAAS has many advantages:
You can easily change the way user authenticates solely by configuring your server - without need to change anything inside your code.
You can be sure your security is up-to-date, supporting strongest algorithms, storing Principal in a secure manner and so on. Again just by staying up-to-date with your server, framework etc. Having a hand-written security module is prone to errors and to be outdated soon.
You can leverage framework security - eg. web.xml security tags, EJB security annotations. Because JAAS is a standard way to authenticate, you can be sure adopting future technologies will be easier, because all serious technologies will support JAAS (Spring security etc.). If your software is planned to grow, you will definitely need a standard.
It will save you time and effort. JAAS provides both authentication and authorization, neatly packed and configurable within minutes.
I recommend futher reading on J2EE security or you can find more resources in OWASP guides.
1) I don't know if you can extend the class Principal. But note, in your LoginModule, before you finish the authentication calling the commit() (probably in your login() method), it is possible to add credentials in the Subject. For this, just add the object to one of the lists: Subject.getPrivateCredentials() or Subject.getPublicCredentials() (with no arguments). You can add many objects like your own class, a String, or whatever you want.
To retrieve the objects in your application, use the procedure detailed in my other answer.
import javax.security.jacc.PolicyContext;
Subject subject = (Subject) PolicyContext.getContext("javax.security.auth.Subject.container");

Categories