Nithin B
Nithin B

Reputation: 680

How Quarkus @ApplicationScoped bean's injected dependency has different value every time

I have below WebSocket bean class. I have injected JsonWebToken in this bean class and have a global property called clientIdGlobal. OnOpen I am picking clientId from token and assigning it to clientIdGlobal property.

package sample.sockettest;

import io.quarkus.security.Authenticated;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import jakarta.websocket.*;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import org.eclipse.microprofile.jwt.JsonWebToken;

@ServerEndpoint(
        value = "/api/v1/samplesocket/"
)
@ApplicationScoped
@Authenticated
public class WebSocket {
    @Inject
    JsonWebToken jsonWebToken;

    String clientIdGlobal = "";

    @OnOpen
    public void onOpen(Session session) {
        String clientId = jsonWebToken.getClaim("client_id");
        clientIdGlobal = clientId; // Picking clientId form token and assigning to clientIdGlobal property.
    }

    @OnError
    public void onError(Session session, Throwable throwable) { 
        String clientId = jsonWebToken.getClaim("client_id");
        String x = clientIdGlobal; // last connected clientId always.
    }

    @OnMessage
    public void onMessage(Session session, String message) { 
        String clientId = jsonWebToken.getClaim("client_id");
        String x = clientIdGlobal; // last connected clientId always.
    }

    @OnClose
    public void onClose(Session session) { 
        String clientId = jsonWebToken.getClaim("client_id");
        String x = clientIdGlobal; // last connected clientId always.
    }
}

Expectation:

  1. There will be only one instance of WebSocket class.
  2. clientIdGlobal - Behaves as expected because there is only one instance and the data, we change in global property will persist in subsequent injects (I would not be using this global variable, used just for testing).
  3. jsonWebToken - Here I see token came is exactly belonging to the respective client not just in OnOpen but also in OnMessage. How is this token dynamically changing? I would not be surprised if it is injected into method but here inject is in class level which should ideally happen once at object creation right.

It would be great if someone explains how this is happening.

Upvotes: 0

Views: 107

Answers (1)

geoand
geoand

Reputation: 64059

As you are keeping request specific state in the WebSocket class (remember that @JsonWebToken is a @RequestScoped bean), you should make WebSocket @RequestScoped as well

Upvotes: 1

Related Questions