Spring Security custom validation without using user password involved - spring

I was wondering if in Spring Security is possible to lock all endpoints of a rest api, and to do a login by doing a custom validation without using the username and password at all.
It is like create a custom validation method that receives a token and not user/pass. The method will then validate the token with third party that has already validated the caller.
This sounds familiar to OAuth2 only that the backend API needs to be secure by spring, and at the same time it is not the OAuth2 client:
We are building a login feature.
We have a client (mobile app), backend (REST like endpoints Spring MVC), and an AuthProvider for OAuth2/OpenIdConnect flows.
The OAuth/OpenIDConnect flow happens only between the mobile and OpenIDProvider. (an initial call happens from mobile to backend to provide some details for oauth flows)
Once the authorization succeeded, the mobile app receives an auth_code, and only then the backend is called from the app to "Login" which means validate the auth_code, exchange for access_token, and create user session. (we need to have a session).
As you see backend kind of "login" in the sense that needs to receive the auth_code only, and validate it with the AuthProvider before creating a session.
Thank you very much!
Any comments, or references are very appreciated.

Spring Security determines if a user is authenticated by looking at the SecurityContext in the SecurityContextHolder. This means you can authenticate the user however you like using the following:
boolean userIsAuthenticated = ...
if(userIsAuthenticated) {
Authentication request = new UsernamePasswordAuthenticationToken(name, password);
Authentication result = ...
SecurityContext context = SecurityContextHolder.createEmptyContext();
context.setAuthentication(result);
SecurityContextHolder.setContext(context);
}

Spring Security is a very flexible framework that publishes a variety of interfaces that allow the user to customize the behavior as need be.
I'd recommend the following resources to learn how to go about this:
Architecture Deep Dive in Spring Security
Spring Security Custom Authentication Provider
Spring Security Custom AccessDecisionVoters
Spring Security Reference Documentation

Related

Spring Cloud - Micoservice Authentication propagation

I am building an application using microservice architecture. I am using Eureka for service discovery with Spring Cloud Gateway for request routing. For authentication mechanism I am issuing JWT tokens (in auth service). What is the best practice when it comes to propagating Authentication so I can get logged user information in each service which is after the gateway?
So far I've came up/found couple of possible solutions:
In gateway add headers for relevant user information, and in each service create filter which would take said headers and create Authentication object and store it into SecurityContextHolder. The downside of this approach is I can't just plug and play services outside my application.
Pass the token coming from the client through the gateway to the each service, where I would have JWTFilter which would validate token and extract the user information. Downside I see with this approach is I have to have jwt secret shared between each service or stored on each service, and I would have to implement JWT logic, producing duplicate code.
Final solution is having something like oAuth token introspection endpoint in auth service which would be called from each service (filter) once the request reaches it.
I implemented the filter logic for validating the user token in the gateway service, but I would like to use role based authorization on each endpoint (service) differently (ie. user service has endpoint for creating users (ADMIN), and for fetching user information (ANY ROLE)).
I opted for something like your option 2 and use spring-boot to configure JWT decoder from an OIDC authorization-server (Keycloak).
Configuring OpenID resource-servers is super easy (more options in parent folder), and authorization-server JWT public signing key is retrieved automatically by spring JWT decoder.
All that is required is ensuring that Authorization header with JWT bearer is correctly propagated between services.

custom oidc in keycloak

I have a spring based application which does authentication and authorization(oauth2 based) for a client app.I want to now use keycloak to manage my authorizations, but i want to keep my spring code. Basically i want to use my existing auth code as an external identity provider in keycloak.
I am thinking of adding changes in client app such that it receives token from my existing oauth code(which does the authentication) and then exchange this token with keycloak(for session and authorization management). How can i do this? What configurations need to be done in keycloak?
I read about token exchange in keycloak here, but i am not clear about the kind of token i need to send from my existing auth code.
https://www.keycloak.org/docs/latest/securing_apps/
Here is how OAuth2 roles are usually spread:
Keycloak is authorization-server
Spring service is resource-server
front-end is client
user is resource-owner
I have a doubt of you wanting your Spring service to be "authorization-server" as well (serve user identity). If so, I think you should not.
Keycloak (or any other OpenID provider) should be the only authorization-server. Both Spring and client(s) should be configured to use it as so.
To write it differently, Keycloak is responsible for users login and emitting tokens with user ID (subject) and rights (roles or whatever). Other tiers in the architecture (clients & resource servers) get user info from the token and apply relevant security checks (spring security annotations, Angular guards, etc.).
I published a mono-repo for a meetup with minimal sample involving a Spring resource-server and Angular (with Ionic) client talking to a Keycloak OpenID authorization-server. You might find some inspiration browsing it.

