Experiencing a 404 error after attempting to access an endpoint following a successful MSAL Azure AD

Incorporating the UserAgentApplication.loginPopup function to authenticate users on our Azure AD has been a challenge as we transition from an ASP.NET MVC application to a Vue.js front end and ASP.NET 'API' backend. The goal is to pass the accessToken obtained from MSAL to our backend in order to verify access levels. While everything works perfectly locally, once the project is deployed to the server, hitting the '/api/authentication/SetAzureUser' endpoint results in a 404 error.

route.js

var myMSALObj;

const getLoginPopup = (request) => {
    return myMSALObj.loginPopup(request);
}

const getTokenPopup = (request) => {
    return myMSALObj.acquireTokenSilent(request)
        .catch(() => {
            // fallback to interaction when the silent call fails
            return myMSALObj.acquireTokenPopup(request)
                .then(tokenResponse => {
                    return tokenResponse;
                }).catch(error => {
                    console.log(error);
                });
        });
}

const azureUserAuthentication = async () => {
    const utilityStore = useUtilityStore();

    try {
        const msalConfig = {
            auth: {
                clientId: "clientId",
                authority: "https://login.microsoftonline.com/",
                redirectUri: `${window.location.protocol}//${window.location.host}/api/authentication/AzureAuthenticationCallback`,
            },
            cache: {
                cacheLocation: "sessionStorage", 
                storeAuthStateInCookie: false, 
            }
        };

        const loginRequest = {
            scopes: ["openid", "profile", "User.Read.All"]
        };

        const tokenRequest = {
            scopes: ["Mail.Read"]
        };

        myMSALObj = new UserAgentApplication(msalConfig);

        var loginPopupResponse = await getLoginPopup(loginRequest);

        if (loginPopupResponse != null && myMSALObj.getAccount()) {
            var tokenResponse = await getTokenPopup(tokenRequest);

            if (tokenResponse != null) {
                
                // Getting 404 on this axios call.
                var setAzureUserResponse = await axios({
                    method: 'get',
                    url: '/api/authentication/SetAzureUser',
                    contentType: "application/json",
                    withCredentials: true,
                    params: {
                        accessToken: tokenResponse.accessToken
                    }
                });

                if (!setAzureUserResponse.succeeded) {
                    window.document.title = "Unauthorized Access";
                    return { name: 'unauthorized-access' }
                } else {
                    utilityStore.$patch({ showProcessingOverlay: false });
                }
            }
        }
    } catch (ex) {
        console.log(ex);
    }
}

API Endpoint

    [HttpGet("SetAzureUser")]
    public JsonResult SetAzureUser(string accessToken)
    {
        return Json(_authenticationService.AuthenticateAzureUser(_stateManagement.BuildBaseParameters(), accessToken));
    }

Answer №1

My decision ultimately veered away from using loginPopUp and instead I went with loginRedirect.

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

Discovering and revising an item, delivering the complete object, in a recursive manner

After delving into recursion, I find myself at a crossroads where I struggle to return the entire object after making an update. Imagine you have an object with nested arrays containing keys specifying where you want to perform a value update... const tes ...

Using window.print as a direct jQuery callback is considered an illegal invocation

Curious about the behavior when using Chrome $(selector).click(window.print) results in an 'illegal invocation' error $(selector).click(function() { window.print(); }), on the other hand, works without any issues To see a demo, visit http://js ...

When there is an error or no matching HTTP method, Next.js API routes will provide a default response

