登录
首页 >  Golang >  Go问答

Bcrypt身份验证与JWT授权

来源:stackoverflow

时间:2024-02-22 12:21:25 239浏览 收藏

偷偷努力,悄无声息地变强,然后惊艳所有人!哈哈,小伙伴们又来学习啦~今天我将给大家介绍《Bcrypt身份验证与JWT授权》,这篇文章主要会讲到等等知识点,不知道大家对其都有多少了解,下面我们就一起来看一吧!当然,非常希望大家能多多评论,给出合理的建议,我们一起学习,一起进步!

问题内容

我有一个 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 令牌包含在授权 HTTP 标头中,作为承载身份验证方案的一部分

JWT 令牌由颁发者(执行身份验证的服务器)进行数字签名,无需再次与服务器通信即可对其进行验证

因此需要在登录成功后生成。在您的情况下,在重定向到欢迎页面之前。

好了,本文到此结束,带大家了解了《Bcrypt身份验证与JWT授权》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>