Automatically Acquire Access Token for Site Hosted in SharePoint to Authenticate in On-Premise Web API
Image by Jacynthe - hkhazo.biz.id

Automatically Acquire Access Token for Site Hosted in SharePoint to Authenticate in On-Premise Web API

Posted on

Are you tired of dealing with authentication hassles when trying to access your on-premise web API from a SharePoint site? Do you wish there was a way to automatically acquire an access token for seamless authentication? Well, you’re in luck! In this article, we’ll guide you through the process of automatically acquiring an access token for a site hosted in SharePoint to authenticate in an on-premise web API.

Understanding the Problem

When trying to access an on-premise web API from a SharePoint site, you may encounter authentication issues. This is because SharePoint and the web API are two separate entities, and the default authentication mechanism may not work as expected. To overcome this hurdle, you need to acquire an access token that can be used to authenticate with the web API.

Why Do We Need an Access Token?

An access token is a security token that proves an identity and authenticates a user or application to access a protected resource. In our case, the protected resource is the on-premise web API. By acquiring an access token, you can authenticate with the web API and access the required data or services.

What Are the Benefits of Automatically Acquiring an Access Token?

  • Seamless authentication: With automatic access token acquisition, you can authenticate with the web API without requiring users to enter credentials manually.
  • Improved user experience: Users don’t need to remember additional credentials or go through multiple authentication steps.
  • Enhanced security: Automatic access token acquisition reduces the risk of credential theft or phishing attacks.

Prerequisites

Before we dive into the process of automatically acquiring an access token, make sure you have the following prerequisites in place:

  • A SharePoint site (2013 or later)
  • An on-premise web API (hosted on a server or in a cloud environment)
  • A registered Azure AD application (for OAuth 2.0 authentication)
  • The Azure AD application has been granted permissions to access the web API
  • The SharePoint site has been configured to use Azure AD as the authentication provider

Step 1: Configure the Azure AD Application

In this step, we’ll configure the Azure AD application to issue an access token for our SharePoint site.

  1. Log in to the Azure portal (https://portal.azure.com)
  2. Navigate to the Azure AD application you registered earlier
  3. Click on “Authentication” under “Manage” section
  4. Click on “Add a platform” and select “Web”
  5. In the “Web” platform configuration, enter the following details:
    • Redirect URI: https://[SharePoint-site-url]/_layouts/15/oauth2.ashx
    • Front-channel logout URL: https://[SharePoint-site-url]/_layouts/15/oauth2.ashx
  6. Click “Configure” to save the changes

Step 2: Configure the SharePoint Site

In this step, we’ll configure the SharePoint site to use the Azure AD application for authentication.

  1. Log in to the SharePoint site as an administrator
  2. Navigate to the SharePoint site’s “Site Settings” page
  3. Click on “Site Administration” and then “Site Collection Features”
  4. Activate the “OAuth 2.0 Authentication” feature
  5. Click on “OAuth 2.0 Authentication” under “Site Administration”
  6. In the “OAuth 2.0 Authentication” configuration, enter the following details:
    • Client ID: [Azure-AD-application-client-ID]
    • Client secret: [Azure-AD-application-client-secret]
    • Authorization URL: https://login.microsoftonline.com/[Azure-AD-tenant-ID]/oauth2/v2.0/authorize
    • Token endpoint URL: https://login.microsoftonline.com/[Azure-AD-tenant-ID]/oauth2/v2.0/token
  7. Click “OK” to save the changes

Step 3: Acquire the Access Token

In this step, we’ll use the SharePoint REST API to acquire an access token for the on-premise web API.

<script>
  (function () {
    var accessToken;
    var resourceId = "[on-premise-web-API-resource-ID]";
    var clientId = "[Azure-AD-application-client-ID]";
    var clientSecret = "[Azure-AD-application-client-secret]";
    var tokenEndpointUrl = "https://login.microsoftonline.com/[Azure-AD-tenant-ID]/oauth2/v2.0/token";

    function acquireAccessToken() {
      var headers = {
        "Content-Type": "application/x-www-form-urlencoded"
      };

      var data = {
        "grant_type": "client_credentials",
        "client_id": clientId,
        "client_secret": clientSecret,
        "resource": resourceId
      };

      $.ajax({
        type: "POST",
        url: tokenEndpointUrl,
        headers: headers,
        data: data,
        success: function (response) {
          accessToken = response.access_token;
          console.log("Access token acquired: " + accessToken);
        },
        error: function (xhr, status, error) {
          console.log("Error acquiring access token: " + error);
        }
      });
    }

    acquireAccessToken();
  })();
</script>

Step 4: Use the Access Token to Authenticate with the Web API

In this step, we’ll use the acquired access token to authenticate with the on-premise web API.

<script>
  (function () {
    var webApiUrl = "[on-premise-web-API-url]";
    var accessToken = "[acquired-access-token]";

    $.ajax({
      type: "GET",
      url: webApiUrl,
      headers: {
        "Authorization": "Bearer " + accessToken
      },
      success: function (response) {
        console.log("Authenticated with web API: " + response);
      },
      error: function (xhr, status, error) {
        console.log("Error authenticating with web API: " + error);
      }
    });
  })();
</script>

Troubleshooting Common Issues

Here are some common issues you may encounter during the process and their solutions:

Issue Solution
Error acquiring access token Verify the Azure AD application configuration, client ID, and client secret. Ensure the SharePoint site is configured to use the correct Azure AD application.
Invalid access token Verify the acquired access token is valid and not expired. Check the token endpoint URL and resource ID.
Authentication failed with web API Verify the web API is configured to accept the acquired access token. Check the web API’s authentication settings and ensure the correct permissions are granted.

Conclusion

In this article, we’ve demonstrated how to automatically acquire an access token for a site hosted in SharePoint to authenticate in an on-premise web API. By following these steps, you can seamlessly authenticate with your web API and access the required data or services. Remember to troubleshoot common issues and ensure the correct configuration of your Azure AD application, SharePoint site, and web API.

Happy coding!

Frequently Asked Question

If you’re struggling to authenticate with an on-premise web API from a site hosted in SharePoint, you’re not alone. Here are some frequently asked questions to help you automatically acquire an access token for seamless integration.

What is the main challenge in authenticating with an on-premise web API from a SharePoint site?

The main challenge is obtaining an access token to authenticate with the on-premise web API from a SharePoint site, as SharePoint uses a different authentication mechanism than the API.

How can I acquire an access token for the on-premise web API from a SharePoint site?

You can acquire an access token by registering an Azure AD application, configuring the API permissions, and using the client ID and client secret to request an access token using the OAuth 2.0 client credentials flow.

What is the purpose of the client ID and client secret in acquiring an access token?

The client ID and client secret are used to authenticate the Azure AD application and authorize it to request an access token for the on-premise web API. They serve as credentials to prove the identity of the application.

Can I use the SharePoint site’s authentication mechanism to acquire an access token for the on-premise web API?

No, you cannot use the SharePoint site’s authentication mechanism to acquire an access token for the on-premise web API. SharePoint uses a different authentication mechanism than the API, so you need to use a separate authentication flow to acquire an access token.

How can I handle token refresh and expiration when acquiring an access token for the on-premise web API?

You can handle token refresh and expiration by implementing a token cache and using the refresh token to request a new access token when the existing one expires. This ensures that your application remains authenticated with the API.

Leave a Reply

Your email address will not be published. Required fields are marked *