How to implement JWT with Keycloak in Spring boot microservice acrhitecture?

I have read some articles for Keycloak spring implementation (eg: easily-secure-your-spring-boot-applications-with-keycloak) but no one mention how to use with JWT.
I have created zuul api gateway and add Keycloak adapter as described in the previously linked article. That's ok, but I want to use JWT with keycloak.
Mentioned elsewhere set the client access type to bearer-only and the session strategy to NullAuthenticatedSessionStrategy. That's enough or need something else for JWT?
So my questions:
How do I configure client on Keycloak admin for JWT?
How do I configure Keycloak in backend config file for JWT?
How do I configure Keycloak adapter for JWT?
How do I pass user info to microservice? Create filter in gateway? But how I get user info from request?
Keycloak access token is a JWT. It is a JSON and each field in that JSON is called a claim. By default, logged in username is returned in a claim named “preferred_username” in access token. Spring Security OAuth2 Resource Server expects username in a claim named “user_name”. So, you need to create mapper to map logged in username to a new claim named user_name.
In order to provide access to client (micro-service), respective role needs to be assigned/mapped to user.
In your spring boot application, then you need to configure connection to keycloak server, providing, auth url, token url, scope, grant-type, client-id and client-secret.
Afterthat, your app be able to parse JWT token, you need to create some JwtAccessTokenCustomizer. This class should extend DefaultAccessTokenConverter and implement JwtAccessTokenConverterConfigurer classes. The main logic lays in public OAuth2Authentication extractAuthentication(Map<String, ?> tokenMap) method.
Then you need to configure OAuth2 Resource Server to provide access for other micro services. For that you define here - Oauth2RestTemplate Bean.
And in the end, secure your REST API, via the standard configuration Component.
So, you can see that, it is a large work, and couldn't be described with code, show some of your work, divide it to the chunk, and ask interesting your questions.

Spring Boot Authorization Only With Spring Security JWT

I am working on securing a REST API, here is the basic set up (Happy Path) I am working with:
1) UI will request to authenticate with another service, this service will return a JWT to the UI.
2) Once a user of the UI is done with their work, they will make a request to the REST API that I am tasked with securing using a JWT that is passed to me.
3) I will then ensure the JWT is legit, get the users roles and then determine if the user is authorized to access that endpoint (perform the requested function).
I am sure this is possible, but my past experience with Spring Security wasn't dealing with JWT or Authorization only.
Would it be a correct approach to implement Authentication and Authorization, get that working and then back out the Authentication part?
Thank you for your kind help!
I suggest that you take a look at the Spring Security OAuth2 project. It makes this kind of thing fairly easy.
In particular, have a look at this section about using JWT

Can spring security parse headers and verify authentication information?

Spring Security is commonly used for authentication and authorization of web applications and web services. While spring can validate users based on credentials_id (user id) and credentails_secret (password) passed through web forms.
What I am looking at is
1) can spring work when these userid and password are passed through http headers.
2) on subsequent requests can spring validate user based on a session id (some thing like jsessionid) passed through http headers?
You can add spring-security module in your project.
passing username and password via http-headers for every request is stateless basic-authentication. Check this example
You can do a stateful authentication: authenticate once, maintain the session.
Check this sample
So, you should write a custom AuthenticationFilter extending referred UsernamePasswordAuthenticationFilter.
Checkout:
Spring Security using HTTP headers

Resources