Authorizing APIs

In modern time, we generally use Web APIs. These Web APIs are resource-specific and stateless. Thus, we have to implement security to secure the APIs.
 
In a real-life scenario, we use a microservice architecture. So, we generally create microservices based on the specific domain. For example - we have a microservice named Authorization Service. This will create a token for the API based on the username and password.
 
Content Service
 
This will show the content based on the user or authorization. I am going to demonstrate the authorization code in content service which is deployed on a different server. We will install the below NuGet Packages for implementing the Owin Security.
 
Packages
  1. Microsoft.owin.cors  
  2. Microsoft.AspNet.Identity.Owin  
  3. Microsoft.Owin.Security.OAuth  
  4. Microsoft.Owin.Security  
  5. Microsoft.Owin.Host.SystemWeb  
  6. Owin  
  7. Microsoft.Owin  
After adding the package, we will add the StartUp class. This class is the entry point of the request. The request will be received in StartUp, then Middleware, and then the instace of the controller is created.
 
StartUp Class
  1. Public class StartUp {  
  2.     Public Static OAuthAutherizationserverOptions oAuth {  
  3.         get;  
  4.         private set;  
  5.     }  
  6.     static startup() {  
  7.         OAuth = new OAuthAutherizationserverOptions {  
  8.             TokenEndPointPath = new PathString("/Token"),  
  9.                 Provider = new OAuthProvider(),  
  10.                 AccessTokenExpireTimeSpan = Timespan.FromMInutes(20), // Expiration time of the token  
  11.                 AllowInsecureHttp = True // for local, On production please do it false  
  12.         }  
  13.     }  
  14.     Public void Configuration(IAppBuilder app) {  
  15.         app.UseOAuthBearerTokens(OAuth); // middleware code to authenticate the Bearer token.  
  16.     }  
  17. }  
The below code is for authorizing the context based on the bearer token.
 
Provider class code
  1. Public class X: OAuthAuthorizationServerProvider {  
  2.     public override Task ValidateClientAuth(OAuthValidateClientAuthenticationContext c) {  
  3.         if (context.ClientId == null) {  
  4.             c.Validated();  
  5.         }  
  6.         return Task.FromResult < object > (null);  
  7.     }  
  8. }  
In this example, we are not generating the token. We are just validating the token in other APIs. We are using the same token which is generated by Authorization service on a different server.
 
We have to use the machine key in the web.config. So, both the servers can share the session.