Search code examples
swiftwebsocketstarscream

How to authenticate user using Starscream


I am stuck in user authentications; i want to authenticate user via username and password.

I did successfully connect via websocket but i don't know how to authenticate user i try lot of research over google but still i can't achieved my goal due to less number of work done on that.

The server API i want to request via JSON:

{ “UserName”: “UserName”, “Password”: “Password” } 

and after request the server response is also JSON can some one please help me to achieve this. I am very thankful.

Basically i am new in WebSocket in Swift 4 that's why i am facing lot of issues on that i just used cocoapods of Starcream.

Thanks in advance.


Solution

  • Here is sample of Basic authentication with Starscream:

    //Prepare autorization data
        let authString: String = "\(userName):\(password)"        
        let base64String = authString.data(using: String.Encoding.utf8)!.base64EncodedString()
    
        // Prepare request and set headears for Basic Authorization
        var request = URLRequest(url: URL(string: SERVER_URL)!)
        request.setValue("Basic \(base64String)", forHTTPHeaderField: "Authorization")
    
        //Initiate websocket
        socket = WebSocket(request: request)
        socket?.advancedDelegate = self
        socket?.connect()
    

    If you got "invalid http upgrade" as result, just make sure you providing correct username and password.