Fish
Fish

Reputation: 67

Basic Authentication in play framework

How to implement Basic Authentication for web sockets using play framework.

I am creating a web socket using play framework. I would like to do basic authentication and send 401 if authentication fails. Below is my code and i am not able to send "{code=401, message=unauthorized access}" as response

def ChatServer(): WebSocket = WebSocket.accept[String, String] { request =>
    if (Util.doBasicAuthentication(request.headers)) {
      ActorFlow.actorRef { out =>
        ChatActor.props(out)
      }
    } else throw new RuntimeException("Unauthorized Access")
  }

Whenever authentication fails, i am not able to send the response back as "unauthorized access" instead i am ending up with exceptions

Upvotes: 1

Views: 347

Answers (1)

Jeffrey Chung
Jeffrey Chung

Reputation: 19517

As described in the Play documentation, use WebSocket.acceptOrResult:

def socket = WebSocket.acceptOrResult[String, String] { request =>
  Future.successful {
    if (Util.doBasicAuthentication(request.headers)) {
      Right(ActorFlow.actorRef { out =>
        ChatActor.props(out)
      })
    } else {
      Left(Unauthorized)
    }
  }
}

Upvotes: 0

Related Questions