1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

Error "When allowCredentials is true" with allowCredentials is false

Discussão em 'Angular' iniciado por Matheus Castilho, Maio 24, 2025.

  1. I have an application with a websocket connection, but when I test it with the wscat tool I get a return saying "connection received [connection_id]" but when I try to make the connection through the frontend I get the following error in the terminal "java.lang.IllegalArgumentException: When allowCredentials is true, allowedOrigins cannot contain the special value "*" since that cannot be set on the "Access-Control-Allow-Origin" response header. To allow credentials to a set of origins, list them explicitly or consider using "allowedOriginPatterns" instead. " but I'm not using "setAllowCredentials(true)" in my configuration I'm using "configuration.setAllowCredentials(false);" I will provide the prints and information of the following codes.

    Fisrt, my CorsConfig class


    package com.pixpro.upload.core.config;

    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.cors.CorsConfiguration;
    import org.springframework.web.cors.CorsConfigurationSource;
    import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

    import java.util.List;

    @Configuration
    public class CorsConfig {

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
    CorsConfiguration configuration = new CorsConfiguration();
    configuration.setAllowCredentials(false);
    configuration.addAllowedOriginPattern("*");
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", configuration);

    return source;
    }
    }


    Now, my UploadSocketHandler

    package com.pixpro.upload.core.websocket;

    import org.springframework.stereotype.Component;
    import org.springframework.web.socket.TextMessage;
    import org.springframework.web.socket.WebSocketSession;
    import org.springframework.web.socket.handler.TextWebSocketHandler;

    import java.io.IOException;

    @Component
    public class UploadSocketHandler extends TextWebSocketHandler {
    public void notifyProcessingComplete(WebSocketSession session, String fileName) throws IOException {
    session.sendMessage(new TextMessage("Imagem " + fileName + " processada com sucesso!"));
    }
    }


    And tha last one backend class, my WebSocketConfig

    package com.pixpro.upload.core.websocket;

    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.socket.config.annotation.EnableWebSocket;
    import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
    import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;

    @Configuration
    @EnableWebSocket
    public class WebSocketConfig implements WebSocketConfigurer {

    private final UploadSocketHandler uploadSocketHandler;

    public WebSocketConfig(UploadSocketHandler uploadSocketHandler) {
    this.uploadSocketHandler = uploadSocketHandler;
    }

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
    registry.addHandler(uploadSocketHandler, "/ws/upload")
    .setAllowedOrigins("*");
    }
    }


    In My angular, the code it is

    import { Injectable, Inject, PLATFORM_ID } from '@angular/core';
    import { isPlatformBrowser } from '@angular/common';
    import { Observable, EMPTY } from 'rxjs';
    import { webSocket, WebSocketSubject } from 'rxjs/webSocket';

    @Injectable({ providedIn: 'root' })
    export class UploadSocketService {
    private socket$!: WebSocketSubject<any>;

    constructor(@Inject(PLATFORM_ID) private platformId: Object) {}

    connect(): Observable<any> {
    if (!isPlatformBrowser(this.platformId)) {
    console.warn('[WebSocket] Ignorado: ambiente SSR');
    return EMPTY;
    }

    if (!this.socket$ || this.socket$.closed) {
    this.socket$ = webSocket({
    url: 'ws://localhost:8080/ws/upload',
    openObserver: {
    next: () => console.log('[WebSocket] ✅ Conectado ao servidor')
    },
    closeObserver: {
    next: (event: any) => {
    console.warn('[WebSocket] ❌ Conexão encerrada', {
    code: event?.code,
    reason: event?.reason || 'Sem motivo informado',
    wasClean: event?.wasClean
    });
    }
    }
    });


    this.socket$.subscribe({
    next: msg => console.log('[WebSocket] Mensagem recebida:', msg),
    error: err => {
    console.error('[WebSocket] ❗ Erro de conexão:', err);
    if (err && typeof err.code === 'number') {
    console.error(`[WebSocket] Código: ${err.code}, Motivo: ${err.reason || 'Desconhecido'}`);
    }
    }
    });
    }

    return this.socket$.asObservable();
    }

    disconnect() {
    if (this.socket$) {
    console.log('[WebSocket] Desconectando...');
    this.socket$.complete();
    }
    }
    }


    But, in my opinion, the problem is only in the backend...

    Here's the terminal output print [​IMG]

    Continue reading...

Compartilhe esta Página