Interacting with a Web API using JavaScript following successful authentication with Azure AD B2C

Currently, I am working on a .Net Web App. After going through the authentication process with Azure AD B2C using the Azure AD Connect protocol, my app's controller successfully obtains an access token via the MSAL library (written in C# code) to connect to a backend Web API. Everything works smoothly up to this point. Now, I need to figure out how to utilize this access token obtained from the server-side C# code in my client-side JavaScript within the same web app to access the Web API without being prompted to sign-in again.

To kick things off, I utilized sample code available on GitHub which helped get me started with the process. However, when I run my JavaScript code, it throws an error stating: "user_login_error:User login is required".

if (!clientApplication) {
    clientApplication = new Msal.UserAgentApplication(window.config.clientID, window.config.authority, authCallback);
    clientApplication.redirectUri = window.config.redirectUri;
}

function ReloadInfo(type, language, location) {
    clientApplication.acquireTokenSilent(window.config.b2cScopes).then(function (accessToken) {
        ReadResource(accessToken, type, language, location);
    }, function (error) {
        clientApplication.acquireTokenPopup(window.config.b2cScopes).then(function (accessToken) {
            ReadResource(accessToken, type, language, location);
        }, function (error) {
            debugger
            logMessage("Error acquiring the access token to call the Web api:\n" + error);
        });
    })
}

Any insights or help regarding this matter will be greatly appreciated! Thank you!

Answer №1

If you're looking for a straightforward solution to this situation, consider creating a dedicated controller to interact with the web API.

When working with JavaScript, rather than directly accessing the web API, you can have your script communicate with your web app instead. By leveraging the sign-in feature, JavaScript can effectively communicate with the controller without the necessity of utilizing the MSAL library for JavaScript in this particular setup.

Update

<script src="https://code.jquery.com/jquery-3.2.1.js"
              integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE="
              crossorigin="anonymous"></script>
<script>
    $(document).ready(function () {
        $("#Location").change(function () {
            $.ajax({
                url: "data.html",//modify the path HTTP request you wanted
            }).done(function (data) {
                console.log(data);// handle the result data here
            });
        });
    })


</script>

To learn more about jQuery, check out the complete documentation here.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for Dynamic Importing and Rendering of Components in ReactJS

I'm looking to dynamically import and render a component in React. I have two components - Dashboard and Home. Essentially, I want to dynamically render the Dashboard Component inside the Home Component without having to import it beforehand or maybe ...

Chrome tab freezes when scrolling with the mouse

Working on a particularly interesting bug, I've managed to replicate it using a fiddle. The issue arises when the middle mouse button is clicked over the div element containing text, causing the pointer to become stuck. Is this possibly a browser bug ...

Pretending to determine the exact height of the body

I am facing a challenge with my JavaScript application that is loaded within an iframe through a Liferay portlet. The HTML container is currently empty and the JS is loaded only when the document is fully loaded. Upon loading the page in the iframe, Lifer ...

What is the best way to show the current value of a checkbox element in the future?

I want to add multiple checkboxes using this method: $(".btn-sample").on("click", function() { $(".container").append( '<input class="check-sample" type="checkbox" value="'+check_value+'"/>' ); }); The issue I' ...

NPM TypeORM is throwing the error message "Duplicate migrations" when changes are made to a migration file

Recently, I made a modification to an existing table by adding a new column using the command npm run migration:generate <filename>. Unfortunately, I realized later on that I had misspelled the column name and needed to correct it (showComission -&g ...

The ancient oracle of Delphi and the modern login portal of Microsoft

I need to login to a site that utilizes . To streamline the process for end-users, I want to store credentials in an .ini file and inject them into a two-stage JavaScript online prompt. Is there a way to have Delphi run a program with a browser that auto ...

City-based Address Suggestions with Google API Places

I have been struggling to find a solution to this specific issue without any luck. Your assistance would be greatly appreciated. Currently, I am attempting to implement autocomplete address functionality using Google API with the following code: var inpu ...

What is the best way to create divs that can close and hide themselves when clicked from inside the div itself?

I have a situation in my code where clicking a link reveals a div, and then the same link must be clicked again to hide it. However, I want to modify this so that any link within the div can also hide it when clicked. I currently have eight divs set up lik ...

Using jQuery Ajax and PHP for Secure User Authentication

Hello everyone, I could really use some assistance right now. The issue I'm facing is that the error div is not showing the content I expect in the success function of my AJAX request. I've tried alerting the response, which returns true if the ...

Displaying a single photo on mobile, while simultaneously showing four photos on the web using Nuxt.js

When viewing the web browser from a mobile device, only one image should be displayed instead of all four images fetched from an API. What are some possible ways to achieve this? The data retrieved includes all the images at once. <template> <d ...

Drop-down options disappear upon refreshing the page

Code snippet for sending value to server using AJAX in JavaScript In my script, the status value may vary for each vulnerable name. When selecting a status option and storing it in the database through AJAX, the selected value is lost after refreshing th ...

Achieving CSS transition effects using the .appendChild function in JavaScript

When using the mouseenter event, I have a JavaScript function applied to an svg path element: const fadeIn = (event, locale) => { event.target.style.fill = 'hwb(' + (120 - score[locale] * 1.2) + ' 0% 0% / 1)' } This function wor ...

Use Yii2 to pass an ID when a button is clicked in order to render a partial using

On the index page, I display all the rows and some fields from my model. When a button is clicked, I want a modal to appear with all the data from the corresponding row. When the button is clicked, I need an ajax call to render a partial view. This will i ...

Protractor unable to locate elements using by.repeater

What is the best method for targeting this repeater with Protractor? <a ng-repeat="item in filteredItems = (items | filter:'abc')">{{item}}</a> ...

The act of employing `Function.prototype.run` within an Angular TypeScript class is deemed as illegitimate

Is there a way to globally define a new function called run within my Angular component as shown below? Function.prototype.run = function (delay: number) { // some content; }; However, the compiler shows an error that the Property 'run' does n ...

What could be causing the lack of updates for a watched object in vue?

Although there are many similar questions on this topic, mine has a unique twist. After delving into reactivity in depth, I feel like I have a solid grasp of the concept. However, one thing continues to baffle me: Summary: Why does a watched property det ...

The div is incorrect and causing the label and input to move in the wrong direction

Whenever I try to adjust the position of the current-grade-name-input, the entire grade-point-input moves along with it inexplicably. /* final grade calculator: (wanted-grade - (current-grade * (1 - final%))) / final% Ex: have a 80 an ...

Setting up Express routes in a separate file from the main one: a step-by-step

My goal is to organize my routes separately from the main app.js file using the following file structure. I attempted to create a api/user/ post API but encountered a 404 error. Any suggestions on how to resolve this issue with the given file structure? . ...

Extra spaces within the source code visible after the page has been processed by Angular

Within my angular application, I am retrieving a list of addresses from a service that provides an object structured like this: { Flat: "10B", BuildingName: "Some Building", Line: "10B Some Building Road Town POST CODE", Postcode: "POST CODE", ...

Steps to close a socket upon session expiration

I am currently working on a small express application that also incorporates a socket program. Everything works perfectly when a user successfully logs in - it creates the session and socket connection seamlessly. However, I encountered an issue where eve ...