[JAVA] Microservices in Spring Cloud

Use Spring cloud to configure a simple microservice. Use OAuth2 to log in so that you can log in with your Google account. The source is https://github.com/jun-1/spring-cloud-microservices

overall structure

Web-service performs dialogue with clients such as browsers and login processing, and requests various functions from backend-service. At this time, register the service in discovery-service so that each service can find each other.

image

Implementation of discovery service

You can implement the Eureka server as a service registry simply by creating a spring-boot application annotated with @EnableEurekaServer. You can also check the status from http: // localhost: 8761.

package demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

@EnableEurekaServer
@SpringBootApplication
public class DeiscoveryServiceApplication {

	public static void main(String[] args) {
		SpringApplication.run(DeiscoveryServiceApplication.class, args);
	}
}

Set the port number and yourself so that they are not registered in the registry.

eureka:
  client:
    register-with-eureka: false
    fetch-registry: false
server:
  port: 8761

implementation of web-service

First, get the client ID and client secret used by OAuth.

Google credential creation

Create your credentials at https://console.developers.google.com.

image

From Credentials, click Create Project to create the project.

image

Select the OAuth client ID and create the credentials. (If you have not created the OAuth consent screen, create it)

image

If you want to run on localhost, select [Other] and click the [Create] button to get the client ID and client secret of the OAuth client.

Application implementation

The role of web-service is to interact with clients, log in, and reverse proxy to backend-service.

With @EnableZuulProxy, you can use Zuul to act as a reverse proxy without having to manage CORS and authentication concerns separately. Single sign-on based on OAuth2 can be realized by adding @ EnableOAuth2Sso.

package demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@EnableEurekaClient
@EnableZuulProxy
@EnableOAuth2Sso
@SpringBootApplication
public class WebServiceApplication extends WebSecurityConfigurerAdapter{

	public static void main(String[] args) {
		SpringApplication.run(WebServiceApplication.class, args);
	}
	
	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.authorizeRequests()
			.antMatchers("/", "index.html").permitAll()
			.anyRequest().authenticated();
	}
}

configure () sets that authentication is required to access URLs other than index.html. Next is the web-service settings.

spring:
  application:
    name: web-service
eureka:
  client:
    service-url: 
      defaultZone: http://localhost:8761/eureka
zuul:
  ignored-services: '*'
  routes:
    backend-service: 'api/**'
security:
  oauth2:
    resource:
      user-info-uri: https://www.googleapis.com/oauth2/v1/userinfo
    client:
      access-token-uri: https://accounts.google.com/o/oauth2/token
      user-authorization-uri: https://accounts.google.com/o/oauth2/auth
      client-id: ${clientId}
      client-secret: ${clientSecret}
      grant-type: code
      scope: profile

The service will be registered with the Eureka server with the name set in spring.application.name. The registration destination server is specified by ╩╗eureka.client.service.url.defaultZone`.

The zuul setting is set to forward requests to api / ** to backend-service. Here, you can use the service name registered on the Eureka server as the forwarding destination.

The security setting is the OAuth2 client setting. Here, use the client ID and client secret obtained earlier.

backend-service

backend-service is an OAuth2 client and implemented as a resource server.

package demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableOAuth2Client;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;

@EnableEurekaClient
@EnableOAuth2Client
@EnableResourceServer
@SpringBootApplication
public class BackendServiceApplication {

	public static void main(String[] args) {
		SpringApplication.run(BackendServiceApplication.class, args);
	}
}

The following is a controller that just returns the string'Hello', but it will not be accessible without OAuth2 authentication. When accessing via web-service, Zuul Proxy relays the authentication token, so if you are logged in with web-service, you can call it with / api / hello.

package demo.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class BackendController {
	
	@RequestMapping("/hello")
	public String hello(){
		return "Hello";
	}
}

You can also use OAuth2RestTemplate as shown below to easily perform Rest communication with other services.

    @Bean
    @LoadBalanced
    public OAuth2RestTemplate oAuth2RestTemplate(OAuth2ProtectedResourceDetails resource, OAuth2ClientContext context){
        return new OAuth2RestTemplate(resource, context);
    }

Recommended Posts

Microservices in Spring Cloud
Configure microservices with Spring Cloud (4): API Gateway
Inject Logger in Spring
Spring Cloud Netflix Note
Use Interceptor in Spring
Get cookies in Spring
Try gRPC in Spring Boot & Spring Cloud project (Mac OS)
Set context-param in Spring Boot
Spring Cloud Stream demo released
Error in Spring database connection
Major changes in Spring Boot 1.5
NoHttpResponseException in Spring Boot + WireMock
Create microservices with Spring Boot
Loop step in Spring Batch
How to use Lombok in Spring
Call Chain from Chain in Spring Integration
Spring Boot Hello World in Eclipse
Spring Boot application development in Eclipse
Java Spring environment in vs Code
Write test code in Spring Boot
I participated in JJUG CCC 2019 Spring
Implement reCAPTCHA v3 in Java / Spring
Store session information in database in Spring Session
Oauth2 authentication with Spring Cloud Gateway
Implement REST API in Spring Boot
Google Cloud Platform with Spring Boot 2.0.0
Event processing is performed in Spring.
Spring Cloud Config Embedding the Config Server
Implement Spring Boot application in Gradle
Let's thoroughly explain Spring Cloud Gateway
Microservices With Docker and Cloud Performance
Thymeleaf usage notes in Spring Boot
[Cloud9] Address already in use [Solution]
Spring Autowired is written in the constructor
Launch (old) Spring Boot project in IntelliJ
Convert request parameter to Enum in Spring
Support Protocol Buffers for Spring Cloud Stream
Build Spring Boot + Docker image in Gradle
Static file access priority in Spring boot
How to include Spring Tool in Eclipse 4.6.3?
Output Spring Boot log in json format
Local file download memorandum in Spring Boot
Handle system environment variables in Spring application.properties
Create Java Spring Boot project in IntelliJ
Loosen Thymeleaf syntax checking in Spring Boot
Separate Task Executors used in Spring @Async
[Practice! ] Display Hello World in Spring Boot
How Dispatcher servlet works in Spring MVC
Use DynamoDB query method in Spring Boot
Null support cache in Spring Data Redis
To write Response data directly in Spring
Major changes in Spring Framework 5.0 core functionality
What I got into @Transactional in Spring
Switching beans by profile annotation in Spring
Install the IBM Cloud CLI in the container
Rails server cannot be started in Cloud9
DI SessionScope Bean in Spring Boot 2 Filter
[* Java *] I participated in JJUG CCC 2019 Spring
Maven configuration problem in Spring pom.xml in Eclipse
Change session timeout time in Spring Boot
File output bean as JSON in spring