Starscream: Session cookie

Created on 7 Aug 2018  路  2Comments  路  Source: daltoniam/Starscream

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!

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! :-)

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()
    }
}

All 2 comments

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()
    }
}
Was this page helpful?
0 / 5 - 0 ratings

Related issues

adrian-niculescu picture adrian-niculescu  路  4Comments

gmosx picture gmosx  路  4Comments

francos picture francos  路  3Comments

haducloc picture haducloc  路  3Comments

LondonAtlas picture LondonAtlas  路  3Comments