5

I want my Go application to authenticate with a website and then use the received cookie to access secure locations. The following curl examples illustrates exactly what I'm trying to do:

Authenticate with website via x-www-form-urlencoded and save cookie. Data is urlencoded automatically:

curl 'https://www.example.com/login' \
    --cookie-jar cookies.txt \
    --header 'Content-Type: application/x-www-form-urlencoded' \
    --data 'user=USER NAME&pass=PASS'

Now authentication cookie is saved in cookies.txt and I just send that to access a page that requires login:

curl 'https://www.example.com/profile' \
    --cookie cookies.txt

I don't want to store the cookie on disk in my application, only in memory so I can use it when required.

Does anyone have an example of how this can be achieved in Go?

John Smith
  • 381
  • 1
  • 5
  • 12
  • 5
    Yes, use an [http.CookieJar](http://golang.org/pkg/net/http/#CookieJar). See [What is the difference between cookie and cookiejar?](http://stackoverflow.com/questions/31270461/what-is-the-difference-between-cookie-and-cookiejar/31270794#31270794) – icza Apr 07 '17 at 05:30
  • Thanks. Nice and clear explanation. I return a pointer to `cookiejar.Jar` from my authentication function and use this with `http.Client` in another function. – John Smith Apr 07 '17 at 17:10

2 Answers2

0

For golang you can Add a cookie to a request you can also get cookies using this function after making a web request.

0

you will find that Golang's approach is much similar to the one in Java. make sure you are inside your login handler. you only set the cookie using the SetCoookie function

myCookie := http.Cookie{
    Name: "cookie Name",
    Value: "cookieValue",
  }

  http.SetCookie(w, &myCookie)

it is recommended for security reasons to add the httpOnly flag to your cookie.

httpOnly: true

this flag true has nothing to do with HTTPS/HTTP. it only means no scripts allowed, HTTP requests only, to prevent Cross-site scripting (XSS) attacks. you store the cookie from the client-side, then when required you call the cookie and you verify if it the right cookie and the right client u send it to. this approach can be done using:

cookie, err := r.Cookie("appointment")
checkErr(err)

now u decrypt the cookie. verify it. do whatever the hell u want with it. then return your response to the client if it is the right client or not. hope this kinda helps

Fath
  • 84
  • 7