Add social based login (Google, Facebook, and Github) to your Spring Boot application using OAuth2 functionalities

In the tutorial, we will explain how to add social-based login to a Spring boot application using a Spring Security function called OAuth2. We use MySQL database and React for the frontend.

App Screenshot

Creating the Project

You can create a project using the Spring Initializr web tool http://start.spring.io, follows the introduction to fill in the information:

  • Artifact: ozenero-spring-social
  • Dependencies: Spring Web, Spring Security, OAuth2 Client, Spring Data JPA, MySQL Driver, Validation

After that, you can click Generate and download your project

Creating OAuth2 apps for social login

You need to create an app in OAuth2 provider console to enable social login with an OAuth2 provider. After that, you can get AppID and AppSecret (also called ClientId and Client Secret). OAuth2 providers use the AppID and AppSecret to identify your app. Some other settings include:

  • Authorized redirect URIs: A valid list of redirect URIs to redirect users after granting or rejecting permission to the app.
  • Scope: used to ask users for permission to access data.

Creating Facebook, Github, and Google Apps

Configuring the Spring Boot application

By default, Spring boot reads configurations from the file src/main/resource/application.properties. It also supports .yaml format. Rename application.properties file to application.yaml and add the following configurations.

spring:
    datasource:
        url: jdbc:mysql://localhost:3306/spring_social?useSSL=false&serverTimezone=UTC&useLegacyDatetimeCode=false
        username: root
        password: callicoder

    jpa:
        show-sql: true
        hibernate:
            ddl-auto: update
            naming-strategy: org.hibernate.cfg.ImprovedNamingStrategy
        properties:
            hibernate:
                dialect: org.hibernate.dialect.MySQL5InnoDBDialect
    security:
      oauth2:
        client:
          registration:
            google:
              clientId: your_id.apps.googleusercontent.com
              clientSecret: your_secret
              redirectUri: "{baseUrl}/oauth2/callback/{registrationId}"
              scope:
                - email
                - profile
            facebook:
              clientId: your_id
              clientSecret: your_secret
              redirectUri: "{baseUrl}/oauth2/callback/{registrationId}" # Note that facebook now mandates the use of https redirect URIs, so make sure your app supports https in production
              scope:
                - email
                - public_profile
            github:
              clientId: your_id
              clientSecret: your_secret
              redirectUri: "{baseUrl}/oauth2/callback/{registrationId}"
              scope:
                - user:email
                - read:user
          provider:
            facebook:
              authorizationUri: https://www.facebook.com/v3.0/dialog/oauth
              tokenUri: https://graph.facebook.com/v3.0/oauth/access_token
              userInfoUri: https://graph.facebook.com/v3.0/me?fields=id,first_name,middle_name,last_name,name,email,verified,is_verified,picture.width(250).height(250)
app:
  auth:
    tokenSecret: your_token_secret
    tokenExpirationMsec: 864000000
  cors:
    allowedOrigins: http://localhost:3000 # Comma separated list of allowed origins
  oauth2:
    # After successfully authenticating with the OAuth2 Provider,
    # we'll be generating an auth token for the user and sending the token to the
    # redirectUri mentioned by the client in the /oauth2/authorize request.
    # We're not using cookies because they won't work well in mobile clients.
    authorizedRedirectUris:
      - http://localhost:3000/oauth2/redirect
      - myandroidapp://oauth2/redirect
      - myiosapp://oauth2/redirect

The data source includes MySQL database configurations. Database name is spring_social, please modify spring.datasource.username and spring.datasource.password.

In security:oauth2:client:registration:, the configurations include all details of oauth2 providers. Inapp.auth, its config the JWT authentication token when the user logged in successfully.

In redirectUriTemplate property in all the registered oauth2 providers, when you create an app in the OAuth2 providers, you have to add an authorized redirect URI which matches the template. In this case, for a google app, we config the authorizedRedirectURI http://localhost:8080/oauth2/callback/google.

Binding AppProperties

In the next step, we bind all configurations prefixed with app to a POJO class using Spring Boot’s @ConfigurationProperties feature

package com.example.springsocial.config;

import org.springframework.boot.context.properties.ConfigurationProperties;

import java.util.ArrayList;
import java.util.List;

@ConfigurationProperties(prefix = "app")
public class AppProperties {
    private final Auth auth = new Auth();
    private final OAuth2 oauth2 = new OAuth2();

