func authzViaCookieValue(r *http.Request, tok string) int { r.AddCookie(&http.Cookie{ Name: "arvados_api_token", Value: auth.EncodeTokenCookie([]byte(tok)), }) return http.StatusUnauthorized }
func buildTestRequest(method string, path string, body string, headers map[string][]string, cookies []*http.Cookie) *http.Request { host := "127.0.0.1" port := "80" rawurl := "http://" + host + ":" + port + path url_, _ := url.Parse(rawurl) proto := "HTTP/1.1" if headers == nil { headers = map[string][]string{} } headers["User-Agent"] = []string{"web.go test"} if method == "POST" { headers["Content-Length"] = []string{fmt.Sprintf("%d", len(body))} if headers["Content-Type"] == nil { headers["Content-Type"] = []string{"text/plain"} } } req := http.Request{Method: method, URL: url_, Proto: proto, Host: host, Header: http.Header(headers), Body: ioutil.NopCloser(bytes.NewBufferString(body)), } for _, cookie := range cookies { req.AddCookie(cookie) } return &req }
func initRequest(req *http.Request, gr *GoReq) { for k, v := range gr.Header { req.Header.Set(k, v) } // Add all querystring from Query func q := req.URL.Query() for k, v := range gr.QueryData { for _, vv := range v { q.Add(k, vv) } } req.URL.RawQuery = q.Encode() // Add basic auth if gr.BasicAuth != (struct{ Username, Password string }{}) { req.SetBasicAuth(gr.BasicAuth.Username, gr.BasicAuth.Password) } // Add cookies for _, cookie := range gr.Cookies { req.AddCookie(cookie) } //check client if gr.Client == nil { gr.setDefaultClient() } if gr.CheckRedirect != nil { gr.Client.CheckRedirect = gr.CheckRedirect } // Set Transport gr.Client.Transport = gr.Transport }
func (m *MpWechat) AddCookies(req *http.Request) error { fi, err := os.Open(m.CookieFile) if err != nil { return err } defer fi.Close() f_bytes, read_err := ioutil.ReadAll(fi) if read_err != nil { return read_err } cookies := make([]*http.Cookie, 0) json_err := json.Unmarshal(f_bytes, &cookies) if json_err != nil { return json_err } for _, cookie := range cookies { //fmt.Println(cookie) req.AddCookie(cookie) } cookie := &http.Cookie{Name: "noticeLoginFlag", Value: "1"} req.AddCookie(cookie) return nil }
func (c *Client) addAuthentication(req *http.Request) error { // Apply HTTP Basic Authentication if c.Authentication.HasBasicAuth() { req.SetBasicAuth(c.Authentication.name, c.Authentication.secret) return nil } // Apply HTTP Cookie if c.Authentication.HasCookieAuth() { req.AddCookie(&http.Cookie{ Name: c.Authentication.name, Value: c.Authentication.secret, }) return nil } // Apply Digest Authentication. If we're using digest based // authentication we need to make a request, process the // WWW-Authenticate header, then set the Authorization header on the // incoming request. We do not need to send a body along because // the request itself should fail first. if c.Authentication.HasDigestAuth() { uri, err := c.buildURLForRequest(req.URL.RequestURI()) if err != nil { return err } // WARNING: Don't use c.NewRequest here unless you like // infinite recursion. digestRequest, err := http.NewRequest(req.Method, uri, nil) digestRequest.Header.Set("Accept", "*/*") digestRequest.Header.Set("Content-Type", "application/json") if err != nil { return err } response, err := c.client.Do(digestRequest) if err != nil { return err } // When the function exits discard the rest of the // body and close it. This should cause go to // reuse the connection. defer io.Copy(ioutil.Discard, response.Body) defer response.Body.Close() if response.StatusCode == http.StatusUnauthorized { authorization, err := c.Authentication.digestAuthHeader(response) if err != nil { return err } req.Header.Set("Authorization", authorization) } } return nil }
//get Session func (manager *Manager) SessionStart(w http.ResponseWriter, r *http.Request) (session SessionStore) { cookie, err := r.Cookie(manager.cookieName) if err != nil || cookie.Value == "" { sid := manager.sessionId(r) session, _ = manager.provider.SessionRead(sid) cookie = &http.Cookie{Name: manager.cookieName, Value: url.QueryEscape(sid), Path: "/", HttpOnly: true, Secure: manager.secure} if manager.maxage >= 0 { cookie.MaxAge = manager.maxage } //cookie.Expires = time.Now().Add(time.Duration(manager.maxlifetime) * time.Second) http.SetCookie(w, cookie) r.AddCookie(cookie) } else { //cookie.Expires = time.Now().Add(time.Duration(manager.maxlifetime) * time.Second) cookie.HttpOnly = true cookie.Path = "/" if manager.maxage >= 0 { cookie.MaxAge = manager.maxage http.SetCookie(w, cookie) } sid, _ := url.QueryUnescape(cookie.Value) session, _ = manager.provider.SessionRead(sid) } return }
func setUserSession(w http.ResponseWriter, r *http.Request, username string) { handler.SetCookie(w, r, "_sess", username) resp := http.Response{Header: w.Header()} for _, v := range resp.Cookies() { r.AddCookie(v) } }
func (manager *Manager) SessionRegenerateId(w http.ResponseWriter, r *http.Request) (session SessionStore) { sid := manager.sessionId(r) cookie, err := r.Cookie(manager.cookieName) if err != nil && cookie.Value == "" { //delete old cookie session, _ = manager.provider.SessionRead(sid) cookie = &http.Cookie{Name: manager.cookieName, Value: url.QueryEscape(sid), Path: "/", HttpOnly: true, Secure: manager.secure, } } else { oldsid, _ := url.QueryUnescape(cookie.Value) session, _ = manager.provider.SessionRegenerate(oldsid, sid) cookie.Value = url.QueryEscape(sid) cookie.HttpOnly = true cookie.Path = "/" } if manager.maxage >= 0 { cookie.MaxAge = manager.maxage } http.SetCookie(w, cookie) r.AddCookie(cookie) return }
func setAuth(request *http.Request) { if authConfig.Username != "" && authConfig.Password != "" { if authConfig.SimpleAuth { request.SetBasicAuth(authConfig.Username, authConfig.Password) } else { session := authenticate() layout := "2006-01-02T15:04:05Z07:00" expire, err := time.Parse(layout, session.Expires) if err != nil { logg.LogPanic("Error parsing time: %v", err) } rawCookie := []string{session.CookieName + "=" + session.SessionID} maxAge := 0 secure := true httpOnly := true path := "/" cookie := http.Cookie{session.CookieName, session.SessionID, path, config.SyncURL, expire, expire.Format(time.UnixDate), maxAge, secure, httpOnly, rawCookie[0], rawCookie} request.AddCookie(&cookie) } } }
func AddCookies(req *http.Request, cookie_file string) error { fi, err := os.Open(cookie_file) if err != nil { return err } defer fi.Close() f_bytes, read_err := ioutil.ReadAll(fi) if read_err != nil { return read_err } cookies := make([]*http.Cookie, 0) json_err := json.Unmarshal(f_bytes, &cookies) if json_err != nil { return json_err } for _, cookie := range cookies { //fmt.Println(cookie) req.AddCookie(cookie) } return nil }
func (s *SediAPI) doReq(req *http.Request) ([]byte, error) { count := 0 for { for _, cookie := range s.cookies { req.AddCookie(cookie) } client := &http.Client{} res, err := client.Do(req) if res == nil || err != nil { log.Println("SEDI response is: ", res, "; error is:", err, ". I will reconnect and will retrieve data again after 3s.") time.Sleep(3 * time.Second) count += 1 if count > MAX_TRY_COUNT { return []byte{}, errors.New(fmt.Sprintf("Max tryings count ended and request not proceed... %#v", req)) } continue } defer res.Body.Close() s.updateCookies(res.Cookies()) body, err := ioutil.ReadAll(res.Body) body = prepareResponse(body) return body, err } return []byte{}, errors.New(fmt.Sprintf("Error at do request... %#v", req)) }
func (c *RestClient) Do(req *http.Request) (mresp map[string]interface{}) { defer func() { if err := recover(); err != nil { log.Fatal(err) } }() req.Header.Set("Content-Type", "application/json") req.Header.Set("Accept-Language", "en-us") req.Header.Set("Accept-Encoding", "gzip, deflate") if c.cookie != nil { req.AddCookie(c.cookie.(*http.Cookie)) } resp, err := c.client.Do(req) if err != nil { log.Printf("%v", err) } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { log.Printf("%v", err) } json.Unmarshal(body, &mresp) return }
// NewSessionRequest issues any request with session / cookie and read the response. // If successful, the caller may examine the Response and ResponseBody properties. // NOTE: Session data will be added to the request cookies for you. func (test *Client) NewSessionRequest(t *testing.T, request *http.Request) { for _, cookie := range test.Client.Jar.Cookies(request.URL) { request.AddCookie(cookie) } test.NewRequest(t, request) }
// Regenerate a session id for this SessionStore who's id is saving in http request. func (manager *Manager) SessionRegenerateId(w http.ResponseWriter, r *http.Request) (session SessionStore) { sid, err := manager.sessionId(r) if err != nil { return } cookie, err := r.Cookie(manager.config.CookieName) if err != nil && cookie.Value == "" { //delete old cookie session, _ = manager.provider.SessionRead(sid) cookie = &http.Cookie{Name: manager.config.CookieName, Value: url.QueryEscape(sid), Path: "/", HttpOnly: true, Secure: manager.isSecure(r), Domain: manager.config.Domain, } } else { oldsid, _ := url.QueryUnescape(cookie.Value) session, _ = manager.provider.SessionRegenerate(oldsid, sid) cookie.Value = url.QueryEscape(sid) cookie.HttpOnly = true cookie.Path = "/" } if manager.config.CookieLifeTime > 0 { cookie.MaxAge = manager.config.CookieLifeTime cookie.Expires = time.Now().Add(time.Duration(manager.config.CookieLifeTime) * time.Second) } http.SetCookie(w, cookie) r.AddCookie(cookie) return }
// Regenerate a session id for this SessionStore who's id is saving in http request. func (manager *Manager) SessionRegenerateId(w http.ResponseWriter, r *http.Request) (session SessionStore) { var c = appengine.NewContext(r) sid, err := manager.sessionId(r) if err != nil { return } cookie, err := r.Cookie(manager.config.CookieName) if err != nil && cookie.Value == "" { //delete old cookie session, _ = manager.provider.SessionRead(sid, c) cookie = &http.Cookie{Name: manager.config.CookieName, Value: url.QueryEscape(sid), Path: "/", HttpOnly: true, Secure: manager.config.Secure, Domain: manager.config.Domain, } } else { oldsid, _ := url.QueryUnescape(cookie.Value) session, _ = manager.provider.SessionRegenerate(oldsid, sid, c) cookie.Value = url.QueryEscape(sid) cookie.HttpOnly = true cookie.Path = "/" } if manager.config.CookieLifeTime >= 0 { cookie.MaxAge = manager.config.CookieLifeTime } http.SetCookie(w, cookie) r.AddCookie(cookie) return }
//get Session func (manager *Manager) SessionStart(w http.ResponseWriter, r *http.Request) (session SessionStore) { cookie, err := r.Cookie(manager.cookieName) if err != nil || cookie.Value == "" { sid := manager.sessionId() session, _ = manager.provider.SessionRead(sid) secure := false if len(manager.options) > 0 { secure = manager.options[0].(bool) } cookie := http.Cookie{Name: manager.cookieName, Value: url.QueryEscape(sid), Path: "/", HttpOnly: true, Secure: secure} //cookie.Expires = time.Now().Add(time.Duration(manager.maxlifetime) * time.Second) http.SetCookie(w, &cookie) r.AddCookie(&cookie) } else { //cookie.Expires = time.Now().Add(time.Duration(manager.maxlifetime) * time.Second) cookie.HttpOnly = true cookie.Path = "/" http.SetCookie(w, cookie) sid, _ := url.QueryUnescape(cookie.Value) session, _ = manager.provider.SessionRead(sid) } return }
// Start session. generate or read the session id from http request. // if session id exists, return SessionStore with this id. func (manager *Manager) SessionStart(w http.ResponseWriter, r *http.Request) (session SessionStore, err error) { var c = appengine.NewContext(r) cookie, errs := r.Cookie(manager.config.CookieName) if errs != nil || cookie.Value == "" { sid, errs := manager.sessionId(r) if errs != nil { return nil, errs } session, err = manager.provider.SessionRead(c, sid) cookie = &http.Cookie{ Name: manager.config.CookieName, Value: url.QueryEscape(sid), Path: "/", HttpOnly: true, Secure: manager.isSecure(r), Domain: manager.config.Domain, } if manager.config.CookieLifeTime > 0 { cookie.MaxAge = manager.config.CookieLifeTime cookie.Expires = time.Now().Add(time.Duration(manager.config.CookieLifeTime) * time.Second) } if manager.config.EnableSetCookie { http.SetCookie(w, cookie) } r.AddCookie(cookie) } else { sid, errs := url.QueryUnescape(cookie.Value) if errs != nil { return nil, errs } if manager.provider.SessionExist(c, sid) { session, err = manager.provider.SessionRead(c, sid) } else { sid, err = manager.sessionId(r) if err != nil { return nil, err } session, err = manager.provider.SessionRead(c, sid) cookie = &http.Cookie{ Name: manager.config.CookieName, Value: url.QueryEscape(sid), Path: "/", HttpOnly: true, Secure: manager.isSecure(r), Domain: manager.config.Domain, } if manager.config.CookieLifeTime > 0 { cookie.MaxAge = manager.config.CookieLifeTime cookie.Expires = time.Now().Add(time.Duration(manager.config.CookieLifeTime) * time.Second) } if manager.config.EnableSetCookie { http.SetCookie(w, cookie) } r.AddCookie(cookie) } } return }
func addAuthentication(req *http.Request) { if req != nil { req.AddCookie(&http.Cookie{ Name: models.UISecretCookie, Value: config.UISecret(), }) } }
func (self *session) stamp(req *http.Request) { if self.session != "" { req.AddCookie(&http.Cookie{ Name: "api_key", Value: self.session, }) } }
func addAuthentication(req *http.Request) { if req != nil { req.AddCookie(&http.Cookie{ Name: models.UISecretCookie, // TODO read secret from config Value: os.Getenv("UI_SECRET"), }) } }
func (this *SessionFactory) SessionStart(r *http.Request, w http.ResponseWriter) (session SessionInstance, errRtn error) { cookie, err := r.Cookie(this.config.CookieKey) if err != nil || cookie.Value == "" { sessionId, err := this.sessionId() if err != nil { session = nil errRtn = err return } session, errRtn = this.provider.SessionRead(sessionId) cookie := &http.Cookie{ Name: this.config.CookieKey, Value: url.QueryEscape(sessionId), Path: "/", HttpOnly: true, Domain: this.config.Domain, } if this.config.CookieLifeTime > 0 { cookie.MaxAge = this.config.CookieLifeTime cookie.Expires = time.Now().Add(time.Duration(this.config.CookieLifeTime) * time.Second) } http.SetCookie(w, cookie) r.AddCookie(cookie) } else { sessionId, err := url.QueryUnescape(cookie.Value) if err != nil { session = nil errRtn = err return } if this.provider.SessionExist(sessionId) { session, err = this.provider.SessionRead(sessionId) } else { sessionId, err := this.sessionId() if err != nil { session = nil errRtn = err return } session, errRtn = this.provider.SessionRead(sessionId) cookie := &http.Cookie{ Name: this.config.CookieKey, Value: url.QueryEscape(sessionId), Path: "/", HttpOnly: true, Domain: this.config.Domain, } if this.config.CookieLifeTime > 0 { cookie.MaxAge = this.config.CookieLifeTime cookie.Expires = time.Now().Add(time.Duration(this.config.CookieLifeTime) * time.Second) } http.SetCookie(w, cookie) r.AddCookie(cookie) } } return }
func addCookie(req *http.Request, sessionID string) { cookie := &http.Cookie{ Name: "JSESSIONID", Value: sessionID, Domain: "www.tropo.com", Path: "/", } req.AddCookie(cookie) }
// MergeRequest merge the request field in scan with the existing one. func (s *Scan) MergeRequest(req *http.Request) { // set cookie from response (if it is not done..) if s.Response != nil { s.Cookies = append(s.Cookies, s.Response.Cookies()...) // s.CookieJar.SetCookies(s.Request.URL, s.Response.Cookies()) } // read the request body, and then reset the reader var post []byte if req.Body != nil { if post, err := ioutil.ReadAll(req.Body); err == nil { req.Body = ioutil.NopCloser(bytes.NewReader(post)) } else { // only possible error is bytes.ErrTooLarge from ioutil package. s.Error("MergeRequest", err) } } // resolve relative url. if !req.URL.IsAbs() { req.URL = s.Request.URL.ResolveReference(req.URL) } // TODO - drop if Method, URL, Body are same.. if req == s.Request { // s.Logf("Result after merge generate same request.", nil) } // swap prevReq := s.Request s.Request = req s.RequestBody = string(post) // TODO - handle relative URL . // Create a cookie jar, add cookie list (so cookie jar reject invalid cookie.) jar, _ := cookiejar.New(nil) jar.SetCookies(req.URL, s.Cookies) // reset cookies s.Cookies = make([]*http.Cookie, 0) for _, c := range jar.Cookies(req.URL) { req.AddCookie(c) s.Cookies = append(s.Cookies, c) } // Add user agent req.Header.Set("User-Agent", prevReq.UserAgent()) // Add referrer - TODO, perhaps we don't need this! // remove Response. s.Response = nil s.ResponseBody = "" }
//get Session func (manager *Manager) SessionStart(w http.ResponseWriter, r *http.Request) (session SessionStore) { cookie, err := r.Cookie(manager.cookieName) maxage := -1 if len(manager.options) > 3 { switch manager.options[3].(type) { case int: if manager.options[3].(int) > 0 { maxage = manager.options[3].(int) } else if manager.options[3].(int) < 0 { maxage = 0 } case int64: if manager.options[3].(int64) > 0 { maxage = int(manager.options[3].(int64)) } else if manager.options[3].(int64) < 0 { maxage = 0 } case int32: if manager.options[3].(int32) > 0 { maxage = int(manager.options[3].(int32)) } else if manager.options[3].(int32) < 0 { maxage = 0 } } } if err != nil || cookie.Value == "" { sid := manager.sessionId(r) session, _ = manager.provider.SessionRead(sid) secure := false if len(manager.options) > 0 { secure = manager.options[0].(bool) } cookie = &http.Cookie{Name: manager.cookieName, Value: url.QueryEscape(sid), Path: "/", HttpOnly: true, Secure: secure} if maxage >= 0 { cookie.MaxAge = maxage } //cookie.Expires = time.Now().Add(time.Duration(manager.maxlifetime) * time.Second) http.SetCookie(w, cookie) r.AddCookie(cookie) } else { //cookie.Expires = time.Now().Add(time.Duration(manager.maxlifetime) * time.Second) cookie.HttpOnly = true cookie.Path = "/" if maxage >= 0 { cookie.MaxAge = maxage } http.SetCookie(w, cookie) sid, _ := url.QueryUnescape(cookie.Value) session, _ = manager.provider.SessionRead(sid) } return }
func SetAuthCookie(request *http.Request, user_id string, token_id string) error { cookie_userid := &http.Cookie{Name: settings.USERID_COOKIE_FIELD_NAME, Value: user_id, Path: "/", Domain: settings.RESTAPI_SERVER_ADDR} cookie_token := &http.Cookie{Name: settings.TOKEN_COOKIE_FIELD_NAME, Value: token_id, Path: "/", Domain: settings.RESTAPI_SERVER_ADDR} request.AddCookie(cookie_token) request.AddCookie(cookie_userid) // func (r *Request) AddCookie(c *Cookie) { return nil }
// 設定 cookie 內容。 func (s *Service) SetCookie(req *http.Request) { if req == nil { return } c := &http.Cookie{ Name: "loginkuser", Value: s.Key, } req.AddCookie(c) }
func addCookies(req *http.Request) error { cookies, err := parseCookies() if err != nil { return err } for _, c := range cookies { req.AddCookie(c) } return nil }
func (manager *Manager) SessionRegenerateId(w http.ResponseWriter, r *http.Request) (session SessionStore) { sid := manager.sessionId(r) cookie, err := r.Cookie(manager.cookieName) if err != nil && cookie.Value == "" { //delete old cookie session, _ = manager.provider.SessionRead(sid) secure := false if len(manager.options) > 0 { secure = manager.options[0].(bool) } cookie = &http.Cookie{Name: manager.cookieName, Value: url.QueryEscape(sid), Path: "/", HttpOnly: true, Secure: secure, } } else { oldsid, _ := url.QueryUnescape(cookie.Value) session, _ = manager.provider.SessionRegenerate(oldsid, sid) cookie.Value = url.QueryEscape(sid) cookie.HttpOnly = true cookie.Path = "/" } maxage := -1 if len(manager.options) > 3 { switch manager.options[3].(type) { case int: if manager.options[3].(int) > 0 { maxage = manager.options[3].(int) } else if manager.options[3].(int) < 0 { maxage = 0 } case int64: if manager.options[3].(int64) > 0 { maxage = int(manager.options[3].(int64)) } else if manager.options[3].(int64) < 0 { maxage = 0 } case int32: if manager.options[3].(int32) > 0 { maxage = int(manager.options[3].(int32)) } else if manager.options[3].(int32) < 0 { maxage = 0 } } } if maxage >= 0 { cookie.MaxAge = maxage } http.SetCookie(w, cookie) r.AddCookie(cookie) return }
func doWithCookies(c *http.Client, req *http.Request) (*http.Response, error) { for _, cookie := range c.Jar.Cookies(req.URL) { req.AddCookie(cookie) } res, err := c.Do(req) if err != nil { return nil, err } if len(res.Cookies()) > 0 { c.Jar.SetCookies(req.URL, res.Cookies()) } return res, err }
func Before2Sign(writer http.ResponseWriter, req *http.Request) (e error) { if ok, name := User.IsSignIn(req); ok { cookie := &http.Cookie{ Name: "name", Value: name, Path: "/", } req.AddCookie(cookie) return } output.Puts(writer, "code", CODE_SIGN_IN_REQUIRED) return err.AccessError{Status: http.StatusBadRequest, Msg: "required sign in"} }