Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access to XMLHttpRequest has been blocked origin ASP.NET CORE 2.2.0 / Angular 8 / signalr1.0.0 [(CORS Policy-Access-Control-Allow-Origin) failed]

nugetPackage on .net core2.2.0:

signalr 1.0.0 + ASP.Core2.2.0

I'm using angular to connect use signalr:

package.json: "@aspnet/signalr": "1.1.0",

my angular front code:

import { Component } from '@angular/core';
import * as signalR from "@aspnet/signalr";


@Component({
    selector: 'app-root',
    templateUrl: './app.component.html'
})
export class AppComponent {
    constructor() { }


    private _hubConnection: signalR.HubConnection;
    msgs: Message[] = [];


    ngOnInit(): void {
        this._hubConnection = new signalR.HubConnectionBuilder()
            .withUrl('http://localhost:44390/chatHub')
            .build();
        this._hubConnection
            .start()
            .then(() => console.log('Connection started!'))
            .catch(err => console.log('Error while establishing connection :('));

        this._hubConnection.on('BroadcastMessage', (type: string, payload: string) => {
            this.msgs.push({ Type: type, Payload: payload });
        });
    }
}

export class Message {

    public Type: string
    public Payload: string
}       .catch(err => console.log('Error while establishing connection :('));

        this._hubConnection.on('BroadcastMessage', (type: string, payload: string) => {
            this.msgs.push({ Type: type, Payload: payload });
        });
    }

}

export class Message {

    public Type: string
    public Payload: string
}

my hub class:

using Microsoft.AspNetCore.SignalR; 
using System.Threading.Tasks;

namespace SharAPI.Models
{
    public class ChatHub : Hub 
    {
        public async Task BroadcastMessage(string msg)
        {
            await this.Clients.All.SendAsync("BroadcastMessage", msg);
        }
    }
}

startup.cs (ConfigureServices):

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
    {
        builder.AllowAnyOrigin()
               .AllowAnyMethod()
               .AllowAnyHeader();
    }));
    services.AddSignalR();
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

    // other codes
}

startup.cs (Configure):

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseResponseCompression();

    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
        app.UseHsts();
    }

    app.UseHttpsRedirection();
    app.UseSignalR(routes =>
    {
        routes.MapHub<ChatHub>("/chatHub");

    });
    app.UseCors(options => options.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod());

    app.UseMvc();

    //other codes
}

controller:

using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SignalR;
using SharAPI.Models;
using System;

namespace SharAPI.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    [EnableCors("MyPolicy")]

    public class MessageController : ControllerBase
    {
        private ChatHub _hub;
        public MessageController(ChatHub hub)
        {
            _hub  = hub ;
        }
        [HttpPost]
        public string Post([FromBody]Message msg)
        {
            string retMessage = string.Empty;
            try
            {
               _hub. BroadcastMessage(msg.message);
                retMessage = "Success";
            }
            catch (Exception e)
            {
                retMessage = e.ToString();
            }
            return retMessage;
        }
    }
}

and i get the error of:

Access to XMLHttpRequest at 'https://localhost:44390/chatHub/negotiate' from origin 'http://localhost:44390' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute

here is the pic

like image 713
Salar Kazazi Avatar asked Mar 04 '23 00:03

Salar Kazazi


2 Answers

You should add your CORS like this:

services.AddCors(options =>
{
    options.AddPolicy("CorsPolicy", builder => builder.WithOrigins("http://localhost:4200")
        .AllowAnyHeader()
        .AllowAnyMethod()
        .AllowCredentials()
        .SetIsOriginAllowed((host) => true));
});

Note:

The order is important!

like image 168
Kiril1512 Avatar answered Mar 05 '23 17:03

Kiril1512


You should apply your policy in Configure method:

public void Configure 
{
    app.UseResponseCompression();

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            // The default HSTS value is 30 days. You may want to change this 
            // for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }
    app.UseCors("MyPolicy");
}

UPDATE:

If you are using localhost as http://localhost:4200, then try to set it in your configuration:

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(options => options.AddPolicy("ApiCorsPolicy", build =>
    {                
        build.WithOrigins("http://localhost:4200")
             .AllowAnyMethod()
             .AllowAnyHeader();
        }));
        // ... other code is omitted for the brevity
     }
}

And Configure method:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    app.UseCors("ApiCorsPolicy");
    app.UseHttpsRedirection();        
    app.UseMvc();
}
like image 23
StepUp Avatar answered Mar 05 '23 17:03

StepUp