    public static class Auth {
        private String tokenSecret;
        private long tokenExpirationMsec;

        public String getTokenSecret() {
            return tokenSecret;
        }

        public void setTokenSecret(String tokenSecret) {
            this.tokenSecret = tokenSecret;
        }

        public long getTokenExpirationMsec() {
            return tokenExpirationMsec;
        }

        public void setTokenExpirationMsec(long tokenExpirationMsec) {
            this.tokenExpirationMsec = tokenExpirationMsec;
        }
    }

    public static final class OAuth2 {
        private List<String> authorizedRedirectUris = new ArrayList<>();

        public List<String> getAuthorizedRedirectUris() {
            return authorizedRedirectUris;
        }

        public OAuth2 authorizedRedirectUris(List<String> authorizedRedirectUris) {
            this.authorizedRedirectUris = authorizedRedirectUris;
            return this;
        }
    }

    public Auth getAuth() {
        return auth;
    }

    public OAuth2 getOauth2() {
        return oauth2;
    }
}

Enabling AppProperties

In order to enable the properties, we add the@EnableConfigurationProperties annotation. Let’s open the main application class SpringSocialApplication.java and add the annotation like below.

package com.example.springsocial;

import com.example.springsocial.config.AppProperties;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;

@SpringBootApplication
@EnableConfigurationProperties(AppProperties.class)
public class SpringSocialApplication {

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

Enabling CORS

In order to enable CORS to allow our frontend client can access the APIs from a different origin. We need to enable the origin http://localhost:3000 where the frontend application will be running.

package com.example.springsocial.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    private final long MAX_AGE_SECS = 3600;

    @Value("${app.cors.allowedOrigins}")
    private String[] allowedOrigins;

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
        .allowedOrigins(allowedOrigins)
        .allowedMethods("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS")
        .allowedHeaders("*")
        .allowCredentials(true)
        .maxAge(MAX_AGE_SECS);
    }
}

Creating the database entities

Let’s now create the Entity classes of our application. Following is the definition of the User class –

In the next step, we create Entity classes for the application. You can define the User class like below.

package com.example.springsocial.model;
import com.fasterxml.jackson.annotation.JsonIgnore;

import javax.persistence.*;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotNull;

@Entity
@Table(name = "users", uniqueConstraints = {
        @UniqueConstraint(columnNames = "email")
})
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false)
    private String name;

    @Email
    @Column(nullable = false)
    private String email;

    private String imageUrl;

    @Column(nullable = false)
    private Boolean emailVerified = false;

    @JsonIgnore
    private String password;

    @NotNull
    @Enumerated(EnumType.STRING)
    private AuthProvider provider;

    private String providerId;

    // Getters and Setters (Omitted for brevity)
}

The User class contains information about the authentication provider. Following is the definition of the AuthProvider enum –

In the User class, it provides information related to the authentication provider. Here is the definition of the AuthProvider enum.

package com.example.springsocial.model;

public enum  AuthProvider {
    local,
    facebook,
    google,
    github
}

Creating the repositories for accessing data from the database

Let’s create the repository layer for accessing data from the database. The following UserRepository interface provides database functionalities for the User entity. Thanks to Spring-Data-JPA, we don’t need to write much code here

In order to create the repository layer for accessing data from the database, we need to config theUserRepository interface to provide database functionalities for the User entity. Refer to Spring-Data-JPA  for the code

package com.example.springsocial.repository;

import com.example.springsocial.model.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import java.util.Optional;

@Repository
public interface UserRepository extends JpaRepository<User, Long> {

    Optional<User> findByEmail(String email);

    Boolean existsByEmail(String email);

}

In this article, we introduce how to configure an application and defined the entity classes and repositories.

Tutorial to use Tuya Cloud Development Platform for your first IoT Development Practice

In the tutorial, we will introduce how to configure a Tuya Cloud Project, add devices, create a simulation with virtual devices, debug devices, and use Tuya-connector-Python SDK to develop a program to control ‘Powered by Tuya’ devices.

Configure Cloud Project

After registering an account at https://iot.tuya.com/, log in and go to Cloud>Development, choose to Create Cloud Project.

Fill the information in Project Name, Description, Development Method, Industry, Availability Zone.

To understand about development method, see Development Method.

Click Create and subscribe to the API products On the Authorize API Products page -> Click Authorize

Next, create the original asset and original account

