B4J Question WebsocketClient Authorization

Blueforcer

Well-Known Member
Licensed User
Longtime User
I need to send a API key to connect to a Websocket server. As i read i need to set a header

org.eclipse.jetty.websocket.api.UpgradeException: 401 Unauthorized
Caused by: org.eclipse.jetty.client.HttpResponseException: HTTP protocol violation: Authentication challenge without WWW-Authenticate header

with a websocketclient on the esp8266 i need to call webSocket.setAuthorization("apikey", MyApiKey);

how can i do this with the B4J Library?
 
Last edited:

Erel

B4X founder
Staff member
Licensed User
Longtime User
1. You need to find out which authentication method is expected.

2. Update the library with the attached one (1.11). This is an internal library.

Make the request like this:
B4X:
Dim UpgradeRequest As JavaObject
UpgradeRequest.InitializeNewInstance("org.eclipse.jetty.websocket.client.ClientUpgradeRequest", Null)
UpgradeRequest.RunMethod("setHeader", Array("key", "value"))
ws.Connect2(Url, UpgradeRequest)

The header key and value depend on the authentication method.
 

Attachments

  • jWebSocketClient.zip
    5.8 KB · Views: 237
Last edited:
Upvote 0

woniol

Active Member
Licensed User
Longtime User
I connect to jServer. Here I have AuthenticationFilter:
B4X:
srvr.AddFilter("/*", "BasicAuthenticationFilter", False)

with the following code:
B4X:
'Return True to allow the request to proceed.
Public Sub Filter(req As ServletRequest, resp As ServletResponse) As Boolean
    If req.GetSession.GetAttribute2("logged in", False) = True Then Return True
    If req.RequestURI="/ws" Then
        Return True
    Else
        Dim auths As List = req.GetHeaders("Authorization")
        If auths.Size = 0 Then
            resp.SetHeader("WWW-Authenticate", $"Basic realm="Realm""$)
            resp.SendError(401, "authentication required")
            Return False
        Else
            If CheckCredentials(auths.Get(0)) Then
                req.GetSession.SetAttribute("logged in", True)
                Return True
            Else
                resp.SendError(401, "authentication required")
                Return False
            End If
        End If
    End If
End Sub

It works fine for standard http/https but not for websocket.
Headers are used here.
 
Upvote 0

woniol

Active Member
Licensed User
Longtime User
It works perfect. With a few lines of code we have Basic authentication:
B4X:
Dim cred As String
cred = username&":"&pass
Dim su As StringUtils
Dim encoded As String
encoded = su.EncodeBase64(cred.GetBytes("UTF8")) 'data is a bytes array

ws.Headers = CreateMap("Authorization":"Basic "&encoded)
ws.Connect(Url)

Thanks
 
Upvote 0
Top