How to build an API Gateway in ASP.NET Core using Ocelot (Build API Gateway in a few minutes)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello everyone and welcome to dot net core central in today's video i am going to talk about api gateway and specifically implementing api gateway with oc lot now before we go to oc lord let's discuss what is api gateway in today's world we usually create multiple microservices or single responsibility services for a particular product and for each of these services we will have different different endpoint accessing these services from an external world it doesn't make sense exposing multiple url we should have a single entry point to all our services and based on different path we should be doing the routing now this can also be done by traditional load balancer but the feature of traditional load balancer is very limited to what it can do whereas api gateway is way beyond just the routing now in this diagram i'm showing three services for an attendance management system one is a user service which is used for managing users one is attendance service which is used for attendance and one is report service which is used for reporting api gateway can be the entry point for any external calls and then based on the route it will be routing these two different different endpoints now if i go into the features of a standard api gateway the main top level features are routing request aggregation authentication authorization rate limiting caching and load balancing but most of the api gateway out there in market has way many features than this even aussie alert has many more features than what i have listed here you can check it out in their website but these are the most common and heavily used features in my opinion at least in my experience these are the things which are very commonly used now what is oc lord ocelot is asp.net core api gateway it supports dotnet core 3.1 it's a nuget package which can be added to any asp.net core application to make it a api gateway ocelot api gateway supports all the features of standard api gateway but for today's video i'm going to focus on routing which is the very basic and the must-have feature then authentication which also in my opinion is very important third is response caching and fourth is rate limiting i have a application running on port 5001 and it is exposing an api for weather forecast this is just a standard.net core application the out-of-box weather forecast endpoint so if i run it it's going to give weather forecast every time i make a call to this endpoint so for the goal of the api gateway is going to route to this particular endpoint so to do that first i'm going to create asp.net core web application and i'm going to name it as osilord.demo and i'm going to create a empty asp.net code 3.1 project now once the project is created i'm going to go to the program file now here what i'm going to do is i'm just going to add a couple of things so first of all i'm going to add logging and i'm going to add console log this will be useful for printing out all the logs now next thing i'm going to do is i'm going to add the nuget packages for ocelot so there is a single nuget package we need for the basic ocelot implementation and i'm going to install that as you can see here it supports dotnet core app version 3.1 only once the nuget package is installed i'm going to go into startup and then here i can do services dot add oc lot i can either pass configuration object here or i can call it empty the next thing i'm going to do is i'm going to do here app dot use ocelot dot wait so that's all i have to do to configure oc lord these are the only two lines that we need now next thing and which is the most important thing is to add the oc lord dot json so i'm going to add a new item and i'm going to add a json file and i'm going to name it as ocelot and let me just copy paste and create a dev version of this file and let me go and change a couple of things here let me in the debug let's provide the environment as dev because that's the name of the file the next thing i'm going to do is because 5000 port is already taken by the other one i'm going to name it as five thousand five zero two one and five zero two zero so for the oscillator configuration it's a json configuration which has couple of things first thing is the routes which is the most important part which specifies where to route to and second is a global configuration so i'm just going to copy paste the configuration so routes as you can see it's an array and we can have multiple routes inside it of course because we might be calling multiple services from here in global configuration we have a base url this is a very important part the base url is the url where this particular oc load api gateway would be running this is important for dealing with headers for ocelot so we have to provide it here the next thing is the routes so for routes downstream template path is the downstream application which we are going to call so in our case the downstream application is just weather forecast so we can say slash weather forecast and then the downstream scheme is either http or https in our case it is https and then downstream host is localhost and the downstream port is going to be the port of this application which is 5001 and then the upstream template is what is the endpoint that we will be calling into the gateway so here i'm going to give api slash weather and the http method is get it can be post put based on whatever we are doing but for this example it's going to be get the other thing is if weather takes a parameter like id you can configure it same way here if the downstream is expecting an id the upstream can also pass it along for our example we don't need it so i'm just going to delete it so now we configured everything we configured the route configured it as https and the base url now after the configuration is done the next thing to do is to add the configuration into the system so for that we are going to do web builder dot configure app configuration and for this one we get the config delegate so i can say config and here we can say config dot add json file and for the json file we are going to give the ocelot dot dot json and we need the environment here so for environment we can get the equal to and the environment variable name is sp net core underscore environment it's a standard name which is used so we're going to get it and that's about it and here i'm going to pass the environment so now for dev because we are running in dev mode it's going to pick up the ocelot.tab.json let me make this aesthetic now let me run the application and once i run the application i can now go to api slash weather and you can see the weather from the other endpoint is showing up here and if we go back here in the logs you can see that we made a request to slash weather forecast this is the 200 status code is coming back from localhost 5001 weather forecast so we can see that made a call to this one and then redirected the response to this endpoint if you call it again we'll get it back so that's the very basic feature of api gateway you can see how easy it is to use ocelot as an api gateway it is super simple now let's get to the authentication piece now why authentication is very important when you have multiple api just like in this example here when you have multiple services with apis the services can be consumed by external as well as internal processes now for internal processes which are running as cron job or some background worker it's always overhead to authenticate for each service instead these internal services can call directly these services without any authentication whereas external services coming in the authentication responsibility can be given to api gateway so the services really does not have to worry about how to authenticate authorization is a different case in case of authorization the services need to know the role and based on that they have to do though the api gateway can figure out the role and pass it to the services as header and the services can react based on that i'm not going to go into detail for that for this demo i am going to implement authentication in the api gateway so to do that let's say we are going to use jwt now i have a video on how to create a jwt authentication server which will return a jwt token and i have that server running here on port 5030 and this is the postman test for it so i can call this to create a jwd token you can see here what we need to do is in the api gateway we need to ensure that the call coming has authentication token it's a jwd token and it should be able to validate the token and let in so for that what we are going to do is we are going to add the nuget package for jwt bearer so we're going to install the microsoft.sp netcore authentication.jwt better and once this is installed we can go back to startup and in the services here we can add the authentication so we can see services dot add authentication and for the authentication we have an action with configuration options so we can use that and we can say option dot default authentication scheme is equal to jwt bearer defaults dot authentication scheme and option dot default challenge scheme is also jwt bearer defaults dot authentication scheme so we do that and then what we are going to do is we are going to add jwt bearer and for this one also we have an action jwt bearer options so we are going to use it and we're going to say options dot require https metadata we're just going to set it to false again i have gone deep into what each of these parameters are in my video i'm going to provide the link above you can go and check it out then options dot safe token is equal to true and then finally option dot token validation parameters equal to new of token validation parameters i can just add this namespace and here we're going to say issue our signing key that's very important and for the signing key we are going to use new symmetric security key this class takes a byte area of key so we're going to pass it and for that i'm going to copy paste the text which we used as a secret so you can say and then i'll say key is equal to encoding dot ski dot get bytes of the secret and this is the key that i'm going to pass here then i'm going to say validate issuer signing key and i'm going to set it to true because we want to validate that and then for validate issuer and validate audience i'm just going to say false that's it so after i add the jwt bearer i have to add the authentication so i can do app dot use authentication and then after that i have to go to the ocelot configuration and here i have to set the authentication configuration and for that i just have to add the authentication option at the route level so i'm going to add the authentication option and authentication provider key is what is the key which is the authentication scheme which is better so i just reset that and allow scopes is do we have anything that we want to allow or disallow for here i'm just going to allow all the authentication scope so once i do that if i run and if i go to api slash weather i get a 401 error you can see here it is written in 401 http and i can see that the api weather is unauthenticated now what i can do i can go here and i can copy paste this url and in the headers i can add the authorization header and here i can pass the bearer token and i already got the token which is not expired yet so i should be able to use this token if not i'll regenerate again and i can run and if i run you can see here i'm getting the weather response back i'm getting the 200 and the weather response so as you can see this is extremely powerful feature of api gateway to be able to authenticate at the api gateway level and not at the individual service level in that case the services can be completely private and api gateway can be the external facing service and it can handle authentication routing rate limiting and response caching so now next thing i want to show is how to do rate limiting so for that what we can do is rate limiting is extremely simple there is no change in code or anything we just update the rate limit here so for that we have to add a rate limit option configuration i'm just going to copy paste it so here the client white list is if we want to white list some endpoints enable rate limiting is true of course period is what is the period so i provided five seconds it is in terms of s for second m for minute h4 hour period time span is one after that how many seconds we are going to wait till we allow the next one and limit is how many requests so we are allowing only one request for every five seconds so now if i run this and i go back to my postman and if i request it a couple of times see if i request it too fast i get the 429 too many requests maximum remate and maximum admittance is one power five seconds as you can see it's working as expected it was very trivial it's just adding a configuration node and that's about it the next and final thing i want to demo is response caching for response caching we need a different nuget package and i'm going to add that for that what we need is ocelot dot cash dot cash manager and once we install this nuget package after that all we have to do is we have to go to the services dot add ocelot and here we can do add cache manager and cache manager has settings sections and to settings what we are going to say is we are going to do with dictionary handle that's something we need to pass and then in the configuration here we just have to add a configuration for enabling caching and for how many seconds we want to keep the cache so here i'm going to again copy paste the file cache option and i'm going to keep it as 30 seconds so that we can see that the call is not going out for 30 seconds we can see it in the console and after 30 seconds it'll go out till the time it'll just cache the response and of course this is caching the response in memory so now if i make a call first time it goes out it gets the response you can see it's getting 200 okay and then if i call it's all coming from memory so you can see that it is all coming from memory it did not make any other call so that's all i wanted to cover today i think api gateway is a very important component that all of us would need at some point in time when we are building micro services and you can go ahead and use api gateway light apg or other options but those are really expensive in my opinion ocelot it really really easy to set it up and you might need like two or three containers to support most of your use cases unless you have a very heavy load so that's all i wanted to cover today if you like this video please give me a thumbs up if you are new to my channel and if you think you are getting value out of my channel please subscribe to my channel thanks so much for watching this video
Info
Channel: DotNet Core Central
Views: 58,988
Rating: undefined out of 5
Keywords: ocelot, api gateway, ocelot asp.net core, ocelot api gateway asp.net core, api gateway asp.net core, ocelot api gateway, ocelot .net core, api gateway .net core, ocelot api gateway .net core, asp.net core api gateway, .net core api gateway
Id: hlUGZ6Hmv6s
Channel Id: undefined
Length: 18min 25sec (1105 seconds)
Published: Sun Aug 23 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.