locked
Swagger Web API Cors error RRS feed

  • Question

  • User-893002196 posted

    Hi All,

    I am using Client Credential Method.

    I having error:-

    (index):1 Access to fetch at 'https://login.microsoftonline.com/xxxxxxxxxxxx-xxxxxxxxx-xxxx-xxxx-xxxxxxxxxx/oauth2/token' from origin 'https://xxxx.azurewebsites.net' 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.

    May I know what wrong?

    Startup.cs

    services.AddCors(options =>
    {
    options.AddPolicy("SiteCorsPolicy", builder => builder
    .WithOrigins(
    "http://localhost:8080",
    "https://localhost:8080",
    "http://localhost:4200",
    "https://localhost:4200",
    "https://xxx.azurewebsites.net")
    .AllowAnyMethod()
    .AllowAnyHeader()
    .AllowCredentials());
    });

     services.AddSwaggerGen(c =>
                {
                    c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
                    c.AddSecurityDefinition("oauth2", new OAuth2Scheme
                    {
                        Type = "oauth2",
                        Flow = "application",
                        TokenUrl = $"https://login.microsoftonline.com/{Configuration["AzureAd:TenantId"]}/oauth2/token",
                        Scopes = new Dictionary<string, string>
                        {
                            { "user_impersonation", "Access XXX" }
                        }
                    });
     
                    c.AddSecurityRequirement(new Dictionary<string, IEnumerable<string>>
                    {
                        { "oauth2", new[] { "user_impersonation" } }
                    });
                });

    app.UseCors("SiteCorsPolicy");

    portal.azure.com >App Services > My Web API > Cors >[v  tick] Enable Access-Control-Allow-Credentials 

    Allowed Origin: I added:-

    https://xxx.azurewebsites.net

    Please advise. What's is the step missing.

    Thanks

    Regards,

    Micheale

    Wednesday, November 13, 2019 11:25 AM

