简体   繁体   中英

Bcrypt authentication and JWT authorization

I have a GET handler /login that displays a form asking for a username and password.

type Credentials struct {
   Username string `json:"username"`
   Password string `json:"password"`
}

func login(w http.ResponseWriter, req *http.Request) {
   creds := &Credentials{}
   creds.Username = req.FormValue("username")
   creds.Password = req.FormValue("password")

   result := config.Db.QueryRow("SELECT password FROM users WHERE username=$1", creds.Username)

   storedCreds := &Credentials{}
   err := result.Scan(&storedCreds.Password)
   if err != nil {
      if err == sql.ErrNoRows {
          // No such row. Return to login form
          http.Redirect(w, req, "/login", http.StatusSeeOther)
          return
      }

      fmt.Println("internal error")
      return
}

   err = bcrypt.CompareHashAndPassword([]byte(storedCreds.Password), []byte(creds.Password))
   if err != nil {
      // wrong password - return to login form
      http.Redirect(w, req, "/login", http.StatusSeeOther)
      return
   }

   // username and password match. Redirect to /welcome.
   http.Redirect(w, req, "/welcome", http.StatusSeeOther)
}

For authorization I use JWT (JSON Web Tokens), so there's nothing stored on the server, but the token has to be created and stored on the user's computer in a cookie. I was wondering when should I start creating the cookie that stores the token? Right after the sign-in succeeds? Is that okay?

   err = bcrypt.CompareHashAndPassword([]byte(storedCreds.Password), []byte(creds.Password))
   if err != nil {
      // wrong password - return to login form
      http.Redirect(w, req, "/login", http.StatusSeeOther)
      return
   }


   // Should I create the cookie/token here?


   // username and password match. Redirect to /welcome.
   http.Redirect(w, req, "/welcome", http.StatusSeeOther)
}

Most examples I saw on the web describes the process of JWT authorization without the authentication (login form), so that's why I'm asking.

JWT is one of the safest ways to authenticate HTTP requests. In a JWT flow, the token itself contains the data. The server decrypts the token to authenticate the user only. No data stored on the server.

JWT tokens are included in the Authorization HTTP header as part of the bearer authentication scheme

JWT tokens are digitally signed by the issuer (server doing the authentication), they can be validated without talking to the server again

Hence it needs to be generated after successful login. In your case, before redirecting to welcome page.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM