XMLHttpRequest error in .Net core 3.0 and angulr8,Access to XMLHttpRequest at url from from origin 'https://. has been blocked by CORS policy

130 views Asked by At

I am trying to call SignIn in angular.

  Login(reqobj: { RedirectUrl: string; }) {
var Url = this.GeturlFromServerName(this.baseUrl) + "Account/SignIn";this.baseUrl+reqobj.RedirectUrl;
return this.http.get(Url, {
  headers: {
    'Content-Type': 'application/json;charset=UTF-8',
    'Accept': 'application/json; charset=utf-8',
    "Access-Control-Allow-Origin": "*"        
  } })

}

Controller

    [EnableCors("CorsPolicy")]
    [AllowAnonymous]
    [HttpGet, Route("SignIn")]
    public async Task SignIn(string redirectUri)
    {
        if (!HttpContext.User.Identity.IsAuthenticated)
        {
            try
            {
                await HttpContext.ChallengeAsync(OpenIdConnectDefaults.AuthenticationScheme, new AuthenticationProperties() { RedirectUri = redirectUri });
            }
            catch (Exception e)
            {
                _loggWriter.LogError("Login Exception :", e);
            }
        }
    }

Startup.cs

services.AddAuthentication(options =>
        {
            options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
            options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        })
            .AddCookie()
            .AddOpenIdConnect(o =>
            {
                o.ClientId = clientId;
                o.ResponseType = "id_token";
                o.GetClaimsFromUserInfoEndpoint = true;

                o.MetadataAddress = metadataAddress;
                o.SignedOutRedirectUri = PostLogoutRedirectUri;

                o.Events = new OpenIdConnectEvents
                {
                    OnRemoteFailure = OnAuthenticationFailed
                };

            });

        services.AddAuthorization();

        services.AddCors(options =>
        {
            options.AddPolicy("CorsPolicy",
                builder => builder.WithOrigins("https://localhost:44381", "https://sts.xxxxxx.com")
            .AllowAnyHeader()
            .AllowAnyMethod()
            .AllowCredentials());
        });


        private Task OnAuthenticationFailed(RemoteFailureContext arg)
    {
        arg.HandleResponse();
        arg.Response.Redirect("/?errormessage=" + arg.Failure.Message);
        return Task.FromResult(0);
    }

public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseHttpsRedirection();

        app.UseRouting();

        app.UseFileServer();
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Error");
        }

        app.UseStaticFiles();
        if (!env.IsDevelopment())
        {
            app.UseSpaStaticFiles();
        }
        app.UseCors("CorsPolicy");
        app.UseAuthentication();
        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });

        app.UseSpa(spa =>
        {
            spa.Options.SourcePath = "ClientApp";
            if (env.IsDevelopment())
                         spa.UseAngularCliServer(npmScript: "start");
        });

}

Getting Error Some thing like this Access to XMLHttpRequest at 'https://.. from origin 'https://localhost:44381' 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

0

There are 0 answers