Add Virtual device

Add devices with IoT Device Management app

In order to add your physical devices, you need to install the IoT Device Management app. After installing the IoT Device Management app, click Add Device -> Add Devices with IoT Device Management App, and the Scan the QR code with the IoT Device Management app to authorize the project.

You can log in to the IoT Device Management app using the initial account configured when the project was created. You also manage your account and the Tab Users.

After login, you can create your Assets and Pair your Smart Device.

A device can be added in two methods, Add Manually and Auto Scan. They are similar to those used to add devices on all-in-one apps. For more information, see Add a device.

Make a simulation with Virtual devices

You can create a simulation by adding Virtual devices to your cloud project. Choose Cloud->Development->Devices->All Devices->Add Device->Add Virtual Device

You can choose different types of devices for your application such and home security, household appliance, Health & Personal Care.

You can click “Buy” the physical devices at a good price. Tuya also provides OEM solutions for your product, when you can customize Logo, packing, User material, and user apps.

 

Debug Devices

You can make your simulation and use debugging feature to send instructions to control your devices.

Choose Cloud -> Development -> select your project -> Devices -> Debug Devices

Modify your  Value in Instruction Set -> Click Send Instruction

You also can modify the Instruction Set by choosing JSON Editing

You can click Update Device Status to get the Lastest status of the device.

Click Device Logs, you can query logs by DP ID, device event, and time.

Develop a program to control ‘Powered by Tuya’ devices

Next step, we can use Tuya-connector-Python SDK to control your devices through your Cloud development projects.

Firstly, download the SDK at Tuya-connector-Python.

You need to install a tuya-connector-python on your computer for requirements.

pip3 install tuya-connector-python

You need to modify ACCESS_ID, ACCESS_KEY, API_ENDPOINT, MQ_ENDPOINT to connect to your Cloud Project.

Go to Overview Tab to get that parameters

ACCESS_ID and ACCESS_KEY: Enter the values of Access ID and Access Key in the Authorization Key section on the Cloud Development Platform. For more information, see Query project information.

API_ENDPOINT: the data center address of API requests. See the tuya-connector-python/tuya_connector/tuya_enums.py file.

MQ_ENDPOINT: the request address of message subscription.

Location API_ENDPOINT MQ_ENDPOINT
China https://openapi.tuyacn.com wss://mqe.tuyacn.com:8285/
America https://openapi.tuyaus.com wss://mqe.tuyaus.com:8285/
Europe https://openapi.tuyaeu.com wss://mqe.tuyaeu.com:8285/
India https://openapi.tuyain.com wss://mqe.tuyain.com:8285/

How to Control Devices with Python

Use the sample code of querying devices and issuing instructions: device_control.py.

import logging
from tuya_connector import TuyaOpenAPI, TUYA_LOGGER

ACCESS_ID = "yhyrrpky*****gc0xmj9"
ACCESS_KEY = "ad976bf8*****da383ec37311e65f554"
API_ENDPOINT = "https://openapi.tuyacn.com"

# Enable debug log
TUYA_LOGGER.setLevel(logging.DEBUG)

# Init OpenAPI and connect
openapi = TuyaOpenAPI(API_ENDPOINT, ACCESS_ID, ACCESS_KEY)
openapi.connect()

# Set up device_id
DEVICE_ID ="vdevo164024617876854"

# Call APIs from Tuya
# Get the device information
response = openapi.get("/v1.0/iot-03/devices/{}".format(DEVICE_ID))

# Get the instruction set of the device
response = openapi.get("/v1.0/iot-03/devices/{}/functions".format(DEVICE_ID))


# Send commands
commands = {'commands': [{'code': 'countdown_1', 'value': 200}]}
openapi.post('/v1.0/iot-03/devices/{}/commands'.format(DEVICE_ID), commands)

# Get the status of a single device
response = openapi.get("/v1.0/iot-03/devices/{}/status".format(DEVICE_ID))

Modify DEVICE_ID with the ID of the device you want to control. You can get the Device ID at Development->Devices->All Devices

In the above code, sent commands are modified by, you should modify the code and the value depend on your devices.

commands = {'commands': [{'code': 'switch_led', 'value': true}]} openapi.post('/v1.0/iot-03/devices/{}/commands'.format(DEVICE_ID), commands)

The return should like below


