登录
首页 >  Golang >  Go问答

我可以将 JWT 令牌放入 Golang Echo 框架的 Context 中吗?

来源:stackoverflow

时间:2024-04-17 13:48:34 142浏览 收藏

推广推荐
免费电影APP ➜
支持 PC / 移动端,安全直达

大家好,今天本人给大家带来文章《我可以将 JWT 令牌放入 Golang Echo 框架的 Context 中吗?》,文中内容主要涉及到,如果你对Golang方面的知识点感兴趣,那就请各位朋友继续看下去吧~希望能真正帮到你们,谢谢!

问题内容

我正在学习如何使用 echo framework 和 golang 来实现有用且强大的 web 服务器。

现在我正在尝试构建一个附加 jwt 令牌和哈希函数的真实用户身份验证。

在 echo 官方文档和几篇博客文章中,我进行了身份验证过程,将 jwt 令牌放入 cookie 中,并在进入受限路由时将其取出。

但是,据说将身份验证方法保存在cookie、本地存储和会话存储中是非常危险的,因为我不认识的人可以访问这3种方法,并侵入我的秘密信息。

然后我尝试在 echo context 中保存令牌,而不是 cookie。

我编写了将令牌放入上下文中的代码,但我不知道如何从上下文中获取它们,然后提交到身份验证过程。

也许 jwt 配置中的 tokenlookup 属性决定了我可以存储令牌的位置,例如 header、cookie、query 和 params。那么我可以在 echo 上下文中存储 jwt 令牌吗?

我附上了示例代码。

package main

import (
    "fmt"
    "net/http"
    "time"

    "github.com/dgrijalva/jwt-go"
    "github.com/labstack/echo"
    "github.com/labstack/echo/middleware"
)

// jwtCustomClaims are custom claims extending default ones.
type jwtCustomClaims struct {
    Name  string `json:"name"`
    Admin bool   `json:"admin"`
    jwt.StandardClaims
}

func login(c echo.Context) error {
    username := c.FormValue("username")
    password := c.FormValue("password")

    // Throws unauthorized error
    if username != "jon" || password != "shhh!" {
        return echo.ErrUnauthorized
    }

    // Set custom claims
    claims := &jwtCustomClaims{
        "Jon Snow",
        true,
        jwt.StandardClaims{
            ExpiresAt: time.Now().Add(time.Hour * 3).Unix(),
        },
    }

    // Create token with claims
    token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)

    // Generate encoded token and send it as response.
    t, err := token.SignedString([]byte("secret"))
    if err != nil {
        return err
    }

    c.Set("Authorization", fmt.Sprintf("Bearer %s", t))
    return c.Redirect(http.StatusPermanentRedirect, "/restricted")
}

func accessible(c echo.Context) error {
    return c.String(http.StatusOK, "Accessible")
}

func restricted(c echo.Context) error {
    user := c.Get("user").(*jwt.Token)
    claims := user.Claims.(*jwtCustomClaims)
    name := claims.Name
    return c.String(http.StatusOK, "Welcome "+name+"!")
}

func main() {
    e := echo.New()

    // Middleware
    e.Use(middleware.Logger())
    e.Use(middleware.Recover())

    // Login route
    e.GET("/login", func(c echo.Context) error {
        return c.HTML(http.StatusOK,
            `
                <html>
                    <head>
                        <meta charset="utf-8" />
                        <title>Login Page</title>
                    </head>
                    <body>
                        <form action="/login" method="post">
                            &lt;input type=&quot;text&quot; name=&quot;username&quot; /&gt;
                            &lt;input type=&quot;text&quot; name=&quot;password&quot; /&gt;
                            <button type="submit">Action</button>
                        </form>
                    </body>
                </html>
            `,
        )
    })
    e.POST("/login", login)

    // Unauthenticated route
    e.GET("/", accessible)

    // Restricted group
    r := e.Group("/restricted")

    // Configure middleware with the custom claims type
    config := middleware.JWTConfig{
        Claims:      &jwtCustomClaims{},
        SigningKey:  []byte("secret"),
        TokenLookup: "cookie:FakeToken",
    }
    r.Use(middleware.JWTWithConfig(config))
    r.GET("", restricted)

    e.Logger.Fatal(e.Start("localhost:1323"))
}

在上下文中保存令牌是在函数登录中执行的。


解决方案


阅读https://echo.labstack.com/guide/context

这不能取代客户端的凭据存储。毕竟,客户端才是需要验证的。

文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《我可以将 JWT 令牌放入 Golang Echo 框架的 Context 中吗?》文章吧,也可关注golang学习网公众号了解相关技术文章。

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