How to Implement Oauth2 Security in Microservices
Implementing Oauth2 Security in microservices distributed systems using Oauth2, Oauth2-Client, Spring Cloud and Netflix components with full example.
Join the DZone community and get the full member experience.Join For Free
I wanted a solution where we can easily captured
Oauth2 and Oauth2 client for the secure communication with all of the
microservices. Focusing, how to achieve oauth2 full flavor into
microservices architecture. User can’t access API without token. The token will be available when user given basic and authentication details to generate token for access API.
All requests will consider one entry point API-Gateway but, service-to-service can communicate. The API-Gateway will dynamic routing using
Zuul Netflix OSS component. Every request will check authorization when request will arrived into service and service will request authorization server to verify is either authenticate or not. The entire Meta configuration settled into the central configuration on
github (You can manage on any repository).
- Achieve authentication/authorization, based on
Spring security, Oauth2, Oauth2 client
- Understanding microservices architecture using
- Demonstration of microservice architecture based on
Java, Spring and Oauth2.
What Are Microservices?
Microservices is a service-oriented architecture pattern where in applications are built as a collection of various smallest independent service units. It is a software engineering approach which focuses on decomposing an application into single-function modules with well-defined interfaces. These modules can be independently deployed and operated by small teams who own the entire life-cycle of the service.
Spring Cloud and Microservice
Firstly, we do not write a microservice. We write a service which eventually will be called microservice when deployed with other services to form an application.
Having said that, Spring cloud just gives you abstractions over some set of tools (
eureka, zuul, feign, ribbon etc.) making it easy for you to integrate with spring applications.
However, you can also achieve microservice architecture without using spring cloud. You can take advantage of tools like
Kubernetes, docker swarm, haproxy, Kong, nginx etc to achieve the same. The advantage of not using spring cloud has its own pros and cons and vice versa.
High Level Microservice Architecture With Authorizations
- User login into the system using basic authorization and login credentials.
- User will got token if user basic auth and login credentials is matched.
- Next, user send request to access data from service. the API gateway recive the request and check with authorization server.
- Every request have one entry point API Gateway
- Security checking and dynamically routing to the service
- Every service have single database to manipulate data.
Spring Cloud Key Concept and Features
- Spring Cloud works for microservices to manage configuration
- Intelligent routing and services discovery
- Service -to- service call
- Load balancing (It is proper distributed network traffic to the backend server)
- Leadership election (The Application work with another application as a third-party system)
- Global Lock (Two thread are not accessed simultaneously for the same resource same time)
- Distributed configuration and messaging
If you want to avail many services in one application, then the cloud-based application is an easy way. Spring Cloud works is the same way.
Spring Boot Key Concept and Features
- Spring boot works to create microservices
- Spring Application create stand-alone spring application
- Web Application HTTP Embedded (
Tomcat, JTTY or Undertrow) No need to deploy war file.
- Externalized Configuration
- Security (It is secure in built with basic authentication on all http endpoint)
- Application Event and Listener
- Spring Boot works on product-based web application. It used for unit test development and integration test time reduce.
Spring Cloud Advantage:
- It is provided cloud service development
- It is microservice-based architecture and configuration
- It provides inter service communication
- It is based on Spring Boot model.
Spring Cloud Have Main 5 Annotations:
This Annotation converts the application into server in which more application use to get their configuration.
This annotation is used for Eureka Discovery Services for other application which can be used to locate services using it.
Helping of this annotation application register in the service discovery, it discovers others services using it.
Use the circuit breaker pattern to continue operating when related service fail and prevent cascading failure. This annotation used for Hystrix Circuit Breaker.
Hystrix is a Latency and Fault Tolerance Library for Distributed Systems.
Overview of Netflix Components
Spring Cloud Netflix provides
Netflix OSS integrations for Spring Boot apps through autoconfiguration and binding to the Spring Environment and other Spring programming model idioms. With a few simple annotations you can quickly enable and configure the common patterns inside your application and build large distributed systems with battle-tested Netflix components. The patterns provided include
Service Discovery (Eureka),
Circuit Breaker (Hystrix),
Intelligent Routing (Zuul) and
Client-Side Load Balancing (Ribbon).
Eureka (Service Registration and Discovery)
- REST service which registers itself at the registry (Eureka Client) and
- Web application, which is consuming the REST service as a registry-aware client (Spring Cloud Netflix Feign Client).
Ribbon (Dynamic Routing and Load Balancer)
- Ribbon primarily provides client-side load balancing algorithms.
- APIs that integrate load balancing, fault tolerance, caching/batching on top of other ribbon modules and Hystrix
- REST client built on top of Apache HttpClient integrated with load balancers (deprecated and being replaced by ribbon module
- Configurable load-balancing rules
Hystrix (Circuit Breaker):
- Hystrix is a fault tolerance java library. This tool is designed to separate points of access to remote services, systems, and 3rd-party libraries in a distributed environment like Microservices. It improves overall system by isolating the failing services and preventing the cascading effect of failures.
Zuul (Edge Server):
- Zuul is the front door for all requests from devices and web sites to the backend of the Netflix streaming application.
- Zuul will serve as our API gateway
- Handle dynamic routing
- Zuul is built to enable dynamic routing, monitoring, resiliency and security.
What Is a Feign Client?
Netflix provides Feign as an abstraction over REST-based calls, by which
microservices can communicate with each other, but developers do not have to bother about REST internal details.
Feign Client, which works on the declarative principle. We must create an interface/contract, then Spring creates the original implementation on the fly, so a REST-based service call is abstracted from developers. Not only that — if you want to customize the call, like encoding your request or decoding the response in a Custom Object, you can do it with Feign in a declarative way. Feign, as a client, is an important tool for
microservice developers to communicate with other
microservices via Rest API.
The Feign client uses a declarative approach for accessing the API. To use it, we must first enable the Spring Cloud support for it on our Spring Boot Application with the
@EnableFeignClients annotation at the class level on a
Server Side Load Balancing:
In JavaEE architecture, we deploy our war/ear files into multiple application servers, then we create a pool of server and put a
load balancer (Netscaler) in front of it, which has a public IP. The client makes a request using that public IP, and Netscaler decides in which internal application server it forwards the request by round robin or sticky session algorithm. We call it server side load balancing.
- Java 8+
- Spring Latest
- Spring security
- Oauth2, Oauth2 Client
- Spring Cloud
- Netflix OSS
Create Project Structure:
Step 1: Create Project
"central configuration" for All of the Services
With microservices, we create a central config server where all configurable parameters of micro-services are written version controlled. The benefit of a central config server is that if we change a property for a microservice, it can reflect that on the fly without redeploying the microservice.
You can create project use this link: https://start.spring.io/.
Hints: You can use your git server or local machine, New service name will be add if new service introduce..
EhealthCentralConfigurationApplication.Java Class example:
You must include annotation
Example of create central configuration for services:
Hints: create folder <projectName> / <projectName-development.properties>
Step 2 Create Project
"Discovery Server" for all of the Discoverable Services.
About the discovery server — already discussed in this article.
We can enable and disable other actuator endpoints through property files.
If you want to enable all actuator endpoints, then add following property.
To enable only specific actuator endpoints, provide the list of endpoint id.
In some cases, it may be desirable to fail startup of a service if it cannot connect to the Config Server. If this is the desired behavior, set the bootstrap configuration property
spring.cloud.config.fail.Fast=true and the client will halt with an Exception.
EurekaServiceDiscoveryApplication.java Class Example:
You must include annotation
Step 3 Create Project "
API Gateway" for All of the Services Entry Point.
This is the most valuable potion. Here, we write the authorization server in the same project
API Gateway Project Structure
Here, Define time-out for every separate services, you can used default. for more information please visit: https://www.cars24.com/blog/hystrix-how-to-handle-cascading-failures-in-microservices/
Central Configuration Example:
Zuul filtered 4-types while doing dynamic routing.
Zuul filters store request and state information in (and share it by means of) the RequestContext. You can use that to get at the HttpServletRequest and then log the HTTP method and URL of the request before it is sent on its way.
error filter, pre filter, post filter, route filter
EhealthApiGatewayApplication.java Class Example:
EhealthApiGatewayApplication.java class Annotation. Please, see above if not clear.
Spring security and Oauth2 implementation in microservices architecture:
You must be expert in spring security and oauth2. I have done Oauth2 implementation base on Spring security. please, visit my github link.
Step 4 Create a Project
"patient-management-service" Patient-related Data will Be Manipulated
PatientManagementServiceApplication.java class example:
You must be annotated
@EnableDiscoveryClient in the class. Because of Eureka server will be discovered as service or client..
ResourceServerConfig.java, WebSecurityConfig.Java class example:
You need a
WebSecurityConfigurerAdapter to secure the /authorize endpoint and to provide a way for users to authenticate. A Spring Boot application would do that for you (by adding its own
WebSecurityConfigurerAdapter with HTTP basic auth). It creates a filter chain with order=0 by default, and protects all resources unless you provide a request marcher.
@EnableResourceServer does something similar, but the filter chain it adds is at order=3 by default.
WebSecurityConfigurerAdapter has an @Order(100) annotation. So first the ResourceServer will be checked (authentication) and then your checks in your extension of WebSecurityConfigureAdapter will be checked.
Let's Start Demo:
Step 1 — Generate Token:
Project Run Sequence: CentralConfigServer->DiscoveryServer->API Gateway Server-> Others Service.
Client Details In Database:
Call Patient Management Service (Zuul Dynamic Routing):
Direct Call Patient Service (Token Verify from Auth Server) without token u can't call anyway.
Call Clinic Management Service (Zuul Dynamic Routing):
I am trying to show Oauth2 implementation in microservice architecture with secure communication, Single entry point, Dynamic Routing, Fail back Solutions, centralized configurations and Oauth2-client implementation in service to secure every API and every request ensure authorization.
Full Source Code Here:
Opinions expressed by DZone contributors are their own.