[tuya-openapi] Request: method = GET, url = https://openapi.tuyacn.com/v1.0/token, params = {'grant_type': 1}, body = None, t = 1640339456098
[2021-12-24 17:50:57,518] [tuya-openapi] Response: {
"result": {
"access_token": "***",
"expire_time": 7200,
"refresh_token": "***",
"uid": "***"
},
"success": true,
"t": 1640339457334
}
[2021-12-24 17:50:57,519] [tuya-openapi] Request: method = GET, url = https://openapi.tuyacn.com/v1.0/iot-03/devices/vdevo164024617876854, params = None, body = None, t = 1640339457519
[2021-12-24 17:50:57,964] [tuya-openapi] Response: {
"result": {
"active_time": 1640246178,
"asset_id": "1473886148148346880",
"category": "cz",
"category_name": "Socket",
"create_time": 1640246178,
"gateway_id": "",
"icon": "smart/icon/1498529014_0.png",
"id": "vdevo164024617876854",
"ip": "***",
"lat": "***",
"local_key": "***",
"lon": "***",
"model": "HYS-X5-NEW",
"name": "Mini Smart Socket-vdevo",
"online": true,
"product_id": "qoacsyyfbrbe3lm8",
"product_name": "Mini Smart Socket",
"sub": false,
"time_zone": "+08:00",
"update_time": 1640246178,
"uuid": "vdevo164024617876854"
},
"success": true,
"t": 1640339457780
}
[2021-12-24 17:50:57,965] [tuya-openapi] Request: method = GET, url = https://openapi.tuyacn.com/v1.0/iot-03/devices/vdevo164024617876854/functions, params = None, body = None, t = 1640339457965
[2021-12-24 17:50:58,382] [tuya-openapi] Response: {
"result": {
"category": "cz",
"functions": [
{
"code": "switch_1",
"desc": "switch 1",
"name": "switch 1",
"type": "Boolean",
"values": "{}"
},
{
"code": "countdown_1",
"desc": "countdown 1",
"name": "countdown 1",
"type": "Integer",
"values": "{\"unit\":\"s\",\"min\":0,\"max\":86400,\"scale\":0,\"step\":1}"
}
]
},
"success": true,
"t": 1640339458198
}
[2021-12-24 17:50:58,382] [tuya-openapi] Request: method = POST, url = https://openapi.tuyacn.com/v1.0/iot-03/devices/vdevo164024617876854/commands, params = None, body = {'commands': [{'code': 'countdown_1', 'value': 200}]}, t = 1640339458382
[2021-12-24 17:50:58,853] [tuya-openapi] Response: {
"result": true,
"success": true,
"t": 1640339458669
}
[2021-12-24 17:50:58,853] [tuya-openapi] Request: method = GET, url = https://openapi.tuyacn.com/v1.0/iot-03/devices/vdevo164024617876854/status, params = None, body = None, t = 1640339458853
[2021-12-24 17:50:59,284] [tuya-openapi] Response: {
"result": [
{
"code": "switch_1",
"value": false
},
{
"code": "countdown_1",
"value": 200
}
],
"success": true,
"t": 1640339459099
}

In the tutorial, we introduce how to create a Tuya Cloud Project, add devices and create Virtual devices to make a simulation for your different scenarios. Tuya provides APIs and SDK in Python to help you control your smart devices through Tuya Cloud Development Platform. You can apply and extend this tutorial for your experiment with Tuya Platform to build your IoT applications and services fastly.

In the next tutorial, we want to show you “how to design a Smart Security app for home and small business users”. In order to implement DIY home security, the Tuya platform can support Video surveillance, voice chat, and smart control. You can add smart devices and set up a smart home scenario. You can also view live video and cloud-stored video, and communicate timely by voice.

How to use Kong to make Orchestration Microservice API Gateway

Kong is an Orchestration Microservice API Gateway. Kong is an abstraction layer that manages client-microservice communication securely via APIs. It is sometimes called an API Gateway, API Middleware, or Service Mesh. In 2015, it became an open-source project, and its core values are high performance and extensibility.

Kong runs in Nginx as a Lua application and is enabled by Lua-Nginx-module.

Why use Kong?

If you need a common functionality to run your actual software on your website, mobile, or IoT (Internet of Things). Kong can work as a gateway (sidecar) for microservices requests, at the same time also possible to provide logging, load balancing, authentication, rate-limiting, transformations, and more through plugins.

Kong can work as a gateway (sidecar) for microservices requests

