Ocelot API Gateway JWT Authentication Tutorial

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
Hi. Welcome to CodingDroplets. In  this video we are going to see how to implement jwt authentication in ocelot api  gateway. Also I am showing the rate limiting functionality of api gateway in the same video.  We can implement the authentication mechanism either in ocelot api gateway or in the  APIs behind api gateway. Let me know which one you prefer to implement in the comments  section. Also just explain why you prefer that. It will help others as well. Anyway in this video  I'll be showing you both. So let's get started. I've created a new solution and added our previous  micro services and api gateway into it. In the micro services solution folder, you can see the  customer web api, order web api and product web api which we have created in our previous videos. And in the api gateway folder, we have the ocelot api gateway project. So now let's add a new project  to the solution in which we are going to implement the jwt authentication methods. I'm searching for  class library project template and selecting it. Let the project name be jwt authentication manager. Framework is the same as we used before. Let me create the project. We can  remove the auto created class. Now we can install the libraries needed for jwt  authentication from nuget package manager. Let's navigate to the browse tab. The first library  we need is microsoft.identitymodel.tokens. Let me install it. The second library is  system.identitymodel.tokens.jwt. Installing that as well. Now the final library is  microsoft.aspnetcore.authentication.jwtbearer. Next I am creating a new class  with the name jwt token handler. First I am declaring a string constant for jwt  security key. You should provide a very strong security key. Next I am declaring an integer  constant for jwt token validity in minutes. I need the token to be valid only for 20 minutes . You can provide whatever duration you need. Now I am creating a constructor for this  jwt token handler class. Before providing the constructor method, let's create a model  class for user accounts in the models folder. In user account model class, the first property  we need is username. Next we need password. Also we can include role. So that I can show you role based  authorization. Let me remove the unnecessary usings. For showing the demo, I am hard coding some user  accounts. But you don't need to do this. You can directly fetch the user data from your database. In  the constructor I am adding two hard-coded users. First one is an admin user with the password admin  123 and the role is administrator. Next is user 01 with user 01 password and user role. Now let's  add the model class for authentication request. So in the authentication request, we'll  just receive the username and password. I'm also creating one more model  class for authentication response. If the user authentication is successful, we'll  respond back with the authenticated user name. Then the jwt token and the jwt token expiry in seconds.  Now in jwt token handler class, I am creating a new method for generating the jwt token. This method  accepts authentication request as parameter and return authentication response. First let's check  whether the username or password is null or empty. If yes, we'll return a null value. Next we can  validate the username and password. So here you can validate from the database. But I'll just validate  it from the hard-coded user accounts. If there is no user account with the provided username and  password, we'll return a null value again. Now let's create jwt token expiry datetime object by  just adding 20 minutes to the current date time. Next we can create a claims identity object  with multiple claims in it. The first claim is for user name the second one for user role. Next I am creating a signing credentials object. You can see the security algorithm which I've used. Then creating security token descriptor object in which we can provide the claims identity token, expiry date time and the signing credentials. After that we can create the jwt security  token handler object for creating the token. I am creating the security token using the create  token method of the jwt security token handler. Finally we can convert the token to a string value using the WriteToken method of the jwt security  token handler. As the jwt token is ready now, we can return the authentication response object  from this method. We can provide the username from user account object. Then I'm calculating the  total seconds for the jwt token expiry. Finally jwt token is the token which we created now. So that's it needed in jwt token handler class. Next I'm creating an extension class for  jwt authentication dependency injection. Let's name it as custom jwt auth extension. I am making this a public static class. Now inside it, I am creating a public static method  named add custom jwt authentication which accepts iservice collection as a parameter. For iservice  collection, we need to install a library from Nuget package manager. Let me search for microsoft.extensions.dependencyinjection.abstractions. I'm installing it. Now we can add  the dependency injection methods for jwt authentication. Services.AddAuthentication and let's provide the value for default authenticate scheme. It is jwt bearer  defaults dot authenticate scheme. Then default challenge scheme is also jwt bearer default  dot authenticate scheme. Next adding jwt bearer and providing false for require https  metadata. Then true for save token. Now let's assign the token validation parameters. Validate issuer signing key should be true. Then validate issuer let it be false. Then  validate audience also false. Issuer signing key is new symmetric security key of the bytes of security key in jwt token handler class. That's it needed to be done while  adding the dependency injection. Now let's create a new web api service for  user account authentication. So i'm searching for web api project template and selecting it. Let the project name be authentication web api. clicking on next button. unchecking the configure  for https checkbox and enable open api support checkbox. let's create the project now. let me  remove the weather forecast api controller and the model class. we don't need them. now let's create  a new api controller. let the name be account controller. we need to access the jwt  authentication manager class library project from this api project. so let's  add the project reference. now i'm creating a private read-only  object of jwt token handler which is in our jwt authentication manager project. then let's  create the constructor for accountcontroller class and assign the value of the object. in order the  constructor to receive the object as a parameter we need to inject jwt token handler as a  dependency. i am adding it as a singleton service. now coming back to account controller. let's create  an http post method to authenticate the user. this method will accept the authentication request as a  parameter and returns the authentication response. now here i'm just calling the generate jwt token  method which we have created in jwt token handler. next we must check whether the authentication  response is not null as we are returning null values if the user account does not exist. so if it is  null we will return unauthenticated response. otherwise we can return the authentication  response object what we received from generate jwt token method. now let's add docker orchestrator  support for the authentication web api. choosing docker compose as the docker orchestrator  and linux as the docker operating system. the docker file got created i'm just opening  it. also let's open the docker compose yaml file here you can see the authentication web api  container details. i'm just assigning a container name let it be authentication-api. then  adding backend network inside the network section. now let's add the authentication web  api details in ocelot.json file. so i am opening it from ocelot api gateway  project. now under routes section, let's add it the up stream path template is slash  api slash account. in upstream http method we only need POST method. downstream scheme is  http. let me add downstream host and ports as well. then downstream path template is again  slash api slash account. now let's test the authentication api by  running the docker compose project. in the containers window you can see that  the authentication api container is running. let's test the api in postman. in the left side  pane named my workspace, is already showing the other microservice APIs. let me add a new  folder and name it as authentication web api. now let's add a new request inside  that folder. the method is http post. let me provide the url for authentication api. now  i am providing the body content in json format. username is admin. then the password is admin 123. we got 200 okay response and you can  see the response content in which we have the username, jwt token and the expires in  values. let's also test with user01 credentials and we got the response. now let me  provide some invalid username and password. you can see the status code as showing  401 unauthenticated now. so the api is working fine. let me save  it and name it as authenticate. we can use this saved api request  after implementing in other services. now we are going to see how we can implement  the authentication from microservices. let's implement the  authentication in customer web api. i am adding the project reference in customer  web api project. we can see the reference inside the dependencies section. now let's add the  dependency injection in the program.cs class. builder.services. here we can call the  custom extension method which we have created. as we have created the extension method,  we can simply call the method to add the dependency injection. also please make sure  you have added the app.useauthentication and app.useauthorization methods in the program.cs  class. now inside the customer controller, i am providing the authorized attribute for  getcustomers method. so that means the user should be authenticated to call this method. next  i am providing the authorized attribute along with role administrator for create method. so the  user should not only authenticate but also have administrator role to call this method. then for  update method i am providing authorized attribute with administrator and user roles. so the  user should have either administrator or user role to access this method. now let's run  the application and test the apis using post man. first let's try to execute the get customers api  method and you can see that we have received 401 unauthorized response now. let's get a jwt token from authenticate api method by providing the  credentials for admin user. let's copy this token from the response and use it in the  authorization header of get customers method. we have received 200 okay response. that means api execution is successful. there are no customers registered and that is why  it is not showing any records. so first let's try to create a customer let the body content be the  same. we can provide the authorization header now. got 200 ok response. now let's try the  get customers method again. we can see the customer data. so it is working perfectly. now let's try with the user 01 credentials and just replacing the token  in authorization header. the get customers method is working fine with  this user as well. now let's try the create method. you can see the 403 forbidden response as  the create method will only allow users with administrator role. now let's try the update method  the update method should allow both user roles. we got 200OK response. let's check whether  the data got updated. so all are working fine. hope you are clear with the  authentication from micro services. next we are going to see how we can  implement authentication from ocelot api gateway. so first let's add the project  reference in the ocelot api gateway project. now we can do the jwt  authentication dependency injection. also don't forget to add app  dot use authentication and app dot use authorization methods. now let's implement the authentication  in the ocelot configuration json file. this time i am implementing  it in the product web api. we can use authentication options for implementing  authentication. inside that, the authentication provider key is bearer. then allowed scopes. now let's try this api methods in post man. so you can see that the get products api method  is returning 401 unauthorized response without authorization header. so let's try by  providing the authorization header. now it is working fine. we got 200OK response. let's create a product now. the product got saved successfully. next let's see how we can implement role-based  authorization in ocelot configuration. for that we need to make a small change  in jwt token handler class. this claim types dot role is a string value which  contains a url kind of value in it. we can change it to a simple string value as it may through  error if used in ocelot configuration json file. now in ocelot configuration, we can provide route claims requirement. then provide the same string  value here and the role to be allowed. now let's test this using postman. we have created a new product  successfully using admin credentials. we can also see the products using get products  method. now let's try with the other user. it is showing 403Forbidden  response. so the role based authorization is working fine. now i'll just show  you the rate limiting functionality of the ocelot api gateway. let's  use the order web api for that. we can use rate limit options to enable this  functionality. client whitelist is an array that contains the whitelisted clients. it means that  the client in this array will not be affected by the rate limiting. let it be empty. then  enable rate limiting it should be true if we need to enable rate limiting. then period  value specifies the period that the limit applies to such as 1s for 1 second, 5m for 5  minutes, 1h for 1 hour, 1d for 1 day and so on. if you make more requests in this period than the  limit allows, then you need to wait for period time span to elapse before you make another request. let  me provide 60s we can also provide it as 1m. next is period time span this value specifies that  we can retry after a certain number of seconds. i am providing 60 seconds for that as well. limit  is value specifies the maximum number of requests that a client can make in a defined period. let it  be one now. let's try the api methods in postman. first let's try to create a new order using  the create api method. we got 200OK response. now trying to execute get orders api method. we  can see the order details which we created now. let me try to execute the api again. now we got 429  too many requests as a response. also we can see some message in the response content.  these can be customized. let's see how it is. for that we can move to the global configuration  section. then provide rate limit options and inside that, first let's provide a custom message for  the response message. let it be request not allowed next we can customize the http status code. i am providing 909. let's try it in postman. we got the order details in the initial request. let me try again. now you can see that we have received 909 http status code and the custom  message has been displayed as a response body. so that's it for this video. hope you liked  it. please subscribe like and share this video. see you all in the next video. thank you!
Info
Channel: Coding Droplets
Views: 15,340
Rating: undefined out of 5
Keywords: ocelot api gateway jwt authentication tutorial, ocelot api gateway jwt authentication, ocelot api gateway authentication, ocelot api gateway, .net core, .net microservice, asp.net core, microservice, microservices, ocelot, asp net, asp.net, asp.net core 6 tutorial, docker compose, docker desktop, dotnet, microservices c#, microservices tutorial, ocelot .net, postman api testing tutorial, web api, what is microservices, api gateway, ocelot asp.net core, .net ocelot
Id: P2osfctiHAc
Channel Id: undefined
Length: 23min 35sec (1415 seconds)
Published: Tue Aug 09 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.