Guide on how to verify user identities with Azure AD in a Vue.js interface and backend developed with .Net 5

Our team is currently in the process of transitioning from .Net MVC to a Vue.js front-end. We had originally implemented a custom Attribute in our MVC version that utilized Azure AD for user authentication on specific pages. This attribute verified if users were logged into Microsoft and redirected them to our organization's login page if they were not. However, after moving to Vue.js, we encountered a Cross-Origin Request Blocked error during redirection attempts.

After researching solutions online, we attempted to switch to the Non-API approach that Microsoft offers with OpenId to resolve the issue. Unfortunately, we are still facing the same Cross-Origin Request Blocked problem with this alternative method. Our team is unsure of the next steps to take. Below is a snippet showcasing how our Startup.cs file is configured along with the controller we are using for testing purposes:

Startup.cs

public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors();
            services.AddHttpClient();
            services.AddMemoryCache();

            services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
                .AddMicrosoftIdentityWebApp(_configuration.GetSection("AzureAd"));

            services.AddAuthorization(options =>
            {
                options.AddPolicy("AuthorizeAccess",
                    policy => policy.Requirements.Add(new Helpside.Domain.Attributes.AuthorizeAccessAttribute()));
            });
         }

Controller

        [Authorize]
        [HttpGet("Test")]
        public JsonResult Test()
        {
            var response = "Test";

            return Json(response);
        }

Answer №1

Encountering a Cross-Origin Request Blocked error while trying to perform the redirect.

 

A special thanks to Zhi Lv for the valuable insights.

 

You must Install-Package:

 

 

Microsoft.AspNetCore.Cors

 

To resolve this issue, include the following code in your Startup.cs file.

 

builder.Services.AddCors(options => 
{ 
    options.AddPolicy(name: MyAllowSpecificOrigins, policy => 
    {            
        policy.WithOrigins("http://example.com", "http://www.contoso.com"); 
    });
});

 

Default Policy in ConfigureServices Method

 

public void ConfigureServices(IServiceCollection services)  {  
services.AddCors(options =>  
{ 
    options.AddDefaultPolicy(builder => { 
        builder.WithOrigins("[https://localhost:47531](https://localhost:47531/)", "[http://localhost:4430](http://localhost:4430/)")  
               .AllowAnyHeader()  
               .AllowAnyMethod();});});}

In the controller level, add the attribute to permit all origins.

[EnableCors("AllowAllOrigins")]

The Vue app needs to handle authentication using MSAL.js or ADAL.js and obtain access tokens for your backend API via the OAuth implicit flow.

 

For more information, check out the related query on SO 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 retrieving the most recent number dynamically in a separate component without needing to refresh the page

Utilizing both the Helloworld and New components, we aim to store a value in localStorage using the former and display it using the latter. Despite attempts to retrieve this data via computed properties, the need for manual refreshing persists. To explore ...

Creating a Docker image for a Vue.js application

I'm facing an issue while trying to build a docker image for my Vue.js app. Currently, I have a Vue.js application and I am looking to create a docker image for it. Here is the content of my Dockerfile: FROM node:7.7.2-alpine WORKDIR /usr/app CO ...

Coloring a table in vue.js based on performance rankings

I'm facing an issue with sorting my data performance in vue js. Here is the script I have created so far: <template> <div> <div class="row"> <h2> Campaign Performance </h2> <table class=&q ...

There was an issue with the Vuejs Router that prevented the property '$emit' from being read due to a TypeError because

