Implementing authentication and authorization using Zuul Proxy, Oauth2 on REST Microservices - spring-boot

I am trying to implement the above architecture in the workflow with Spring Boot.
Web client makes a request to Resource Server (Microservices Endpoints) through Zuul Proxy.
Zuul Proxy redirects to oauth2 server for authentication.
Oauth2 redirects to Zuul Proxy if the request is authenticated or not.
If not authenticated, Zuul redirects Web client with an unauthenticated response.
If Authenticated, Zull proxy redirects to the requested microservice endpoint.
Microservice endpoint checks if the user is authorized (user level access) to access the resource or not.
Microservice also could make internal rest call to other microservice.
Finally, the requested resource is sent back to the client.
I want to make sure I am following the correct workflow.
I would like to know if there is any solution which has implemented a similar kind for securing microservices APIs.
I have confusion on:
How can we pass the user details to the microservices so that the microservices can do their own level of user authorization?
Should the OAuth2 Access Token header be passed to each microservices such that microservices can validate the token separately?
Should each Microservice use secret credentials to validate the access token so that the token cannot be forged along the request chain?
I know its a bit of lengthy question. But I have not found a proper solution to above architecture.

Unfortunately, I don't have complete answer, only some parts:
Once JWT token is available to the zuul proxy then every microservice can authorize requests by configuring its resource server, e.g.
#Override
public void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests().anyRequest().access("#oauth2.hasScope('microserviceA.read')").and()
.csrf().disable()
.httpBasic().disable();
}
Scopes could be managed by the oauth microservice with a database - basing on the client credentials it will take the scopes info and encode into JWT token.
What I don't know at the moment - how to make the zuul proxy to use "web client" credentials to authorize itself by the oauth - I don't want to hard-code zuul proxy credentials because then the web-client creds won't be used.
I've just posted similar question on this topic:
Authorizing requests through spring gateway with zool via oauth server
update:
I've found article describing almost this configuration (without eureka, but it doesn't that add much complexity from my experience): https://www.baeldung.com/spring-security-zuul-oauth-jwt, there is github project with source code. The source code is unfortunately not polished as it's being used by the author for his commercial courses.
But I've managed to build from his examples working set.
Summary: in the described architecture every resource server (microservice A, B, ..) receive JWT token forwarded by the zuul proxy/gateway from the requesting client. The token is forwarded in a request header. If there is no valid token provided then the gateway will redirect the request to authorization page.
Also every resource server can check the token with the oauth service and if required do scope checking as I wrote above.

I've been struggling with same security design issue for microservice architecture based on spring cloud solution. I only find this article shedding some light on it: https://developer.okta.com/blog/2018/02/13/secure-spring-microservices-with-oauth
But it's pertaining to Okta sso service provider, not a generic solution to other oauth2 server like keycloak.
I also saw some solutions on how to protect gateway and microservice with oauth2 server like this one:
https://github.com/jgrandja/oauth2login-gateway
But it doesn't take into consideration the web client.

I am not sure whether you were able to resolve this, I can see this is not answered yet, but there is a way you can pass all information from JWT to all downstream microservices.
Write your own ZuulAuthenticationFilter, and then create below method
private void addClaimHeaders(RequestContext context, String token) {
try {
Map<String, Claim> claims = jwtTokenVerifier.getAllClaims(token);
claims.forEach((key, claim) -> {
context.addZuulRequestHeader("x-user-info-"+key, String.valueOf(claim.as(Object.class)));
});
}catch(Exception ex) {
log.error("Error in setting zuul header : "+ex.getMessage(), ex);
}
}
this way, you will get information from JWT in headers in each microservice, headers that starts with "x-user-info-" will have your JWT details

There is an implementation of the above architecture in following link:
https://www.baeldung.com/spring-security-zuul-oauth-jwt

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.

Microservices architecture - Spring boot - Gateway

