我有一个GET处理程序/login
,它显示要求用户名和密码的表单。
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)
}
为了获得授权,我使用JWT(JSON Web令牌),因此服务器上没有存储任何内容,但是必须创建令牌并将其存储在用户计算机中的cookie中。我想知道何时应该开始创建存储令牌的cookie?登录成功后立即进行吗?可以吗?
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)
}
我在网络上看到的大多数示例都描述了不进行身份验证(登录表单)的JWT授权过程,所以这就是我要问的原因。
JWT是验证HTTP请求的最安全方法之一。在JWT流中,令牌本身包含数据。服务器解密令牌以仅认证用户。服务器上未存储任何数据。
JWT令牌作为承载认证方案的一部分包含在Authorization HTTP标头中
JWT令牌由发行者(服务器进行身份验证)进行数字签名,无需再次与服务器对话即可对其进行验证。>
因此,成功登录后需要生成它。您的情况,请先重定向到欢迎页面。