skip to Main Content

I’m developing an ASP.NET Core application with a Vue.js frontend, and I’m trying to implement SignalR for real-time notifications. However, I’m encountering a CORS issue when attempting to connect to my SignalR hub. Below are the details of my setup and the errors I’m facing.

Project Setup

  • Frontend: Vue.js, configured with withCredentials: true to send cookies.
  • Backend: ASP.NET Core with JWT authentication, using HttpOnly cookies to store JWTs.

CORS Configuration

            services.AddCors(options =>
            {
                string[] origins = [.. SecretsManager.GetSecret("Cors:AllowedOrigins").Split(',')];

                options.AddPolicy("AllowSpecificOrigins",
                    b => b.WithOrigins(origins)
                    .AllowAnyHeader()
                    .AllowAnyMethod()
                    .AllowCredentials()
                );
            });

JWT Configuration

            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = true,
                    ValidateAudience = true,
                    ValidateIssuerSigningKey = true,
                    ValidateLifetime = true,
                    ValidIssuer = SecretsManager.GetSecret("Jwt:Issuer"),
                    ValidAudience = SecretsManager.GetSecret("Jwt:Audience"),
                    IssuerSigningKey = new SymmetricSecurityKey(
                        Encoding.UTF8.GetBytes(SecretsManager.GetSecret("Jwt:Key"))
                    )
                };

                options.Events = new JwtBearerEvents
                {
                    OnMessageReceived = ctx =>
                    {
                        ctx.Request.Cookies.TryGetValue("access_token", out var accessToken);
                        if (!string.IsNullOrEmpty(accessToken))
                        {
                            ctx.Token = accessToken;
                        }

                        return Task.CompletedTask;
                    }
                };
            });

            services.AddAuthorization();

SignalR Setup in Vue.js

    onMounted(() => {
    connection.value = new signalR.HubConnectionBuilder()
        .withUrl('http://localhost:5132/api/NotificationHub', {
            withCredentials: true
        })
        .build();

    connection.value.start()
        .then(() => console.log('SignalR Connected'))
        .catch(err => console.error('SignalR Connection Error: ', err));

NotificationHub.cs

    [HubEndpoint("api/NotificationHub")]
    [Authorize]
    public class NotificationHub : Hub
    {
        public override Task OnConnectedAsync()
        {
            return base.OnConnectedAsync();
        }

        public override Task OnDisconnectedAsync(Exception exception)
        {
            return base.OnDisconnectedAsync(exception);
        }
        public async Task SendMessage(string user, string message)
        {
            await Clients.Others.SendAsync("CreateMovie", user, message);
        }
    }

Error Details

    Access to fetch at 'http://localhost:5132/api/NotificationHub/negotiate?negotiateVersion=1' from origin 'http://localhost:5173' 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.
The preflight OPTIONS request returns a 401 Unauthorized response with a WWW-Authenticate: Bearer header.

If I remove Authorize attribute everything works fine and connection is established
but when I have [Authorize] Attribute on Hub class it fails the authorization.
but even it fails I can still access the userID for example in OnConnectedAsync of NotificationHub class.

I cannot pass the cookie from client side as well as it is httponly.

can anyone help me find the solution to use Authorize attribute on Hubs? and establish connection only if user is authorized?

thanks

2

Answers


  1. Chosen as BEST ANSWER

    the only stupidest problem was that I had written UseCors() after UseAuthentication() and UseAuthorization() methods and after I changed the order like this in config files everything was fixed. I almost waste 2 days for this problem. which was of course my fault.

        app.UseCors("AllowSpecificOrigins");
    
        app.UseAuthentication();
    
        app.UseAuthorization();
    

  2. You should use accessTokenFactory instead of withCredentials: true.

    Official Doc: Configure bearer authentication

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search