B4J Question jServer authentication

woniol

Active Member
Licensed User
I'm creating web service using jServer. The clients connecting to this WS will use jOkHttp library.
I would like to set basic authentication for this connections.

I can set username and password on the client side, but how to set in on the server side?
 

Erel

Administrator
Staff member
Licensed User
Add this filter class named BasicAuthenticationFilter:
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
   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 Sub

Private Sub CheckCredentials (auth As String) As Boolean
   Dim success As Boolean = False
   If auth.StartsWith("Basic") = True Then
     Dim b64 As String = auth.SubString("Basic ".Length)
     Dim su As StringUtils
     Dim b() As Byte = su.DecodeBase64(b64)
     Dim raw As String = BytesToString(b, 0, b.Length, "utf8")
     Dim UsernameAndPassword() As String = Regex.Split(":", raw)
     If UsernameAndPassword.Length = 2 Then
       'up to you to decide which credentials are allowed <---------------------------
       If UsernameAndPassword(0) = "Username" And UsernameAndPassword(1) = "Password" Then
         success = True
       End If
     End If
   End If
   Return success
End Sub
Add this line to the main module:
B4X:
srvr.AddFilter("/*", "BasicAuthenticationFilter", False)
 
Top