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

Securing folder access using Web.Config Authorization

When setting access rules in the login module, is there a specific denial of all at the end? Imagine I have two distinct roles: Admin and User Admins can enter the directory iPhone while Users can access the directory Blackberry I organize my rules and ...

Updated the object in an array retrieved from an API by adding a new key-value pair. Attempted to toggle the key value afterwards, only to find that

Essentially, I am retrieving products from an API and including a new key value isAdded in the object within the products array. I utilized a foreach loop to add that key and it was successfully added. Now, when I click the Add to cart button, the product ...

Configuring CORS in an Angular JS controller

Having a controller with a service that retrieves JSON from another server, I encountered the following issue: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http:somesite.com. This can be fixed by moving the ...

"I'm encountering an issue with Passport.js where req.isAuthenticated is throwing an error as not

Recently I started working with node and express, along with passport.js for building an authentication feature. However, I encountered an issue while using a middleware function called "checkNotAuthenticated" in my routes. The error message I received was ...

Is it possible to obtain the index of a table row using querySelector?

Is it possible to find the rowIndex of the first occurrence of a table row within the #myTable using JavaScript? http://jsfiddle.net/bobbyrne01/fmj6np6m/1/ html .. <table id="otherTable"></table> <table id="myTable"></table> js ...

Tips for extracting a value from a geojson response using a specific key

When analyzing the geojson response below, I am trying to access the following: Type and Segments To achieve this, I attempted the following: return data["type"] //does not work, error received return data["features"][0]["properties"]["segments"] ...

Transform strings in a table into integers within a specified scope

My World.json file is quite large and contains extensive data on countries worldwide. I've been utilizing a list to display this data in a table format, with the intention of sorting all values accordingly. However, I have encountered an issue - all m ...

Confirming the accuracy of multiple fields in a form

Looking for help with validating both password and email fields on a registration form. I've successfully implemented validation for passwords, but need assistance adding validation for the email section as well. Can both be validated on the same form ...

Why is my "npm install" pulling in unnecessary libraries that I didn't even mention?

I've listed my dependencies in package.json as follows: { "cookie-parser": "~1.0.1", "body-parser": "~1.0.0", "express": "~3.5.0", "socket.io":"1.0", "mongodb":"2.2.21", "request":"2.79.0", "q":"1.4.1", "bcryptjs":"2.4.0", "jsonw ...

The function, stored as state within a context provider, is experiencing only one update

I am facing an issue with my Next.js and Typescript setup, but I believe the problem is more general and related to React. Despite extensive research on Stack Overflow, I have not come across a similar problem. To provide some context: I have a <Grid&g ...

Having issues with the jQuery .css function?

I need help with hiding and showing tabs on my webpage based on a successful login. I have tried various methods, such as setting the tab to be hidden by default in the HTML code and then using JavaScript to display it upon login. However, none of these me ...

What's the rationale behind receiving the second before the first?

I've been digging into ES6 promises, and I thought I had a handle on it for a moment. However, it seems like I may have hit a roadblock. What I'm aiming to do is handle a series of file operations where each operation depends on the completion o ...

Include an item in a JSON structure

I have a settings.json file that contains the following data (where 123456789 represents a unique user id): { "123456789": {"button_mode":true} } My goal is to add a similar id: {button_mode: value} object to this JSON file if there is no existing en ...

Babel fails to substitute arrow functions

After setting up babel cli and configuring a .babelrc file with presets to es2015, I also installed the es2015 preset. However, when running the command babel script.js --out-file script-compiled.js, I noticed that arrow function syntax (=>) was still p ...

html scroll to the flickering page

Why is it that when a user clicks on a link in the list, the browser flickers? This issue becomes especially noticeable if a user clicks on the same 'link' twice. Is there a solution to prevent this from occurring? The problem also seems to aris ...

Clearing Time Field Input in Safari

Recently, I've been utilizing the following HTML input element: <input type="time"> While testing it in both Chrome and Safari, I noticed that the clear field (cross button) is absent when using Safari. How can I make the cross button appear i ...

Javascript function fails to trigger when clicked

<body ng-app="starter"> <ion-pane> <ion-header-bar class="bar-dark"> <h1 class="title">AppifyLife</h1> </ion-header-bar> <ion-content> <center><div class="card" id="life"><h3>20< ...

Utilizing promise values within asynchronous functions

I know this question has been asked multiple times, but I'm facing a situation where I need to retrieve a variable created within a promise. The examples I've come across involve using .then to access the data, but in my case, I need to work with ...

Vue textarea not accepting null values

My current setup includes the following dependencies: - "vue": "3.2.26", - "vee-validate": "4.5.6", - "typescript": "4.5.4" While working on a textarea field in vue3, I encountered an issue Here's a snippet with vee-validate integration import { Fie ...

Having trouble with setting up local notifications in React Native's scheduling feature?

I have integrated the react-native-push-notifications npm library into my application to enable notifications. However, I am facing an issue while trying to schedule notifications using PushNotification.localNotificationSchedule. The code snippet for this ...