Kong also helps you to shorten development time, and support configurable plugins. It has many communities to support your development and make it stable.

Kong can add Security plugins for security layers such as ACL, CORS, Dynamic SSL, IP Restriction. It also has a useful traffic control plugin that has limited costs such as rate-limiting, request size limiting, response rate-limiting...

Support Analytics and monitoring plugin which can visualize, inspect, monitor traffic including Prometheus, data dog, and Runscope.

Support transforms requests and responses on the fly including Request Transformer, Response Transformer by Transformation plugin

Support logging request and response data using: TCP, UDP, HTTP, StatsD, Syslog, and others by Logging plugin

Here we will make a tutorial on how to set up and use KONG. You should refer to Docker and API REST for needed knowledge.

How to Install Kong Community Edition

Kong can work in multiple operating environments. The easiest installation is using docker. Follow the instruction below to install by docker.

Install KONG by docker

1. Create a docker network for Kong and API server

$ docker network create kong-net

2. Run a database. You can choose Postgres or Cassandra. We prioritize Postgres

$ docker run -d --name kong-database \
--network=kong-net \
-p 5555:5432 \
-e “POSTGRES_USER=kong” \
-e “POSTGRES_DB=kong” \
postgres:9.6

3. Run migration with Kong container after preparing a database

$ docker run --rm \
--network=kong-net \
-e “KONG_DATABASE=postgres” \
-e “KONG_PG_HOST=kong-database” \
kong:latest kong migrations up

4. After the migrations and database have been complete, start Kong container

$ docker run -d --name kong \
--network=kong-net \
-e “KONG_LOG_LEVEL=debug” \
-e “KONG_DATABASE=postgres” \
-e “KONG_PG_HOST=kong-database” \
-e “KONG_PROXY_ACCESS_LOG=/dev/stdout” \
-e “KONG_ADMIN_ACCESS_LOG=/dev/stdout” \
-e “KONG_PROXY_ERROR_LOG=/dev/stderr” \
-e “KONG_ADMIN_ERROR_LOG=/dev/stderr” \
-e “KONG_ADMIN_LISTEN=0.0.0.0:8001, 0.0.0.0:8444 ssl” \
-p 9000:8000 \
-p 9443:8443 \
-p 9001:8001 \
-p 9444:8444 \
kong:latest

4. Using the request cmd to check Kong Instance

$ curl -i http://localhost:9001

The successful response is

HTTP/1.1 200 OK
Server: openresty/1.13.6.2
Date: Wed, 18 Jul 2018 03:58:57 GMT
Content-Type: application/json
Connection: keep-alive
Access-Control-Allow-Origin: *

Now Kong is run completely. The next task is that prepare an API server containing service routes and support REST API.

Use node.js to setup API server routing

In the task, we will use node.js for an API server. For simple, you 
can clone from GitHub faren-NodeJS-API-KONG. And it should contain like this in terminal:
Now prepare the API server, for this tutorial we are going to use node.js as an API server. To make it simple, please clone the code from GitHub faren-NodeJS-API-KONG. It should contain like below:
$ ls -l
total 48
-rw-r — r — 1 farendev staff 186 Jul 18 11:37 Dockerfile
-rw-r — r — @ 1 farendev staff 31716 Jul 16 10:36 Kong.postman_collection.json
-rw-r — r — 1 farendev staff 100 Jul 18 11:37 README.md
-rw-r — r — 1 farendev staff 878 Jul 18 11:37 index.js
-rw-r — r — 1 farendev staff 307 Jul 18 11:37 package.json

Let’s build a docker image and run it, by the cmd below:

$ docker build -t node_kong .
$ docker run -d --name=node_kong --network=kong-net node_kong

Check all docker has been run by cmd below:

$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
d13586f83e52 node_kong “npm start” 2 minutes ago Up 2 minutes 10000/tcp node_kong
41156cad5c86 kong:latest “/docker-entrypoint.…” 6 days ago Up 6 days 0.0.0.0:9000->8000/tcp, 0.0.0.0:9001->8001/tcp, 0.0.0.0:9443->8443/tcp, 0.0.0.0:9444->8444/tcp kong
f794a0e9506c postgres:9.6 “docker-entrypoint.s…” 6 days ago Up 6 days 0.0.0.0:5555->5432/tcp kong-database