I'm developing a back-end with microservices architecture. I'm new about that architecture and for now I have developed 3 microservices (RESTful web services, with Spring Boot) each in a container.
I want to implement OAuth2 and JWT Rest Protection and a gateway.
Is it correct to implement a gateway with Authorization Server and Resource Server?
Am I doing something wrong about the architecture?
Thanks for the replies
As per the standard, should not mix gateway with authorization because both the purposes are different.
Gateway
Gateway can be differentiated in two ways - Internal and External. Purpose of gateway is to route the call from external or internal to the protected resource.
Authorization Server
Authorization server comes into the picture for identity access management. All the request coming from external or internal via gateway should be authenticated or authorized before routing call to the protected resource with JWT or access token etc.
https://medium.com/swlh/authentication-and-authorization-in-microservices-how-to-implement-it-5d01ed683d6f
Authentication and Authorization - There should be a separate service that authentication the user (like supporting OAuth0 type of protocol and providing JWT Token). Your frontend should call API Gateway.
Now question comes at what granular level you are maintaining permissions - Only small set of roles or granular level of permission set. Now API Gateway should communicate with Authorization server with JWT and get the set of roles and permission. Based on the same, API gateway should forward or block the call to Microservice.
Even if you have small set of roles and JWT can be extracted and validated by Gateway but avoid to keep the same at Gateway as there are chances that you have to extract the functionality to some other service in near future.

How to secure Spring Cloud microservices using Spring Security?

Here is the authorization service. It has endpoints to login and receive a JWT using either a custom username/password or social OAuth (Facebook, GitHub etc.).
I have a Eureka server setup and Zuul gateway service. From what I understand, there are two ways to go about implementing secure microservices. You either proxy requests through the auth service, or you send requests to the requested service (Ex. Service A) and service A authorizes using the auth service.
I would like to use the second way, however I'm having trouble implementing it. Is my understanding correct? Is there a way to setup service A somehow so that certain paths (configured using Ant matchers) will have to authorize using the auth service, which will set the SecurityContext appropriately and inject a UserPrincipal into the request. If anyone can point me to a good guide for this that would be much appreciated.

Keycloak authentication flow in a microservices based environment

I want to use Keycloak in a microservices based environment, where authentication is based on OpenID endpoints REST calls ("/token", no redirection to keycloak login page), a flow that I thought of would be something like this:
1. Front-end SPA retrieves the tokens from the "/token" endpoint and stores in browser's localStorage, then sends it with every request.
2. Gateway-level authentication: Acess Token is passed from the front end to the gateway, gateway consults Keycloak server to check if the token is still valid (not invalidated by a logout end-point call).
3. Micro-service based authorization: Acess Token is passed from the Gateway to the microservices, using Spring Boot adapter the microservices check the signature of the token offline (bearer-only client?) then based on the role in the token do the authorization.
My questions are: Does this flow make sense or can you suggest another flow? What type of Keycloak clients to use? What's an ideal way to pass Tokens using Spring Boot Adapter, and should it be done like that in the first place? Please keep in mind that I am not a Keycloak expert, I've done my research but I still have doubts.
Your Front-end SPA should be public-client and springboot micro service should be Bearer only Client and Gateway could be Confidential Client.
You can check the Keycloak provided oidc adapters. For springboot you use the keycloak provided adapter
Similar solution using api gateway is discussed here

Get current authenticated user from all other microservices

I am creating a project with microservices architecture using spring. I have zuul for centralized security management, and some other microservices.
To access current authenticated user, in zuul i use this line of code :
SecurityContextHolder.getContext().authentication
But to get the user from other microservices, i extract the token (jwt) from the header in each request, and then i extract user info from the claims, but i find this method is a little annoying.
So, is there another more pretty method?
I tried to add the dependencies of spring security in the other microservices to use :
SecurityContextHolder.getContext().authentication
but every time i execute a request through zuul, even if the authentication is done from there, i get an unauthorized error message, despite having disabled the security autoconfiguration from these microservices.
Any suggestion?
Using SecurityContextHolder.getContext().authentication won't work in other microservices until you set the principal object in the Spring SecurityContext.
I don't know why you are setting the principal in security context at Zuul and extracting the same there, But yes Authentication and token validation should be done at Zuul and same jwt should be sent to backend microservices in header.
Now in backend microservices, By using spring security, extract the required claims from jwt and put in the SecurityContextHolder once, So that you can utilize it further for request authorizations or method level authorizations too.

Resources