SlideShare ist ein Scribd-Unternehmen logo
1 von 34
Downloaden Sie, um offline zu lesen
Building a Microgateway in Ballerina
Nuwan Dias
Director - API Architecture, WSO2
@nuwandias
API Gateway
API Gateway
CLIENT DEVICES API GATEWAY MICROSERVICE
API Gateway - What does it do?
○ Request forwarding
○ URL rewrite
○ Load-balancing
○ Failover
○ Circuit breaking
○ Inbound and outbound security
○ Authentication and authorization
○ OAuth2, OIDC, API Keys, Basic auth, Digital signatures, MTLS, etc.
○ Rate limiting
○ Analytics
Ballerina Service
Ballerina Service
@http:ServiceConfig {
basePath:"/pizzashack/1.0.0"
}
service passthrough on new http:Listener (9090) {
@http:ResourceConfig {
methods:["GET"],
path:"/menu"
}
resource function getMenu (http:Caller caller, http:Request req) {
//contains request forwarding logic to target.
}
}
OAS (Swagger) document becomes the source of the
service definition
OAS
DOCUMENT
Generating the Ballerina service
OAS
DOCUMENT
Auto generate the Ballerina source
code from OAS.
Connecting to the target endpoint
Target endpoint
Forwarding request to the target
http:Client targetEndpoint = new ("https://api.pizzastore.com/pizzashack/v1");
@http:ServiceConfig {
basePath: "/pizzashack/1.0.0"
}
service passthrough on new http:Listener (9090) {
@http:ResourceConfig {
methods:["GET"],
path:"/menu"
}
resource function getMenu (http:Caller caller, http:Request req) {
. . . . . . .
}
}
Forwarding request to the target
resource function getMenu (http:Caller caller, http:Request req) {
//Forward the client request to the /menu resource of the Target Endpoint.
var clientResponse = targetEndpoint -> forward(“/menu”, req);
//Check if the response from the target Endpoint was a success or not.
if clientResponse is http:Response{
var result = caller->respond(res);
if result is error {
log:printError("Error sending response");
}
}
else {
http:Response res = new;
res.statusCode = 500;
res.setPayload(err.message);
var result = caller->respond(res);
if result is error {
log:printError("Error sending response");
}
}
Request Filters
Ballerina filter chain
FILTER1
FILTER2
FILTERn
Listeners and Filters service passthrough on new http:Listener
(9090) {
import wso2/gateway;
AuthnFilter authnFilter;
OAuthzFilter authzFilter;
RateLimitFilter rateLimitFilter;
AnalyticsFilter analyticsFilter;
ExtensionFilter extensionFilter;
listener gateway:APIGatewayListener
apiListener = new (9095, {
filters:[authnFilter, authzFilter,
rateLimitFilter,
analyticsFilter,
extensionFilter]
});
service passthrough on apiListener {
A listener is what a service binds
itself to.
A listener may have one or more
filters to filter requests being
received on the port of the listener.
Security
Authentication listener gateway:APIGatewayListener
apiListener = new (9095, {
filters:[authnFilter, authzFilter]}, {
authProviders:[jwtAuthProvider, basic]
});
http:AuthProvider jwtAuthProvider = {
scheme:"jwt",
issuer:"ballerina",
audience: "ballerina.io",
certificateAlias: "ballerina",
trustStore: {
path:
"${ballerina.home}/bre/security/ballerinaTr
uststore.p12",
password: "ballerina"
}
};
The microgateway supports
different authentication
mechanisms such as OAuth2,
basic authentication, etc.
Which mechanisms to apply
against a request is decided by the
declared authentication providers
in the listener.
Enabling/Disabling
security by service
//This service is accessible at
// /pizzashack/1.0.0 on port 9095
@http:ServiceConfig {
basePath: "/pizzashack/1.0.0",
authConfig: {
authentication: { enabled: true }
}
}
service passthrough on apiListener {
. . . . .
. . . . .
}
Each service bound to the listener
can chose to enable or disable
security by itself.
Authorization
Authorization is enabled per each
operation of the service using
‘scopes’.
Scopes are used as a means of
abstracting the authorization
mechanism.
@http:ResourceConfig {
methods:["PUT"],
path:"/menu",
authConfig: {
scopes: ["edit_menu"]
}
}
resource function editMenu (http:Caller
caller, http:Request req)
Microgateway in-bound security architecture.
CLIENT DEVICES MICROGATEWAY MICROSERVICE
SECURITY TOKEN SERVICE
1 OBTAIN TOKEN FROM
STS
2 SEND TOKEN TO MICROGATEWAY
WITH REQUEST
3
OPTIONAL VALIDATION
REQUEST FROM
MICROGATEWAY TO STS
4
FORWARD REQUEST TO
TARGET
Rate Limiting
Ballerina Streams
The RateLimitFilter on the listener
adds metadata of every
successful request into a
data-stream.
public stream<RequestStreamDTO>
requestStream;
public function
publishNonThrottleEvent(RequestStreamDTO
request) {
requestStream.publish(request);
}
Rate limiting Policies
Rate limiting policies on the
microgateway are modelled as
stream processors where it
executes logic on the data
received via the stream.
forever {
from gateway:requestStream
select messageID, (tier == "Silver")
as isEligible,
subscriptionKey as throttleKey
=> (gateway:EligibilityStreamDTO[]
counts) {
eligibilityStream.publish(counts);
}
from eligibilityStream
throttler:timeBatch(60000, 0)
where isEligible == true
select throttleKey, count(messageID)
>= 2000 as isThrottled,
expiryTimeStamp
group by throttleKey
=>
(gateway:GlobalThrottleStreamDTO[] counts)
{
resultStream.publish(counts);
}
Analytics
Microgateway analytics architecture.
CLIENT DEVICES MICROGATEWAY ANALYTICS ENGINE
1 SEND REQUEST TO
MICROGATEWAY
2 WRITE REQUEST META-DATA TO
FILE SYSTEM
3
PERIODICALLY READ
DATA FROM FILE SYSTEM
4
UPLOAD DATA TO ANALYTICS
ENGINE FOR PROCESSING
BALLERINA BASED
PERIODIC TASK
Using Ballerina Streams to
avoid write-lock contentions
on the file system
public function filterRequest(http:Request
request, http:FilterContext context)
returns http:FilterResult {
http:FilterResult requestFilterResult;
AnalyticsRequestStream requestStream =
generateRequestEvent(request, context);
EventDTO eventDto =
generateEventFromRequest(requestStream);
eventStream.publish(eventDto);
requestFilterResult = { canProceed:
true, statusCode: 200, message:
"Analytics filter processed." };
return requestFilterResult;
}
SERVICE 1 SERVICE 2 SERVICE 3
EVENT STREAM
FILE SYSTEM
Ballerina Character I/O API for
writing data to file
io:ByteChannel channel =
io:openFile("api-usage-data.dat",
io:APPEND);
io:CharacterChannel charChannel =
new(channel, "UTF-8");
try {
match
charChannel.write(getEventData(eventDTO),0)
{
. . . .
. . . .
}
} finally {
match charChannel.close() {
. . . .
. . . .
}
}
Docker and Kubernetes
Ballerina @docker annotations
The @docker annotations help us
build docker images of the
microgateway
@docker:Expose{}
listener gateway:APIGatewayListener
apiListener = new (9095, {
filters:[authnFilter, authzFilter,
rateLimitFilter,
analyticsFilter,
extensionFilter]
});
@docker:Config {
registry:"private.docker.gateway.com",
name:"passthrough",
tag:"v1.0"
}
service passthrough on apiListener {
. . .
. . .
}
Microgateway build process to build docker images
OAS PROJECT
Generate Ballerina source
code from OAS document
Compile Ballerina project to
build docker image of
microgateway
Ballerina @kubernetes
annotations
The @kubernetes annotations help
easily deploy the microgateway to
kubernetes.
@kubernetes:Service {
sessionAffinity: "ClientIP"
}
listener gateway:APIGatewayListener
apiListener = new (9095, {
filters:[authnFilter, authzFilter,
rateLimitFilter,
analyticsFilter,
extensionFilter]
});
@kubernetes:Deployment {
name: "passthrough",
replicas: 3,
labels: { "location": "WA", "city":
"SEA" },
enableLiveness: true,
livenessPort: 9099,
singleYAML: false
}
service passthrough on apiListener {
. . .
. . .
Microgateway build process to build kubernetes deployment
artifacts
OAS PROJECT
Generate Ballerina source
code from OAS document
Compile Ballerina project to
build k8s deployment
artifacts of
microgateway
More information
https://www.infoq.com/articles/ballerina-api-gateway
Q & A
THANK YOU

Weitere ähnliche Inhalte

Was ist angesagt?

What the Heck is OAuth and Open ID Connect? - UberConf 2017
What the Heck is OAuth and Open ID Connect? - UberConf 2017What the Heck is OAuth and Open ID Connect? - UberConf 2017
What the Heck is OAuth and Open ID Connect? - UberConf 2017Matt Raible
 
Carlos García - Pentesting Active Directory [rooted2018]
Carlos García - Pentesting Active Directory [rooted2018]Carlos García - Pentesting Active Directory [rooted2018]
Carlos García - Pentesting Active Directory [rooted2018]RootedCON
 
REST Service Authetication with TLS & JWTs
REST Service Authetication with TLS & JWTsREST Service Authetication with TLS & JWTs
REST Service Authetication with TLS & JWTsJon Todd
 
Getting Started with Spring Authorization Server
Getting Started with Spring Authorization ServerGetting Started with Spring Authorization Server
Getting Started with Spring Authorization ServerVMware Tanzu
 
An Introduction to OAuth2
An Introduction to OAuth2An Introduction to OAuth2
An Introduction to OAuth2Aaron Parecki
 
2016 pycontw web api authentication
2016 pycontw web api authentication 2016 pycontw web api authentication
2016 pycontw web api authentication Micron Technology
 
Building an API Security Ecosystem
Building an API Security EcosystemBuilding an API Security Ecosystem
Building an API Security EcosystemPrabath Siriwardena
 
OAuth 2.0 – A standard is coming of age by Uwe Friedrichsen
OAuth 2.0 – A standard is coming of age by Uwe FriedrichsenOAuth 2.0 – A standard is coming of age by Uwe Friedrichsen
OAuth 2.0 – A standard is coming of age by Uwe FriedrichsenCodemotion
 
What the Heck is OAuth and OpenID Connect - DOSUG 2018
What the Heck is OAuth and OpenID Connect - DOSUG 2018What the Heck is OAuth and OpenID Connect - DOSUG 2018
What the Heck is OAuth and OpenID Connect - DOSUG 2018Matt Raible
 
iMasters Intercon 2016 - Identity within Microservices
iMasters Intercon 2016 - Identity within MicroservicesiMasters Intercon 2016 - Identity within Microservices
iMasters Intercon 2016 - Identity within MicroservicesErick Belluci Tedeschi
 
NextGenPSD2 OAuth SCA Mode Security Recommendations
NextGenPSD2 OAuth SCA Mode Security RecommendationsNextGenPSD2 OAuth SCA Mode Security Recommendations
NextGenPSD2 OAuth SCA Mode Security RecommendationsTorsten Lodderstedt
 
What the Heck is OAuth and OIDC - UberConf 2018
What the Heck is OAuth and OIDC - UberConf 2018What the Heck is OAuth and OIDC - UberConf 2018
What the Heck is OAuth and OIDC - UberConf 2018Matt Raible
 
Single-Page-Application & REST security
Single-Page-Application & REST securitySingle-Page-Application & REST security
Single-Page-Application & REST securityIgor Bossenko
 

Was ist angesagt? (19)

What the Heck is OAuth and Open ID Connect? - UberConf 2017
What the Heck is OAuth and Open ID Connect? - UberConf 2017What the Heck is OAuth and Open ID Connect? - UberConf 2017
What the Heck is OAuth and Open ID Connect? - UberConf 2017
 
Demystifying OAuth 2.0
Demystifying OAuth 2.0Demystifying OAuth 2.0
Demystifying OAuth 2.0
 
OAuth 2.0
OAuth 2.0OAuth 2.0
OAuth 2.0
 
Carlos García - Pentesting Active Directory [rooted2018]
Carlos García - Pentesting Active Directory [rooted2018]Carlos García - Pentesting Active Directory [rooted2018]
Carlos García - Pentesting Active Directory [rooted2018]
 
REST Service Authetication with TLS & JWTs
REST Service Authetication with TLS & JWTsREST Service Authetication with TLS & JWTs
REST Service Authetication with TLS & JWTs
 
Getting Started with Spring Authorization Server
Getting Started with Spring Authorization ServerGetting Started with Spring Authorization Server
Getting Started with Spring Authorization Server
 
An Introduction to OAuth2
An Introduction to OAuth2An Introduction to OAuth2
An Introduction to OAuth2
 
2016 pycontw web api authentication
2016 pycontw web api authentication 2016 pycontw web api authentication
2016 pycontw web api authentication
 
Building an API Security Ecosystem
Building an API Security EcosystemBuilding an API Security Ecosystem
Building an API Security Ecosystem
 
JWTs and JOSE in a flash
JWTs and JOSE in a flashJWTs and JOSE in a flash
JWTs and JOSE in a flash
 
FIWARE ID Management
FIWARE ID ManagementFIWARE ID Management
FIWARE ID Management
 
OAuth 2.0 – A standard is coming of age by Uwe Friedrichsen
OAuth 2.0 – A standard is coming of age by Uwe FriedrichsenOAuth 2.0 – A standard is coming of age by Uwe Friedrichsen
OAuth 2.0 – A standard is coming of age by Uwe Friedrichsen
 
What the Heck is OAuth and OpenID Connect - DOSUG 2018
What the Heck is OAuth and OpenID Connect - DOSUG 2018What the Heck is OAuth and OpenID Connect - DOSUG 2018
What the Heck is OAuth and OpenID Connect - DOSUG 2018
 
OAuth2
OAuth2OAuth2
OAuth2
 
IdM and AC
IdM and ACIdM and AC
IdM and AC
 
iMasters Intercon 2016 - Identity within Microservices
iMasters Intercon 2016 - Identity within MicroservicesiMasters Intercon 2016 - Identity within Microservices
iMasters Intercon 2016 - Identity within Microservices
 
NextGenPSD2 OAuth SCA Mode Security Recommendations
NextGenPSD2 OAuth SCA Mode Security RecommendationsNextGenPSD2 OAuth SCA Mode Security Recommendations
NextGenPSD2 OAuth SCA Mode Security Recommendations
 
What the Heck is OAuth and OIDC - UberConf 2018
What the Heck is OAuth and OIDC - UberConf 2018What the Heck is OAuth and OIDC - UberConf 2018
What the Heck is OAuth and OIDC - UberConf 2018
 
Single-Page-Application & REST security
Single-Page-Application & REST securitySingle-Page-Application & REST security
Single-Page-Application & REST security
 

Ähnlich wie Building a Microgateway in Ballerina_KubeCon 2108

Security enforcement of Java Microservices with Apiman & Keycloak
Security enforcement of Java Microservices with Apiman & KeycloakSecurity enforcement of Java Microservices with Apiman & Keycloak
Security enforcement of Java Microservices with Apiman & KeycloakCharles Moulliard
 
InterCon 2016 - Segurança de identidade digital levando em consideração uma a...
InterCon 2016 - Segurança de identidade digital levando em consideração uma a...InterCon 2016 - Segurança de identidade digital levando em consideração uma a...
InterCon 2016 - Segurança de identidade digital levando em consideração uma a...iMasters
 
Getting Started with Globus for Developers
Getting Started with Globus for DevelopersGetting Started with Globus for Developers
Getting Started with Globus for DevelopersGlobus
 
Securing your Pulsar Cluster with Vault_Chris Kellogg
Securing your Pulsar Cluster with Vault_Chris KelloggSecuring your Pulsar Cluster with Vault_Chris Kellogg
Securing your Pulsar Cluster with Vault_Chris KelloggStreamNative
 
OAuth2 on Ericsson Labs
OAuth2 on Ericsson LabsOAuth2 on Ericsson Labs
OAuth2 on Ericsson LabsEricsson Labs
 
GDG Cloud Taipei: Meetup #52 - Istio Security: API Authorization
GDG Cloud Taipei: Meetup #52 - Istio Security: API AuthorizationGDG Cloud Taipei: Meetup #52 - Istio Security: API Authorization
GDG Cloud Taipei: Meetup #52 - Istio Security: API AuthorizationKAI CHU CHUNG
 
Operationalizing Multi Cluster Istio_ Lessons Learned and Developing Ambient ...
Operationalizing Multi Cluster Istio_ Lessons Learned and Developing Ambient ...Operationalizing Multi Cluster Istio_ Lessons Learned and Developing Ambient ...
Operationalizing Multi Cluster Istio_ Lessons Learned and Developing Ambient ...MichaelOLeary82
 
How to Build an Indivo X Personal Health App
How to Build an Indivo X Personal Health AppHow to Build an Indivo X Personal Health App
How to Build an Indivo X Personal Health AppBen Adida
 
AllTheTalks.Online 2020: "Basics of OAuth 2.0 and OpenID Connect"
AllTheTalks.Online 2020: "Basics of OAuth 2.0 and OpenID Connect"AllTheTalks.Online 2020: "Basics of OAuth 2.0 and OpenID Connect"
AllTheTalks.Online 2020: "Basics of OAuth 2.0 and OpenID Connect"Andreas Falk
 
Building @Anywhere (for TXJS)
Building @Anywhere (for TXJS)Building @Anywhere (for TXJS)
Building @Anywhere (for TXJS)danwrong
 
Pentesting web applications
Pentesting web applicationsPentesting web applications
Pentesting web applicationsSatish b
 
Creating Great REST and gRPC API Experiences (in Swift)
Creating Great REST and gRPC API Experiences (in Swift)Creating Great REST and gRPC API Experiences (in Swift)
Creating Great REST and gRPC API Experiences (in Swift)Tim Burks
 
FIWARE Wednesday Webinars - How to Secure IoT Devices
FIWARE Wednesday Webinars - How to Secure IoT DevicesFIWARE Wednesday Webinars - How to Secure IoT Devices
FIWARE Wednesday Webinars - How to Secure IoT DevicesFIWARE
 
UserCentric Identity based Service Invocation
UserCentric Identity based Service InvocationUserCentric Identity based Service Invocation
UserCentric Identity based Service Invocationguestd5dde6
 
Build resource server &amp; client for OCF Cloud (2018.8.30)
Build resource server &amp; client for OCF Cloud (2018.8.30)Build resource server &amp; client for OCF Cloud (2018.8.30)
Build resource server &amp; client for OCF Cloud (2018.8.30)남균 김
 
Sécurisation de vos applications web à l’aide du composant Security de Symfony
Sécurisation de vos applications web  à l’aide du composant Security de SymfonySécurisation de vos applications web  à l’aide du composant Security de Symfony
Sécurisation de vos applications web à l’aide du composant Security de SymfonyVladyslav Riabchenko
 
Keycloak for Science Gateways - SGCI Technology Sampler Webinar
Keycloak for Science Gateways - SGCI Technology Sampler WebinarKeycloak for Science Gateways - SGCI Technology Sampler Webinar
Keycloak for Science Gateways - SGCI Technology Sampler Webinarmarcuschristie
 
Api security-eic-prabath
Api security-eic-prabathApi security-eic-prabath
Api security-eic-prabathWSO2
 
What the Heck is OAuth and OpenID Connect? Connect.Tech 2017
What the Heck is OAuth and OpenID Connect? Connect.Tech 2017What the Heck is OAuth and OpenID Connect? Connect.Tech 2017
What the Heck is OAuth and OpenID Connect? Connect.Tech 2017Matt Raible
 

Ähnlich wie Building a Microgateway in Ballerina_KubeCon 2108 (20)

Security enforcement of Java Microservices with Apiman & Keycloak
Security enforcement of Java Microservices with Apiman & KeycloakSecurity enforcement of Java Microservices with Apiman & Keycloak
Security enforcement of Java Microservices with Apiman & Keycloak
 
InterCon 2016 - Segurança de identidade digital levando em consideração uma a...
InterCon 2016 - Segurança de identidade digital levando em consideração uma a...InterCon 2016 - Segurança de identidade digital levando em consideração uma a...
InterCon 2016 - Segurança de identidade digital levando em consideração uma a...
 
Getting Started with Globus for Developers
Getting Started with Globus for DevelopersGetting Started with Globus for Developers
Getting Started with Globus for Developers
 
Securing your Pulsar Cluster with Vault_Chris Kellogg
Securing your Pulsar Cluster with Vault_Chris KelloggSecuring your Pulsar Cluster with Vault_Chris Kellogg
Securing your Pulsar Cluster with Vault_Chris Kellogg
 
OAuth2 on Ericsson Labs
OAuth2 on Ericsson LabsOAuth2 on Ericsson Labs
OAuth2 on Ericsson Labs
 
GDG Cloud Taipei: Meetup #52 - Istio Security: API Authorization
GDG Cloud Taipei: Meetup #52 - Istio Security: API AuthorizationGDG Cloud Taipei: Meetup #52 - Istio Security: API Authorization
GDG Cloud Taipei: Meetup #52 - Istio Security: API Authorization
 
Operationalizing Multi Cluster Istio_ Lessons Learned and Developing Ambient ...
Operationalizing Multi Cluster Istio_ Lessons Learned and Developing Ambient ...Operationalizing Multi Cluster Istio_ Lessons Learned and Developing Ambient ...
Operationalizing Multi Cluster Istio_ Lessons Learned and Developing Ambient ...
 
How to Build an Indivo X Personal Health App
How to Build an Indivo X Personal Health AppHow to Build an Indivo X Personal Health App
How to Build an Indivo X Personal Health App
 
AllTheTalks.Online 2020: "Basics of OAuth 2.0 and OpenID Connect"
AllTheTalks.Online 2020: "Basics of OAuth 2.0 and OpenID Connect"AllTheTalks.Online 2020: "Basics of OAuth 2.0 and OpenID Connect"
AllTheTalks.Online 2020: "Basics of OAuth 2.0 and OpenID Connect"
 
Some OAuth love
Some OAuth loveSome OAuth love
Some OAuth love
 
Building @Anywhere (for TXJS)
Building @Anywhere (for TXJS)Building @Anywhere (for TXJS)
Building @Anywhere (for TXJS)
 
Pentesting web applications
Pentesting web applicationsPentesting web applications
Pentesting web applications
 
Creating Great REST and gRPC API Experiences (in Swift)
Creating Great REST and gRPC API Experiences (in Swift)Creating Great REST and gRPC API Experiences (in Swift)
Creating Great REST and gRPC API Experiences (in Swift)
 
FIWARE Wednesday Webinars - How to Secure IoT Devices
FIWARE Wednesday Webinars - How to Secure IoT DevicesFIWARE Wednesday Webinars - How to Secure IoT Devices
FIWARE Wednesday Webinars - How to Secure IoT Devices
 
UserCentric Identity based Service Invocation
UserCentric Identity based Service InvocationUserCentric Identity based Service Invocation
UserCentric Identity based Service Invocation
 
Build resource server &amp; client for OCF Cloud (2018.8.30)
Build resource server &amp; client for OCF Cloud (2018.8.30)Build resource server &amp; client for OCF Cloud (2018.8.30)
Build resource server &amp; client for OCF Cloud (2018.8.30)
 
Sécurisation de vos applications web à l’aide du composant Security de Symfony
Sécurisation de vos applications web  à l’aide du composant Security de SymfonySécurisation de vos applications web  à l’aide du composant Security de Symfony
Sécurisation de vos applications web à l’aide du composant Security de Symfony
 
Keycloak for Science Gateways - SGCI Technology Sampler Webinar
Keycloak for Science Gateways - SGCI Technology Sampler WebinarKeycloak for Science Gateways - SGCI Technology Sampler Webinar
Keycloak for Science Gateways - SGCI Technology Sampler Webinar
 
Api security-eic-prabath
Api security-eic-prabathApi security-eic-prabath
Api security-eic-prabath
 
What the Heck is OAuth and OpenID Connect? Connect.Tech 2017
What the Heck is OAuth and OpenID Connect? Connect.Tech 2017What the Heck is OAuth and OpenID Connect? Connect.Tech 2017
What the Heck is OAuth and OpenID Connect? Connect.Tech 2017
 

Mehr von Ballerina

Role of Integration and Service Mesh in Cloud Native Architecture KubeCon 2108
Role of Integration and Service Mesh in Cloud Native Architecture KubeCon 2108Role of Integration and Service Mesh in Cloud Native Architecture KubeCon 2108
Role of Integration and Service Mesh in Cloud Native Architecture KubeCon 2108Ballerina
 
Ballerina in the Real World: Motorola_KubeCon 2018
Ballerina in the Real World: Motorola_KubeCon 2018Ballerina in the Real World: Motorola_KubeCon 2018
Ballerina in the Real World: Motorola_KubeCon 2018Ballerina
 
Ballerina integration with Azure cloud services_KubeCon 2018
Ballerina integration with Azure cloud services_KubeCon 2018Ballerina integration with Azure cloud services_KubeCon 2018
Ballerina integration with Azure cloud services_KubeCon 2018Ballerina
 
Ballerina is not Java_KubeCon 2108
Ballerina is not Java_KubeCon 2108Ballerina is not Java_KubeCon 2108
Ballerina is not Java_KubeCon 2108Ballerina
 
Microservice Integration from Dev to Production_KubeCon2018
Microservice Integration from Dev to Production_KubeCon2018Microservice Integration from Dev to Production_KubeCon2018
Microservice Integration from Dev to Production_KubeCon2018Ballerina
 
Ballerina ecosystem
Ballerina ecosystemBallerina ecosystem
Ballerina ecosystemBallerina
 
Orchestrating microservices with docker and kubernetes
Orchestrating microservices with docker and kubernetesOrchestrating microservices with docker and kubernetes
Orchestrating microservices with docker and kubernetesBallerina
 
Data integration
Data integrationData integration
Data integrationBallerina
 
Service resiliency in microservices
Service resiliency in microservicesService resiliency in microservices
Service resiliency in microservicesBallerina
 
Microservices integration
Microservices integration   Microservices integration
Microservices integration Ballerina
 
Writing microservices
Writing microservicesWriting microservices
Writing microservicesBallerina
 
Ballerina philosophy
Ballerina philosophy Ballerina philosophy
Ballerina philosophy Ballerina
 
Ballerina: Cloud Native Programming Language
Ballerina: Cloud Native Programming Language Ballerina: Cloud Native Programming Language
Ballerina: Cloud Native Programming Language Ballerina
 
Writing services in Ballerina_Ballerina Day CMB 2018
Writing services in Ballerina_Ballerina Day CMB 2018Writing services in Ballerina_Ballerina Day CMB 2018
Writing services in Ballerina_Ballerina Day CMB 2018Ballerina
 
Resiliency & Security_Ballerina Day CMB 2018
Resiliency & Security_Ballerina Day CMB 2018  Resiliency & Security_Ballerina Day CMB 2018
Resiliency & Security_Ballerina Day CMB 2018 Ballerina
 
Stream Processing with Ballerina
Stream Processing with BallerinaStream Processing with Ballerina
Stream Processing with BallerinaBallerina
 
Secure by Design Microservices & Integrations
Secure by Design Microservices & IntegrationsSecure by Design Microservices & Integrations
Secure by Design Microservices & IntegrationsBallerina
 
Observability with Ballerina
Observability with BallerinaObservability with Ballerina
Observability with BallerinaBallerina
 
Serverless Ballerina
Serverless BallerinaServerless Ballerina
Serverless BallerinaBallerina
 
Test Driven Development for Microservices
Test Driven Development for MicroservicesTest Driven Development for Microservices
Test Driven Development for MicroservicesBallerina
 

Mehr von Ballerina (20)

Role of Integration and Service Mesh in Cloud Native Architecture KubeCon 2108
Role of Integration and Service Mesh in Cloud Native Architecture KubeCon 2108Role of Integration and Service Mesh in Cloud Native Architecture KubeCon 2108
Role of Integration and Service Mesh in Cloud Native Architecture KubeCon 2108
 
Ballerina in the Real World: Motorola_KubeCon 2018
Ballerina in the Real World: Motorola_KubeCon 2018Ballerina in the Real World: Motorola_KubeCon 2018
Ballerina in the Real World: Motorola_KubeCon 2018
 
Ballerina integration with Azure cloud services_KubeCon 2018
Ballerina integration with Azure cloud services_KubeCon 2018Ballerina integration with Azure cloud services_KubeCon 2018
Ballerina integration with Azure cloud services_KubeCon 2018
 
Ballerina is not Java_KubeCon 2108
Ballerina is not Java_KubeCon 2108Ballerina is not Java_KubeCon 2108
Ballerina is not Java_KubeCon 2108
 
Microservice Integration from Dev to Production_KubeCon2018
Microservice Integration from Dev to Production_KubeCon2018Microservice Integration from Dev to Production_KubeCon2018
Microservice Integration from Dev to Production_KubeCon2018
 
Ballerina ecosystem
Ballerina ecosystemBallerina ecosystem
Ballerina ecosystem
 
Orchestrating microservices with docker and kubernetes
Orchestrating microservices with docker and kubernetesOrchestrating microservices with docker and kubernetes
Orchestrating microservices with docker and kubernetes
 
Data integration
Data integrationData integration
Data integration
 
Service resiliency in microservices
Service resiliency in microservicesService resiliency in microservices
Service resiliency in microservices
 
Microservices integration
Microservices integration   Microservices integration
Microservices integration
 
Writing microservices
Writing microservicesWriting microservices
Writing microservices
 
Ballerina philosophy
Ballerina philosophy Ballerina philosophy
Ballerina philosophy
 
Ballerina: Cloud Native Programming Language
Ballerina: Cloud Native Programming Language Ballerina: Cloud Native Programming Language
Ballerina: Cloud Native Programming Language
 
Writing services in Ballerina_Ballerina Day CMB 2018
Writing services in Ballerina_Ballerina Day CMB 2018Writing services in Ballerina_Ballerina Day CMB 2018
Writing services in Ballerina_Ballerina Day CMB 2018
 
Resiliency & Security_Ballerina Day CMB 2018
Resiliency & Security_Ballerina Day CMB 2018  Resiliency & Security_Ballerina Day CMB 2018
Resiliency & Security_Ballerina Day CMB 2018
 
Stream Processing with Ballerina
Stream Processing with BallerinaStream Processing with Ballerina
Stream Processing with Ballerina
 
Secure by Design Microservices & Integrations
Secure by Design Microservices & IntegrationsSecure by Design Microservices & Integrations
Secure by Design Microservices & Integrations
 
Observability with Ballerina
Observability with BallerinaObservability with Ballerina
Observability with Ballerina
 
Serverless Ballerina
Serverless BallerinaServerless Ballerina
Serverless Ballerina
 
Test Driven Development for Microservices
Test Driven Development for MicroservicesTest Driven Development for Microservices
Test Driven Development for Microservices
 

Kürzlich hochgeladen

Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyFrank van der Linden
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 

Kürzlich hochgeladen (20)

Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The Ugly
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 

Building a Microgateway in Ballerina_KubeCon 2108

  • 1. Building a Microgateway in Ballerina Nuwan Dias Director - API Architecture, WSO2 @nuwandias
  • 3. API Gateway CLIENT DEVICES API GATEWAY MICROSERVICE
  • 4. API Gateway - What does it do? ○ Request forwarding ○ URL rewrite ○ Load-balancing ○ Failover ○ Circuit breaking ○ Inbound and outbound security ○ Authentication and authorization ○ OAuth2, OIDC, API Keys, Basic auth, Digital signatures, MTLS, etc. ○ Rate limiting ○ Analytics
  • 6. Ballerina Service @http:ServiceConfig { basePath:"/pizzashack/1.0.0" } service passthrough on new http:Listener (9090) { @http:ResourceConfig { methods:["GET"], path:"/menu" } resource function getMenu (http:Caller caller, http:Request req) { //contains request forwarding logic to target. } }
  • 7. OAS (Swagger) document becomes the source of the service definition OAS DOCUMENT
  • 8. Generating the Ballerina service OAS DOCUMENT Auto generate the Ballerina source code from OAS.
  • 9. Connecting to the target endpoint Target endpoint
  • 10. Forwarding request to the target http:Client targetEndpoint = new ("https://api.pizzastore.com/pizzashack/v1"); @http:ServiceConfig { basePath: "/pizzashack/1.0.0" } service passthrough on new http:Listener (9090) { @http:ResourceConfig { methods:["GET"], path:"/menu" } resource function getMenu (http:Caller caller, http:Request req) { . . . . . . . } }
  • 11. Forwarding request to the target resource function getMenu (http:Caller caller, http:Request req) { //Forward the client request to the /menu resource of the Target Endpoint. var clientResponse = targetEndpoint -> forward(“/menu”, req); //Check if the response from the target Endpoint was a success or not. if clientResponse is http:Response{ var result = caller->respond(res); if result is error { log:printError("Error sending response"); } } else { http:Response res = new; res.statusCode = 500; res.setPayload(err.message); var result = caller->respond(res); if result is error { log:printError("Error sending response"); } }
  • 14. Listeners and Filters service passthrough on new http:Listener (9090) { import wso2/gateway; AuthnFilter authnFilter; OAuthzFilter authzFilter; RateLimitFilter rateLimitFilter; AnalyticsFilter analyticsFilter; ExtensionFilter extensionFilter; listener gateway:APIGatewayListener apiListener = new (9095, { filters:[authnFilter, authzFilter, rateLimitFilter, analyticsFilter, extensionFilter] }); service passthrough on apiListener { A listener is what a service binds itself to. A listener may have one or more filters to filter requests being received on the port of the listener.
  • 16. Authentication listener gateway:APIGatewayListener apiListener = new (9095, { filters:[authnFilter, authzFilter]}, { authProviders:[jwtAuthProvider, basic] }); http:AuthProvider jwtAuthProvider = { scheme:"jwt", issuer:"ballerina", audience: "ballerina.io", certificateAlias: "ballerina", trustStore: { path: "${ballerina.home}/bre/security/ballerinaTr uststore.p12", password: "ballerina" } }; The microgateway supports different authentication mechanisms such as OAuth2, basic authentication, etc. Which mechanisms to apply against a request is decided by the declared authentication providers in the listener.
  • 17. Enabling/Disabling security by service //This service is accessible at // /pizzashack/1.0.0 on port 9095 @http:ServiceConfig { basePath: "/pizzashack/1.0.0", authConfig: { authentication: { enabled: true } } } service passthrough on apiListener { . . . . . . . . . . } Each service bound to the listener can chose to enable or disable security by itself.
  • 18. Authorization Authorization is enabled per each operation of the service using ‘scopes’. Scopes are used as a means of abstracting the authorization mechanism. @http:ResourceConfig { methods:["PUT"], path:"/menu", authConfig: { scopes: ["edit_menu"] } } resource function editMenu (http:Caller caller, http:Request req)
  • 19. Microgateway in-bound security architecture. CLIENT DEVICES MICROGATEWAY MICROSERVICE SECURITY TOKEN SERVICE 1 OBTAIN TOKEN FROM STS 2 SEND TOKEN TO MICROGATEWAY WITH REQUEST 3 OPTIONAL VALIDATION REQUEST FROM MICROGATEWAY TO STS 4 FORWARD REQUEST TO TARGET
  • 21. Ballerina Streams The RateLimitFilter on the listener adds metadata of every successful request into a data-stream. public stream<RequestStreamDTO> requestStream; public function publishNonThrottleEvent(RequestStreamDTO request) { requestStream.publish(request); }
  • 22. Rate limiting Policies Rate limiting policies on the microgateway are modelled as stream processors where it executes logic on the data received via the stream. forever { from gateway:requestStream select messageID, (tier == "Silver") as isEligible, subscriptionKey as throttleKey => (gateway:EligibilityStreamDTO[] counts) { eligibilityStream.publish(counts); } from eligibilityStream throttler:timeBatch(60000, 0) where isEligible == true select throttleKey, count(messageID) >= 2000 as isThrottled, expiryTimeStamp group by throttleKey => (gateway:GlobalThrottleStreamDTO[] counts) { resultStream.publish(counts); }
  • 24. Microgateway analytics architecture. CLIENT DEVICES MICROGATEWAY ANALYTICS ENGINE 1 SEND REQUEST TO MICROGATEWAY 2 WRITE REQUEST META-DATA TO FILE SYSTEM 3 PERIODICALLY READ DATA FROM FILE SYSTEM 4 UPLOAD DATA TO ANALYTICS ENGINE FOR PROCESSING BALLERINA BASED PERIODIC TASK
  • 25. Using Ballerina Streams to avoid write-lock contentions on the file system public function filterRequest(http:Request request, http:FilterContext context) returns http:FilterResult { http:FilterResult requestFilterResult; AnalyticsRequestStream requestStream = generateRequestEvent(request, context); EventDTO eventDto = generateEventFromRequest(requestStream); eventStream.publish(eventDto); requestFilterResult = { canProceed: true, statusCode: 200, message: "Analytics filter processed." }; return requestFilterResult; } SERVICE 1 SERVICE 2 SERVICE 3 EVENT STREAM FILE SYSTEM
  • 26. Ballerina Character I/O API for writing data to file io:ByteChannel channel = io:openFile("api-usage-data.dat", io:APPEND); io:CharacterChannel charChannel = new(channel, "UTF-8"); try { match charChannel.write(getEventData(eventDTO),0) { . . . . . . . . } } finally { match charChannel.close() { . . . . . . . . } }
  • 28. Ballerina @docker annotations The @docker annotations help us build docker images of the microgateway @docker:Expose{} listener gateway:APIGatewayListener apiListener = new (9095, { filters:[authnFilter, authzFilter, rateLimitFilter, analyticsFilter, extensionFilter] }); @docker:Config { registry:"private.docker.gateway.com", name:"passthrough", tag:"v1.0" } service passthrough on apiListener { . . . . . . }
  • 29. Microgateway build process to build docker images OAS PROJECT Generate Ballerina source code from OAS document Compile Ballerina project to build docker image of microgateway
  • 30. Ballerina @kubernetes annotations The @kubernetes annotations help easily deploy the microgateway to kubernetes. @kubernetes:Service { sessionAffinity: "ClientIP" } listener gateway:APIGatewayListener apiListener = new (9095, { filters:[authnFilter, authzFilter, rateLimitFilter, analyticsFilter, extensionFilter] }); @kubernetes:Deployment { name: "passthrough", replicas: 3, labels: { "location": "WA", "city": "SEA" }, enableLiveness: true, livenessPort: 9099, singleYAML: false } service passthrough on apiListener { . . . . . .
  • 31. Microgateway build process to build kubernetes deployment artifacts OAS PROJECT Generate Ballerina source code from OAS document Compile Ballerina project to build k8s deployment artifacts of microgateway
  • 33. Q & A