Answers

  • User-474980206 posted

    its not your site you need to configure CORS, its the login site (https://login.microsoftonline.com ) that needs its CORS configuration to include your site. If you are not allowed to configure your AD, then you will need to do an application proxy to the login server.

     

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, November 14, 2019 10:40 PM

All replies

  • Wednesday, November 13, 2019 11:36 AM
  • User-893002196 posted

    Hi,

    No luck. Same error.

    Thanks.

    Regards,

    Micheale

    Wednesday, November 13, 2019 2:19 PM
  • User-474980206 posted

    CORS must be set by the website being accessed. The website

       https://login.microsoftonline.com/xxxxxxxxxxxx-xxxxxxxxx-xxxx-xxxx-xxxxxxxxxx/oauth2/token

    is the one not setting CORS.   

    Wednesday, November 13, 2019 3:10 PM
  • User-893002196 posted

    Hi,

    I had tried too, no work. Cors cannot added /….

    I only added https://login.microsoftonline.com and https://login.microsoftonline.com:443

    Still, no luck. :(

    Startup.cs

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Authentication;
    using Microsoft.AspNetCore.Authentication.AzureAD.UI;
    using Microsoft.AspNetCore.Authorization;
    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.AspNetCore.HttpsPolicy;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.AspNetCore.Mvc.Authorization;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.Extensions.Logging;
    using Microsoft.Extensions.Options;
    using Swashbuckle.AspNetCore.Swagger;
    using SwaggerSolution.Models;
    using Microsoft.EntityFrameworkCore;
    using Newtonsoft.Json;
    using Newtonsoft.Json.Serialization;
    using Microsoft.AspNetCore.Mvc.Cors.Internal;
    using Microsoft.Net.Http.Headers;
    
    namespace SwaggerSolution
    {
        public class Startup
        {
            public Startup(IConfiguration configuration)
            {
                Configuration = configuration;
            }
    
            public IConfiguration Configuration { get; }
          
            // This method gets called by the runtime. Use this method to add services to the container.
            public void ConfigureServices(IServiceCollection services)
            {
    
                services.Configure<CookiePolicyOptions>(options =>
                {
                    options.CheckConsentNeeded = context => false;
                    options.MinimumSameSitePolicy = Microsoft.AspNetCore.Http.SameSiteMode.None;
                });
    
               
                services.AddCors(options => options.AddPolicy("CorsPolicy",
                 builder =>
                 {
                     builder.AllowAnyMethod().AllowAnyHeader()
                            .AllowAnyOrigin()
                            .AllowAnyMethod()
                            .AllowAnyHeader()
                            .AllowCredentials();
                 }));
                
                services.AddSignalR();
    
                services.AddAuthentication(AzureADDefaults.JwtBearerAuthenticationScheme)
                    .AddAzureADBearer(options => Configuration.Bind("AzureAd", options));
                
                services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1).AddJsonOptions(options => {
                    options.SerializerSettings.DateFormatString = "yyyy-MM-ddTHH:mm:ssZ";
                    options.SerializerSettings.Formatting = Formatting.Indented;
                    options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
                    options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                });
    
                services.Configure<MvcOptions>(options =>
                {
                    options.Filters.Add(new CorsAuthorizationFilterFactory("CorsPolicy"));
                });
    
                services.AddDbContext<XXXXContext>(options => options.UseSqlServer(Configuration["AzureAd:DefaultConnection"]));
    
                services.AddSwaggerGen(c =>
                {
                    c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
                    c.AddSecurityDefinition("oauth2", new OAuth2Scheme
                    {
                        Type = "oauth2",
                        Flow = "application",
                        AuthorizationUrl = $"https://login.microsoftonline.com/{Configuration["AzureAd:TenantId"]}/oauth2//authorize?resource=xxxxxxx-xxxx-xxx-xxxx-xxxxxxxxxxxx",
                        TokenUrl = $"https://login.microsoftonline.com/{Configuration["AzureAd:TenantId"]}/oauth2/token?resource=xxxxxxx-xxxx-xxx-xxxx-xxxxxxxxxxxx",
                        Scopes = new Dictionary<string, string>
                        {
                            { "user_impersonation", "Access XXXX" }
                        }
                    });
    
                    c.AddSecurityRequirement(new Dictionary<string, IEnumerable<string>>
                    {
                        { "oauth2", new[] { "user_impersonation" } }
                    });
                });           
    
            }
    
            // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
            public void Configure(IApplicationBuilder app, IHostingEnvironment env)
            {
                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                }
                else
                {
                    app.UseHsts();
                }
                app.UseAuthentication();
                // Make sure you call this before calling app.UseMvc()
                app.UseCors(policy => 
                    policy.WithHeaders(HeaderNames.CacheControl)
                    .SetIsOriginAllowedToAllowWildcardSubdomains()
                    .AllowAnyOrigin()
                    .SetPreflightMaxAge(TimeSpan.FromDays(1))
                );
                app.UseCors("CorsPolicy");
    
                app.UseHttpsRedirection();
                
                app.UseMvc();
                app.UseSwagger();
                
                app.UseSwaggerUI(c =>
                {
                    c.OAuthClientId(Configuration["Client:ClientId"]);
                    c.OAuthClientSecret(Configuration["Client:ClientSecret"]);
                    c.OAuthRealm(Configuration["Client:ClientId"]);
                    c.OAuthAppName("My API V1");
                    c.OAuthScopeSeparator(" ");  
                    c.OAuthAdditionalQueryStringParams(new {
                        audience = Configuration["AzureAd:ClientId"] }
                    );
                    c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
                    c.OAuthUseBasicAuthenticationWithAccessCodeGrant();
                });
            }
        }
    }
    

    Response Header
    HTTP/1.1 200 OK
    Cache-Control: no-cache, no-store
    Pragma: no-cache
    Expires: -1
    Strict-Transport-Security: max-age=31536000; includeSubDomains
    X-Content-Type-Options: nosniff
    x-ms-request-id: 83443b3a-a3b7-4058-9c28-b222d3256e01
    x-ms-ests-server: 2.1.9645.7 - SIN1 ProdSlices
    Referrer-Policy: strict-origin-when-cross-origin
    P3P: CP="DSP CUR OTPi IND OTRi ONL FIN"
    Set-Cookie: fpc=Ajd3iMMCDTlPuv3v_iz4h-c; expires=Sat, 14-Dec-2019 04:58:14 GMT; path=/; secure; HttpOnly; SameSite=None
    Set-Cookie: x-ms-gateway-slice=prod; path=/; SameSite=None; secure; HttpOnly
    Set-Cookie: stsservicecookie=ests; path=/; SameSite=None; secure; HttpOnly
    Date: Thu, 14 Nov 2019 04:58:13 GMT
    Content-Length: 0

    Request Header
    Host: login.microsoftonline.com
    User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:69.0) Gecko/20100101 Firefox/69.0
    Accept: */*
    Accept-Language: en-US,en;q=0.5
    Accept-Encoding: gzip, deflate, br
    Access-Control-Request-Method: POST
    Access-Control-Request-Headers: authorization
    Referer: https://xxx.azurewebsites.net/swagger/
    Origin: https://xxx.azurewebsites.net
    Connection: keep-alive

    Thanks

    Regards,

    Micheale

    Wednesday, November 13, 2019 10:17 PM
  • User-474980206 posted

    its not your site you need to configure CORS, its the login site (https://login.microsoftonline.com ) that needs its CORS configuration to include your site. If you are not allowed to configure your AD, then you will need to do an application proxy to the login server.

     

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, November 14, 2019 10:40 PM
  • User-182430649 posted

    Try to use Implicit flow instead of other flows - Password and AuthorizationCode result in this CORS issue with https://login.microsoftonline.com

    Saturday, June 6, 2020 12:44 PM