I am facing an issue with a router configuration like this: { path: 'user', redirect: '/user', name: 'user', component: { render(c) { return c('router-view', { on ...

vuejs function for modifying an existing note

Method for editing an existing note with Vue.js in a web application This particular application enables users to perform the following tasks: Create a new note View a list of all created notes Edit an existing note Delete an existing note Prog ...

When a custom throw is triggered in Vue, the console error message appears un

I have implemented a custom throw in the created() method of my component. throw new Error(`Cookie ${cookieName} not found.`); However, Vue logs this error into the console: [Vue warn]: Error in created hook: "Error: Cookie showLanguageInfo not found ...

Troubleshooting Vue component reactivity problems with async server requests

Providing some background information: Within my Vue application, I have a view called Articles. Upon mounting this component to the DOM, I use the axios library to fetch all posts from the database through Laravel controllers and API routes. In the articl ...

Is it possible to assign a Component a name based on data?

In my project, I have three component icons named <DiscoverIcon>, <FeedIcon>, and <ProfileIcon>. In a tab loop, I want to display a different icon for each respective title. I experimented with using a list element like this: { key: 1, ...

Leveraging global variables within Vuex state management strategy

I have successfully added custom global variables into Vue by injecting them. Here is the code snippet: export default function (props, inject) { inject('models', { register(name) { const model = require(`@/models/${name}. ...

Upload several files to your form using formkit

I'm trying to create a form in vue.js using FormKit that allows users to upload multiple files. However, despite adding multiple="true" as the documentation suggests, I am unable to select more than one file. Here is the code snippet I have ...

Having trouble loading CSS and JavaScript files after building with vue-cli and webpack?

I'm working with koa2 as the backend and using koa-swig to handle page rendering. The project structure looks like this: https://i.stack.imgur.com/zYGNS.png Within the dist folder, you'll find index.html and a static directory containing all CSS ...

Encountering a bug in my JSON or object tree viewer in Vue.js 3 where duplicate keys are present when there are multiple similar values

Encountering an issue with the following code: Attempting to create a tree viewer from an object, it works well until encountering identical values which cause key duplication and replacement. View on CodePen: https://codepen.io/onigetoc/pen/rNPeQag?edito ...

My locale NUXT JavaScript files are being blocked by Content Security Policy

I've been working on implementing CSP headers for my website to ensure data is loaded from trusted sources. However, I'm facing an issue where CSP is blocking my local JS files. Here's a snippet from my nuxt.config.js: const self = 'lo ...

Are there alternative methods, aside from using a computed property, that can be utilized to store a Vue route parameter in a way where

In my Vue component, I am working on passing a route parameter through XHR requests and potentially using it in other areas as well. Initially, I considered storing it as a data attribute but realized that it could be modified by someone. Then it occurred ...

Avoid having Vue CLI delete all files in the dist folder

As I work on my Vue project, I am facing a challenge in syncing the dist folder with Git. Previously, this process ran smoothly when using webpack. However, after transitioning to @vue/cli and creating my project with vue create myProject instead of vue in ...

When a Javascript function marked as async is executed, it will return an object

Async function is returning [object Promise] instead of the desired real value. Interestingly, I can see the value in the console log. It seems like this behavior is expected from the function, but I'm unsure how to fix my code. This code snippet is ...

Harness the power of Postcss in combination with Vuepress

Struggling to integrate Postcss plugins into my custom Vuepress theme, but hitting a wall. The documentation provided by Vuepress is lacking and postcss-loader solutions aren't cutting it. Anyone have insights on how to make it work? ...

Avoiding node package trigger errors in another setting

I am facing an issue with my browser extension that utilizes Webpack. The problem lies in a specific package called webextension-polyfill, which throws an error when the script is executed outside of the extension environment. Typically, this wouldn' ...

Syntax of the Vue.js application object model

Just delving into the world of vue.js and stumbled upon this code snippet. Curious to know more about its structure. const CounterApp = { data() { return { counter: 0 } }, mounted() { setInterval(() => { this.counter++ ...

webpack-cli Configuration object is not valid

I have laravel 5.8 set up on my system and I am looking to integrate vue into it. I attempted to execute the following commands. I am using ubuntu, with node version 10.19. 1. npm install 2. npm run watch The first command executed successfully but displa ...