Currently, I am diving into the world of API Routes in Next.js where each path is structured like this: import { NextApiRequest, NextApiResponse } from "next"; export default async (req: NextApiRequest, res: NextApiResponse) => { const { qu ...

In JavaScript, navigate to a new page only after successfully transmitting data to the server

Creating a redirect page that sends data to the server before transitioning to a new page can be achieved using JavaScript as shown below. <body> <script type="text/javascript"> **** Discussion of cookie-related transactions **** document.c ...

The border of the Material UI Toggle Button is not appearing

There seems to be an issue with the left border not appearing in the toggle bar below that I created using MuiToggleButton. Any idea what could be causing this? Thank you in advance. view image here view image here Just a note: it works correctly in the ...

The Importance of Selenium Events and Patience

Currently, I am using Selenium to automate some testing for our company's website, but encountering issues along the way. TestItemFromSearch: (driver, part, qty) => { Search.SearchItem(driver, part); driver.findElement(By.id('enterQty ...

The most effective method for acquiring an object through inheritance

I'm seeking advice on the best practice for adding behavior to an object received as a JSON object. I have REST services that allow me to define a sort of state machine. The API defines a /sessions resources. When creating a session via POST /sessio ...

Learn how to incorporate the prettier command into your coding workflow by adding it as a devDependency before committing code or

I am currently engaged in a React project. I am looking to set up autoformatting on save in my Visual Studio Code. However, I prefer not to adjust the settings within VSCode itself due to the variation in configurations among users. Instead, I want to ach ...

Executing an http.get request in Angular2 without using RxJS

Is there a method to retrieve data in Angular 2 without using Observable and Response dependencies within the service? I believe it's unnecessary for just one straightforward request. ...

Is there a way for me to update the button text and class to make it toggle-like

Is there a way to switch the button text and class when toggling? Currently, the default settings show a blue button with "Show" text, but upon click it should change to "Hide" with a white button background. <button class="btn exam-int-btn">Show< ...

What is the technique for accessing dynamic object properties in Javascript?

I am dealing with a dynamic object where the property values change based on different data sets. For example: MyObj = { country:"Ind", Place:"Pune"} Now, I have a data value that determines which property value I need to retrieve. var MyArr = this.Filt ...

Issue TS2349 occurs when attempting to use a combination of boolean and function types within union typing

In my class, there is a property called "isVisible" which can be either a boolean value or a function that returns a boolean. The code snippet below demonstrates what I am currently using. It works fine and achieves the desired result, but during compilat ...

Embedding JSON data in a GSP page

My goal is to transfer JSON data to a GSP page and present it in a table format. The expected JSON structure: { "data": [ [ "Tiger Nixon", "System Architect", "Edinburgh" ] ]} I attempted to achieve this with the following co ...

Troubleshooting: Android compatibility issues with dynamic source for HTML 5 video

My HTML5 video with dynamic source loaded using JavaScript is functioning properly in a web browser but encountering issues within an Android PhoneGap build application. Take a look at the code snippet below: JavaScript code: $('#video_player' ...

Notifying a Child Component in React When a Props-Using Function Resolves a REST Call

When I submit an item or problem, I trigger a function in the parent component that has been passed down to the child component as props. After sending my information, I want to clear the input fields. The issue is that I am clearing the input fields immed ...

Querying the database to check for the presence of a file in a .js file on Google App Engine

I'm currently working on implementing an upload button for users to upload files to our storage system using Google App Engine with Python, as well as HTML and JavaScript for the views. To achieve this, we have an HTML file and a.js script that promp ...

Is it possible to interpret all events from multiple perspectives?

Is it possible to listen for events in three different ways? This example shows how we can listen for the load event: 1. <body onload="doSomething();"> 2. document.body.onload = doSomething; 3. document.body.addEventListener('load', doS ...

At times, the Angular Modal Dropdown may unexpectedly open in an upward direction

Dealing with an AngularJS modal that contains a dropdown menu. The menu list is quite extensive. Most of the time, around 70%, the menu drops down in the lower direction which is fine. However, approximately 30% of the time, the dropdown menu appears in ...

Is there a way to utilize a value from one column within a Datatables constructor for another column's operation?

In my Typescript constructor, I am working on constructing a datatable with properties like 'orderable', 'data' and 'name'. One thing I'm trying to figure out is how to control the visibility of one column based on the va ...

How can you disable a single button when clicked using the map method, and update the className after a timer runs out in React?

Is there a way to disable only one button when clicked using the map method? I currently have a disabled hook that affects all pressed buttons. Also, how can I revert the 'current__events__hot-price disabled' className back to 'current__even ...