Sunday, June 7, 2020

Protect an API by using OAuth 2.0 with Azure Active Directory and API Management

Protect an API by using OAuth 2.0 with Azure Active Directory and API Management
https://docs.microsoft.com/en-us/azure/api-management/api-management-howto-protect-backend-with-aad

First Create a simple web API and host into Azure app service.

Go to Visual Studio -> Visual c# -> ASP.Net web application

Select Web API -> click on OK button.

Visual studio -> Ctrl + F5 to run application -> check web API result.

now deploy Web API into azure app service. Follow below steps to deploy.





Copy this URL into notepad.
https://webapplication1202200514100115.azurewebsites.net/api/

go to Azure and check whether Web API deployed or not.

now Web API need to deploy into API Management. to do follow below steps.

Go to App service (where Web API deployed) -> API Management -> Create new API Management if not exist else may chose existing one.

Fill required fields to create API Management instance. 


after create new API Management instance need to link Web API endpoints. 
go to App Service -> API Management -> select Echo API under API section then click on Link API button.

To update Web API URL into echo API,
go to API Management -> APIs -> Echo API -> Settings -> Web Service URL -> paste Web API URL
https://webapplication1202200514100115.azurewebsites.net/api/ -> click on Save button.

API Management service -> APIs -> Echo API -> Design -> Get operation -> Fronted edit ->

API Management service -> APIs -> Echo API -> Design -> Get operation -> Fronted edit -> under Get operation enter "/values" Web API's get operation endpoint.

To test click on Developer portal (legacy)

Select APIs Tab -> Get operation -> enter required fields -> click on "Send" button.

Web API endpoint return result, but there is no protection. Whoever have endpoint URL and subscription key they can call API.  If any one want consume this API they have to ask subscription key and we should not give our subscription key to other. to avoid this situation whoever need our API first they need to give us there Azure App details to us then we will add as a trusted App. then they can consume our API without our subscription key. 

First we need to create two Apps.
1. backend-app ->  act as web API
2. client-app  -> client application which is consuming protected Web API

To create and configure backend-app follow below steps.








To create and configure client-app follow below steps.










Now create OAuth 2.0 Service.
To Create and Configure OAuth 2.0 Service follow bellow steps.







Add validate-jwt to validate client-app token. if client-app return invalid token then jwt validate and return unauthorized message.



In API Management console successfully called the Protected Web API by using OAuth 2.0 with Azure Active Directory and API Management.
Chrome Extension for CORS testing.

Successfully called the Protected Web API by using OAuth 2.0 with Azure Active Directory and API Management.

<!DOCTYPE html>
<html>

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <script>
    $(document).ready(function () {
      var token = getToken();      
    });

    function getToken() {
      var settings = {
        "url": "https://login.microsoftonline.com/05e85d9f-3679-4080-a879-17a8669ef4fe/oauth2/v2.0/token",
        "method": "POST",
        "headers": {
          "Content-Type": ["application/x-www-form-urlencoded", "application/x-www-form-urlencoded"]
        },
        "data": {
          "grant_type": "client_credentials",
          "client_id": "2000da14-0dc9-4793-92c5-16184f6c397e",
          "client_secret": "S~WG-20k-Bhgn1reMvtS..S6Ug0OEP80cz",
          "scope": "api://2b2b2c0c-6c5e-4f0c-b669-6143e4fc5740/.default"
        }
      };
      $.ajax(settings).done(function (response) {
        callAPI(response.access_token);
      });
    }

    function callAPI(token) {
      var settings = {
        "url": "https://webapplication120200514100115-apim.azure-api.net/echo/values?param1=sample",
        "method": "GET",
        "headers": {
          "Ocp-Apim-Subscription-Key": "d09030939c7c4bc6bd319893c263f9f4",
          "Authorization": "Bearer " + token
        },
      };
      $.ajax(settings).done(function (response) {
        $("#divData").text(response);
      });
    }
  </script>
</head>

<body>
  <div id="divData"></div>
</body>

</html>



11 comments:

  1. Thank you for sharing such a Magnificent post here. I found this blog very useful for future references. keep sharing such informative blogs with us. How to install Android on PC

    ReplyDelete
    Replies
    1. A full-stack developer may also need to understand how APIs connect different parts of an application. The backend can provide business functionality through REST endpoints while frontend applications consume those endpoints to retrieve or submit information. Dot Net Full Stack Online Training offers a relevant learning path for connecting backend development, APIs, and other components involved in full-stack applications.

      Delete
    2. When the frontend is built with Angular and the backend uses ASP.NET Core, API communication becomes an important part of the overall application architecture. Developers can benefit from understanding how authentication, API requests, backend services, and frontend components work together rather than treating each layer independently. ASP.NET Core Angular Full Stack Online Training can support learning around this combination and provide a broader perspective on developing integrated full-stack applications.

      Delete
    3. Securing APIs is an essential part of building reliable cloud applications, particularly when services are exposed through public endpoints. This tutorial provides a useful starting point for understanding how OAuth 2.0, Azure Active Directory, and Azure API Management work together to protect backend APIs. Deploying a Web API to Azure App Service and configuring authentication helps developers understand the practical steps involved in implementing access control for cloud-hosted applications.

      Security-focused projects provide valuable opportunities to apply authentication and authorization concepts in real-world scenarios. Students exploring secure application development can use Cyber Security Projects for Final Year to explore project ideas involving API security, identity management, and protection against unauthorized access.

      Delete
    4. Beyond authentication, effective API security requires a broader understanding of vulnerabilities, access policies, and secure system design. Working on Information Security Projects for Final Year can help students investigate security mechanisms and develop practical solutions for protecting applications, data, and cloud-based services.

      Delete

  2. When searching for reliable printing solutions, many customers look for convenient options, especially when it comes to quality transfers. If you're interested, you can easily find a service by searching for dtf transfers near me. These services provide efficient and high-quality transfers that meet your needs. Whether you're a small business owner or a hobbyist, finding local options can save you time and ensure timely results.

    ReplyDelete
  3. Thank you for sharing such a Magnificent post here. I found this blog very useful for future references. keep sharing such informative blogs with us.best air cargo services in islamabad

    ReplyDelete
  4. I sincerely enjoy using penalty shooter because it delivers realistic football gameplay with exciting penalty shootouts. Every challenge feels rewarding, while the polished visuals and smooth controls make the overall experience highly entertaining.

    ReplyDelete
  5. It's easy to appreciate space type
    because the game perfectly combines education with entertainment. Every typing challenge rewards improvement while providing colorful graphics, smooth gameplay, and exciting space-themed adventures for every player.

    ReplyDelete
  6. A full-stack developer may also need to understand how APIs connect different parts of an application. The backend can provide business functionality through REST endpoints while frontend applications consume those endpoints to retrieve or submit information. packers and movers in Rawalpindi

    ReplyDelete

Featured Post

Power Platform ALM with GitHub Actions: Export, Source-Control and Deploy a Cloud Flow Solution (Step by Step)

Moving Power Automate flows between environments by hand (export a zip, import a zip, fix connections, repeat) does not scale and leaves n...

Popular posts