Get an IP container on the docker network kong-net for checking API server by accessing its API. You can get into the container kong shell and check the API from it.

Execute the cmd bellow on your terminal:

$ docker network inspect kong-net
…
…
“Containers”: {
“41156cad5c864af4ad8615c051fac8da7f683238a6c8cc42267f02813f14810f”: {
“Name”: “kong”,
“EndpointID”: “fe1cec9f6f31a015ab29a100fdd54b609abea11bbfa00f5e9ca67cc6175d7b2f”,
“MacAddress”: “02:42:ac:13:00:03”,
“IPv4Address”: “172.19.0.3/16”,
“IPv6Address”: “”
},
“d13586f83e52df8866b9879ba0537d58c21fc1b95978dde0580b017ce1a7b418”: {
“Name”: “node_kong”,
“EndpointID”: “5677f7588b7daef391cf8cecec6a3ede0155f99f7d86e0e14dd5970ff0570924”,
“MacAddress”: “02:42:ac:13:00:04”,
“IPv4Address”: “172.169.0.5/16”,
“IPv6Address”: “”
},
“f794a0e9506c7330f1cc19c5c390f745823c29dd4603e0d727dae4e8a68caa8d”: {
“Name”: “kong-database”,
“EndpointID”: “51737ca4e2a4b0e30d25db86e197e653a81e6206893588f4dae7b4a0a50e2799”,
“MacAddress”: “02:42:ac:13:00:02”,
“IPv4Address”: “172.19.0.2/16”,
“IPv6Address”: “”
}
},
…

Check the IP on node_kong in bold font and execute curl the IP bellow exactly.

$ docker exec -ti kong sh
/ # curl -i 172.169.0.5:10000/api/v1/customers
HTTP/1.1 200 OK
X-Powered-By: Express
Content-Type: application/json; charset=utf-8
Content-Length: 110
ETag: W/”6e-Tf3vAGLC3XH0dFR2pCIzWdG8/5c”
Date: Wed, 18 Jul 2018 10:09:32 GMT
Connection: keep-alive
[{“id”:5,”first_name”:”Dodol”,”last_name”:”Dargombez”},{“id”:6,”first_name”:”Nyongot”,”last_name”:”Gonzales”}]

The above respond shows that server API is alive, and can serve to GET method REST /API/v1/workers.

How to setup KONG as API – Gateway to API server routing

After completing the KONG engine and node.js API service, and starting registering our API to Kong, the image below shows the workflow.

Routes define rules to match client requests and work as entry points in Kong. When a route is matched, Kong proxies the request to its associated Service. The service will be direct to the API server that is ready to serve.

For example (Warning: IP might very different for every machine)

API server that is live on server http://172.169.0.5:10000/api/v1/customers

We set routes path /api/v1/customers

And set the service host to http://172.169.0.5:10000, and path /api/v1/customers

So, when the client request to kong (in this case kong is life at localhost:9000) with path route /api/v1/customer: incomplete client request http://localhost:9000/api/v1/customers , Kong will proxy it to 172.169.0.5:10000/api/v1/customers

