Muhammad Shaaban
Muhammad Shaaban

Reputation: 39

jquery ajax not creating golang session cockie

I am creating an creating login part for with preact, jquery and golang. I am using chrome for testing. The login API works fine with testing by postman written in golang. Here is code for this part

e.Use(session.Middleware(sessions.NewCookieStore([]byte("secret"))))
//e.Use(xrayWrapper("bonusapi"))

e.POST("/login", func(c echo.Context) error {
    sess, _ := session.Get("session", c)
    sess.Options = &sessions.Options{
        Path:     "/",
        MaxAge:   86400 * 7,
        HttpOnly: true,
    }

    if(sess.Values["auth"] == true){
        return c.String(http.StatusOK, "Already Login")
    }else {
        fmt.Println(sess.Values["auth"])
    }

    if(c.FormValue("password") == "admin" && c.FormValue("username") == "admin"){
        sess.Values["auth"] = true
        sess.Save(c.Request(), c.Response())
        fmt.Println(sess.Values["auth"])
        return c.String(http.StatusOK, "Login session start")
    }else {
        return c.String(http.StatusOK, "Forbidden Access")
    }

    //return c.String(http.StatusOK, )
})

But it does not work when I use ajax request with jquery. I mean session cookies does do not work in ajax request. I am not sure what is the problem with it. Anyone can help, please. Here is my ajax request code which has a problem I think

var username = props["path"][6].getElementById("username").value.trim();
    var password = props["path"][6].getElementById("password").value.trim();
    var credentials = {
        username: username,
        password: password
    }

    var _this = this
    $.ajax({
        type: "POST",
        url:"http://127.0.0.1:5000/login", 
        data:credentials
    })
    .done(function(data){
        console.log(data);
    });

Upvotes: 0

Views: 246

Answers (1)

Roman Kiselenko
Roman Kiselenko

Reputation: 44380

You're missing ajax headers withCredentials

For cross-domain scenario, 3 things need to happen:

  • Client needs to set withCredentials=true for the xhr object
  • Set Access-Control-Allow-Credentials both in the OPTIONS preflight request as well as the actual request
  • Set the cookie as needed

The most interesting capability exposed by both XMLHttpRequest or Fetch and CORS is the ability to make "credentialed" requests that are aware of HTTP cookies and HTTP Authentication information. By default, in cross-site XMLHttpRequest or Fetch invocations, browsers will not send credentials.

$.ajax({
    type: "POST",
    url:"http://127.0.0.1:5000/login", 
    data:credentials,
    xhrFields: {
      withCredentials: true
   }
})
.done(function(data){
    console.log(data);
});

Upvotes: 1

Related Questions