Hello,
I am using a socket that authorizes user via session cookie. How can I add a cookie to web socket connection? Thank you very much!
I'm also interested in knowing the answer to this question.
Hello!
I found solution of this problem. You can use the extension below. But first let me explain what I did. I create a session by login action and cookie that came from server is stored automatically in application like browser cookies. Then you can get that cookie and set it as a header for the socket connection.
I hope it will be beneficial for you! :-)
import Foundation
import Starscream
extension WebSocket {
static func getSocket() -> WebSocket{
var cookie = HTTPCookie()
if let cookies = URLSession.shared.configuration.httpCookieStorage?.cookies {
cookie = cookies[0]
}
var request = URLRequest(url: URL(string: "ws://\(String.getServerIp()):\(String.getApiPort())/api/socket")!)
request.setValue("\(cookie.name)=\(cookie.value)", forHTTPHeaderField: "Cookie")
let socket = WebSocket(request: request)
return socket
}
}
import UIKit
import Starscream
class SocketViewController: UIViewController {
override func viewDidLoad() {
let socket = WebSocket.getSocket()
socket.connect()
}
}
Most helpful comment
Hello!
I found solution of this problem. You can use the extension below. But first let me explain what I did. I create a session by login action and cookie that came from server is stored automatically in application like browser cookies. Then you can get that cookie and set it as a header for the socket connection.
I hope it will be beneficial for you! :-)