Search code examples
azureazure-active-directoryblazorwebassemblyazure-appservice

BLAZOR, ASPCORE 5 and AzureAPP: has been blocked by CORS policy


I have a problem and i dont know how to solve. I use blazor, with AzureAD and azure Service ( I can loggin) but the problem is to access the data of the database that is in azureBD. I dont know why the redirection. I try a lot of code :( maybe something that i missing??

ERROR:

Access to fetch at 'https://login.microsoftonline.com/12acee71-6c99-48a3-9ff7-02fc9a24288a/oauth2/v2.0/authorize?client_id=5153b62a-311b-4c00-a0d0-at-ver=6.7.1.0' (redirected from 'https://rims.rafint.com/api/TblTeamStdRoles') from origin 'https://rims.rafint.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

Failed to load resource: net::ERR_FAILED

startup.cs:

services.AddDbContext<RIMS_Copy24apr21Context>(options =>
                options.UseSqlServer(
                    Configuration.GetConnectionString("DbContext")));

            services.AddTransient <Rafint_RIMSService> ();
            services.AddHttpClient();

            services.AddOptions();

            string[] initialScopes = Configuration.GetValue<string>(
                "Rafint-RIMS:ScopeForAccessToken")?.Split(' ');

            services.AddMicrosoftIdentityWebAppAuthentication(Configuration)
                .EnableTokenAcquisitionToCallDownstreamApi(initialScopes)
                .AddInMemoryTokenCaches();

            services.AddCors(options =>
            {
                options.AddDefaultPolicy(builder =>
                builder.WithOrigins("https://rims.rafint.com" , "https://rims.rafint.com/api/TblTeamStdRoles",
                "api://5153b62a-311b-4c00-a0d0-a896b0cdc908/TblTeamStdRoles.read")
                       .AllowAnyMethod()
                       .AllowAnyHeader());
            });

            services.AddControllersWithViews();
            services.AddRazorPages().AddMvcOptions(options =>
            {
                var policy = new AuthorizationPolicyBuilder()
                    .RequireAuthenticatedUser()
                    .Build();
                options.Filters.Add(new AuthorizeFilter(policy));
            }).AddMicrosoftIdentityUI();

        }
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseWebAssemblyDebugging();
            }
            else
            {
                app.UseExceptionHandler("/Error");
            }
            app.UseBlazorFrameworkFiles();
            app.UseStaticFiles();

            app.UseRouting();
            app.UseCors();
            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapRazorPages();
                endpoints.MapControllers();
                endpoints.MapFallbackToFile("index.html");
            });       

Problem

Program.CS I need to access to the DataBase!!


Solution

  • As far as I know, the issue lies in the below code snippet,

    services.AddCors(options =>  
    {  
    options.AddDefaultPolicy(builder =>  
    builder.WithOrigins("https://rims.rafint.com"  , "[https://rims.rafint.com/api/TblTeamStdRoles"](https://rims.rafint.com/api/TblTeamStdRoles%22 "https://rims.rafint.com/api/tblteamstdroles%22"),  
    "api://5153b62a-311b-4c00-a0d0-a896b0cdc908/TblTeamStdRoles.read")  
    .AllowAnyMethod()  
    .AllowAnyHeader());  
    });  
    

    To resolve the issue, please try with the following workarounds,

    • Try adding https:// for "api://5153b62a-311b-4c00-a0d0-a896b0cdc908/TblTeamStdRoles.read"
    • Otherwise, try including only two links("https://rims.rafint.com" , "https://rims.rafint.com/api/TblTeamStdRoles") in builder.WithOrigins
    • If it still occurs, make use of AllowAnyOrigin as below,
    Services.AddCors(options =>  
    {  
    options.AddDefaultPolicy(  
    builder =>  
    {  
    builder.AllowAnyOrigin()  
    .AllowAnyMethod()  
    .AllowAnyHeader()  
    .AllowCredentials();  
    });  
    });  
    

    Please find below references if they are helpful.

    References:

    Ref1 , Ref2 , Ref3