Annotation based security restriction does not work for web socket triggered method calls

263 Views Asked by At

I did some research on this, but I couldn't find the solution.

I have a class like this

@Stateless
class ConfigBean {
  @RequiresRole("administrator")
  public void reloadConfiguration(){
     ......
  }
}

and I have a JAX-RS (jersey) service as below.

@Path("config")
class ConfigService{

  @EJB
  ConfigBean config;

  @Get
  @Path("reload")
  public void reload(){ 
     config.reloadConfiguration();
  }
}

This will work properly on calling API /Test/config/relaod (i.e only work with administrator user).

But the below code does not work as expected (i.e Normal user can trigger the reload config method),

@ServerEndpoint("/socket") 
public class EchoServer {
/**
 * @OnOpen allows us to intercept the creation of a new session.
 * The session class allows us to send data to the user.
 * In the method onOpen, we'll let the user know that the handshake was 
 * successful.
 */

@EJB
ConfigBean config;

@OnOpen
public void onOpen(Session session){
    System.out.println(session.getId() + " has opened a connection"); 
    try {
        session.getBasicRemote().sendText("Connection Established");
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

/**
 * When a user sends a message to the server, this method will intercept the message
 * and allow us to react to it. For now the message is read as a String.
 */
@OnMessage
public void onMessage(String message, Session session){
    System.out.println("Message from " + session.getId() + ": " + message);
    try {
        if(message.equalsIgnoreCase("reloadConfig")){
           config.reloadConfiguration();
        }
    } catch (IOException ex) {
        ex.printStackTrace();
    }
 }

/**
 * The user closes the connection.
 * 
 * Note: you can't send messages to the client from this method
 */
@OnClose
public void onClose(Session session){
    System.out.println("Session " +session.getId()+" has ended");
   }
}
1

There are 1 best solutions below

1
On

The Shiro JAX-RS integration only intercepts JAX-RS endpoints.

For a more general approach to annotations, you could use the Guice, Spring, or AspectJ integrations.

If you are using CDI, you can take a look at this branch for a Shiro Annotation Interceptor, it it is just a first pass, but it was working