To start please import postman collection file on GitHub NodeJS-API-KONG (https://github.com/faren/NodeJS-API-KONG) — kong.postman_collection.json.

So let’s see in practice take a look postman collection that has been imported:

For this tutorial, we should get the result like the above scenario:

REST for customers and clients.

Firstly, you register service customers and then register match routes requested. Let take a look at how to get node_kong IP from the docker network.

Find collection Kong, folder Services, POST Services — Create:

POST: localhost:9001/services/

Headers: Content-Type:application/json
Body:
{
“name”: “api-v1-customers”,
“url”: “http://172.169.0.5:10000/api/v1/customers"
}Respond:
{
“host”: “172.169.0.5”,
“created_at”: 1531989815,
“connect_timeout”: 60000,
“id”: “d28c20e4–94d3–4c3b-9a0d-688ac8dbf213”,
“protocol”: “http”,
“name”: “api-v1-customers”,
“read_timeout”: 60000,
“port”: 10000,
“path”: null,
“updated_at”: 1531989815,
“retries”: 5,
“write_timeout”: 60000
}

Find collection Kong, folder Services, GET Services — List:

GET: localhost:9001/services/

Respond:
{
“next”: null,
“data”: [
{
“host”: “172.169.0.5”,
“created_at”: 1531989815,
“connect_timeout”: 60000,
“id”: “d28c20e4–94d3–4c3b-9a0d-688ac8dbf213”,
“protocol”: “http”,
“name”: “api-v1-customers”,
“read_timeout”: 60000,
“port”: 10000,
“path”: null,
“updated_at”: 1531989815,
“retries”: 5,
“write_timeout”: 60000
}
]
}

After creating service customers, you can create routes for service customers.

Find collection Kong, folder Routes, POST Routes — Create:

POST: localhost:9001/services/api-v1-customers/routes/

Headers: Content-Type:application/json
Body:
{
“hosts”: [“api.ct.id”],
“paths”: [“/api/v1/customers”]
}Respond:
{
“created_at”: 1531991052,
“strip_path”: true,
“hosts”: [
“api.ct.id”
],
“preserve_host”: false,
“regex_priority”: 0,
“updated_at”: 1531991052,
“paths”: [
“/api/v1/customers”
],
“service”: {
“id”: “d28c20e4–94d3–4c3b-9a0d-688ac8dbf213”
},
“methods”: null,
“protocols”: [
“http”,
“https”
],
“id”: “4d9503c3-d826–43e3–9063-ed434a949173”
}

Find collection Kong, folder Routes, GET Routes -> List:

GET: localhost:9001/services/

Respond:
{
“next”: null,
“data”: [
{
“created_at”: 1531991052,
“strip_path”: true,
“hosts”: [
“api.ct.id”
],
“preserve_host”: false,
“regex_priority”: 0,
“updated_at”: 1531991052,
“paths”: [
“/api/v1/customers”
],
“service”: {
“id”: “d28c20e4–94d3–4c3b-9a0d-688ac8dbf213”
},
“methods”: null,
“protocols”: [
“http”,
“https”
],
“id”: “4d9503c3-d826–43e3–9063-ed434a949173”
}
]
}

Check you can access API customers from KONG (http://localhost:9000/api/v1/customers)

GET: localhost:9000/api/v1/customers

Headers: Host:api.ct.id
Respond:
[
{
“id”: 5,
“first_name”: “Dodol”,
“last_name”: “Dargombez”
},
{
“id”: 6,
“first_name”: “Nyongot”,
“last_name”: “Gonzales”
}
]

Conclusion

Kong is an open-source, scalable API Layer (API Gateway, or API Middleware), which runs in front of any RESTful API and is extended through Plugins. Kong can provide extra functionality and services beyond the core platform.

For better understanding, the image below shows a typical request workflow of an API using Kong:

When Kong is running, every request being made to the API will hit Kong first, and then it will be proxied to the final API. Kong can execute any plugin in between requests and responses. You can install many types of plugins to empower your APIs, Kong is also supported by plugins from authentication, security, traffic control, logging, and etc… Kong can be used effectively as entry points for every API request.

Angular 13 Spring WebFlux MongoDB CRUD Operations

In this tutorial, we’re gonna build a full Reactive Application in which, Spring WebFlux, Spring Data Reactive MongoDB are used for backend, and Angular, RxJS, EventSource are on client side.

Related Posts:
How to use Angular Http Client to fetch Data from SpringBoot RestAPI – Angular 13
How to use Angular HttpClient to POST, PUT, DELETE data on SpringBoot Rest APIs – Angular 13
How to build SpringBoot MongoDb RestfulApi
How to use SpringData MongoRepository to interact with MongoDB
Angular 13 + Spring Boot + MongoDB CRUD example
Introduction to RxJS – Extensions for JavaScript Reactive Streams

Continue reading “Angular 13 Spring WebFlux MongoDB CRUD Operations”

Angular 12 Spring WebFlux MongoDB CRUD RestAPI

In this tutorial, we’re gonna build a full Reactive Application in which, Spring WebFlux, Spring Data Reactive MongoDB are used for backend, and Angular, RxJS, EventSource are on client side.

Related Posts:
How to use Angular Http Client to fetch Data from SpringBoot RestAPI – Angular 12
How to use Angular HttpClient to POST, PUT, DELETE data on SpringBoot Rest APIs – Angular 12
How to build SpringBoot MongoDb RestfulApi
How to use SpringData MongoRepository to interact with MongoDB
Angular 12 + Spring Boot + MongoDB CRUD example
Introduction to RxJS – Extensions for JavaScript Reactive Streams

Continue reading “Angular 12 Spring WebFlux MongoDB CRUD RestAPI”