A few questions about using JWTs in my Go program

polaris · · 458 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>I&#39;ve spent a few hours now looking at pretty much every link I can find about setting up a simple JWT-based auth system in my web application, but I&#39;m not quite at the finish line yet. It looks like the main JWT package has been updated since a few of the videos/tutorials on using them have been made, so I&#39;m missing a few pieces of the puzzle that I&#39;m hoping someone can help fill in.</p> <p>Here&#39;s the function I&#39;m using to generate a JWT when someone hits the /login endpoint: </p> <pre><code>func LoginHandler(w http.ResponseWriter, r *http.Request, _ httprouter.Params) { decoder := json.NewDecoder(r.Body) var u User err := decoder.Decode(&amp;u) if err != nil { panic(err) } defer r.Body.Close() email := u.Email password := u.Password // Check database here if strings.ToLower(email) != &#34;testEmail.com&#34; { if password != &#34;pw&#34; { w.WriteHeader(http.StatusForbidden) fmt.Println(&#34;Error logging in&#34;) fmt.Fprint(w, &#34;Invalid credentials&#34;) return } } signer := jwt.New(jwt.GetSigningMethod(&#34;RS256&#34;)) // Dealing with claims claims := make(jwt.MapClaims) claims[&#34;iss&#34;] = &#34;testClaim&#34; claims[&#34;exp&#34;] = time.Now().Add(time.Minute * 10).Unix() claims[&#34;CustomUserInfo&#34;] = struct { Email string Role string }{email, &#34;user&#34;} signer.Claims = claims parsedPrivateKey, err := jwt.ParseRSAPrivateKeyFromPEM(SignKey) if err != nil { panic(err) } tokenString, err := signer.SignedString(parsedPrivateKey) if err != nil { w.WriteHeader(http.StatusInternalServerError) fmt.Fprintln(w, &#34;Error while signing the token&#34;) log.Printf(&#34;Error signing token: %v\n&#34;, err) } response := Token{tokenString} JsonResponse(response, w) // Just to see the response fmt.Printf(&#34;%+v&#34;, response) } </code></pre> <p>JsonResponse just writes json to the header. My first question is more generally about JWTs: when someone hits the /login endpoint, their credentials checked by the database, and a JWT is generated (per the function above), where is the JWT stored? In this case, wouldn&#39;t it only be stored on the header for that specific response? Should I be storing this JWT in cookies, or local storage? </p> <p>Finally (and the most crucial piece I&#39;m missing), how should I go about validating a token? The ParseFromRequest function seems to have been removed from the JWT package. </p> <p>I started with an outline like this: </p> <pre><code>func ValidateToken(w http.ResponseWriter, r *http.Request, _ httprouter.Params) { token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) { if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok { return nil, fmt.Errorf(&#34;Unexpected signing method: %v&#34;, token.Header[&#34;alg&#34;]) } return rsaSecret, nil }) </code></pre> <p>Is this the right direction? Should I be checking the request header for the &#34;Authorization bearer {token}&#34;? as the tokenString value? Sorry for the long post, any help at all would be greatly appreciated!</p> <hr/>**评论:**<br/><br/>earthboundkid: <pre><p>I don&#39;t know much about JWT, but this is worth saying in case anyone is new to web dev:</p> <p>The line <code>password != &#34;pw&#34;</code> should not be translated into working code (checking that the password is in the DB). Passwords should not be stored in databases because if they are and a hacker steals your database (for example by getting a database backup from a rogue worker or stealing a laptop), then they will know all your users passwords and be able to try those same username+password combinations on other sites, to check for password reuse.</p> <p>Instead, what you should store in the database is a &#34;salted hash&#34; of the password. Essentially, with a salted hash, a user&#39;s password is turned into an opaque string that cannot be reversed back into the plain text. The most popular algorithm for this is bcrypt. There are more details, but that&#39;s the minimum anyone dealing with passwords absolutely has to know. Google around and you should be able to find more about constant time comparisons and whatnot.</p></pre>ConfuciusBateman: <pre><p>Oh I definitely would not use this in production. This was just to test that my HTTP requests were working correctly.</p></pre>earthboundkid: <pre><p>I figured as much, just thought it was better to be safe than sorry. :-)</p></pre>ConfuciusBateman: <pre><p>Haha no worries, I appreciate the lookout! </p></pre>Tikiatua: <pre><p>I am currently developing a single sign on solution for our various services and did some extensive research on best practice recommendations for jwts.</p> <p>Some good resources were the documentation and blog posts of auth0 (<a href="https://auth0.com" rel="nofollow">https://auth0.com</a>) and stormpath (<a href="https://stormpath.com" rel="nofollow">https://stormpath.com</a>) as well as the specification of OpenID connect (<a href="http://openid.net/connect/" rel="nofollow">http://openid.net/connect/</a>).</p> <p>That said, best practice really boil down to your security requirements and to what you want to use jwts for. </p> <p>The basic problem with jwts is, that someone might steel the token and would then be able to login as the user until the jwt expires. </p> <p>Then there is sort of a federation problem: Let&#39;s say you have a single-sign-on (like for google) that should allow your users to access multiple services after they have logged in. If you are using oauth, the service would get the user authenticated from single-sign-on and then establish its own session by - for example - using jwts. Now the problem is, that jwts typically only get saved on the client. Hence, it becomes quite tricky to stop the session for all services once the users is login out from the single-sign on. This would require to somehow delete the jwts from all services on the client or require you to have a blacklist on the server - which sort of brings you back to the regular session management before jwts. There are some workarounds, but it does get rather complicated.</p> <p>It becomes simpler, if we focus on a single service. Were to store, respectively check for the jwt basically boils down to three options:</p> <ul> <li><p>Request header with &#34;Authentication bearer {token}&#34;. Really convenient for api calls from the command line. Question would be were the client would save the token</p></li> <li><p>Saving the jwt in local storage - as done by auth0. This gives your frontend code access to the information stored in the jwt. Which is great for example for single page applications that should adapt based on user permissions or show information about the current user. However, there is a certain attach surface for this, as the jwt is accessible with javascript. In addition you must implement the functionality to pass the jwt to the server on every request (i.e. as post parameter or as header token)</p></li> <li><p>Saving the jwt in a cookie - recommended in a blog post from stormpath. This is really convenient, as we can leverage the browser functionality to store and expire jwt-cookies. For security reasons the cookies should be set to httpOnly (no javascript access) and secure (to only be passed over https)</p></li> </ul> <p>Here is the code I am using for a web-application that uses cookies to store the jwt (only example code).</p> <pre><code>jwt &#34;github.com/dgrijalva/jwt-go&#34; &#34;github.com/labstack/echo&#34; &#34;github.com/pkg/errors&#34; &#34;github.com/uber-go/zap&#34; // should be replaced by your custom secret var tokenSecret = []byte(&#34;abcdefgh&#34;) const tokenIssuer = &#34;your.domain&#34; // define custom token claims type tokenClaims struct { models.User jwt.StandardClaims } func (env *Environment) requireAuthentication(next echo.HandlerFunc) echo.HandlerFunc { return func(ctx echo.Context) error { // check if the users has a jwt token set in the cookie cookie, err := ctx.Cookie(tokenIssuer) if err != nil { env.Logger.Info(&#34;could not read token cookie&#34;, zap.Error(err)) return ctx.Render(http.StatusOK, &#34;login.html&#34;, nil) } // parse the token string from the cookie tokenString := cookie.Value // check if the token is authenticated token, err := jwt.ParseWithClaims(tokenString, &amp;tokenClaims{}, func(token *jwt.Token) (interface{}, error) { // validate that the signig method is correct if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok { return nil, fmt.Errorf(&#34;Unexpected signing method: %v&#34;, token.Header[&#34;alg&#34;]) } return tokenSecret, nil }) if err != nil { env.Logger.Error(&#34;jwt token error&#34;, zap.Error(err)) return unauthorizedResponse(ctx) } // try to extract our custom claims from the token claims, ok := token.Claims.(*tokenClaims) // check if the token is valid if !ok || token.Valid == false { env.Logger.Info(&#34;token is expired&#34;, zap.Int64(&#34;expired&#34;, claims.ExpiresAt)) return unauthorizedResponse(ctx) } // save the user information in the context ctx.Set(&#34;user&#34;, claims.User) // issue a new cookie for the token err = generateAuthToken(ctx, claims.User) if err != nil { env.Logger.Error(&#34;could not generate new token&#34;, zap.Error(err)) } // handle the next function in the chain return next(ctx) } } // generateAuthToken will issue a new authentication token func generateAuthToken(ctx echo.Context, user models.User) error { // define the claims for the jwt token claims := tokenClaims{ user, jwt.StandardClaims{ ExpiresAt: time.Now().Add(1 * time.Hour).Unix(), Issuer: tokenIssuer, }, } // create a new token token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) // sign the token with our secret tokenString, err := token.SignedString(tokenSecret) if err != nil { return errors.Wrap(err, &#34;could not generate the jwt token&#34;) } cookie := http.Cookie{} // set the name and value of our token cookie cookie.Name = tokenIssuer cookie.Value = tokenString // expire cookie in an hour cookie.Expires = time.Now().Add(1 * time.Hour) // cookie shall not be accessible by javascript cookie.HttpOnly = true // always require https connections cookie.Secure = true // write the cookie header to the given context ctx.SetCookie(&amp;cookie) return nil } func setExpiredCookie(ctx echo.Context) { cookie := http.Cookie{} // set the name and value of our token cookie cookie.Name = tokenIssuer cookie.Value = &#34;&#34; // expire cookie in an hour cookie.Expires = time.Now().Add(-2 * time.Hour) // cookie shall not be accessible by javascript cookie.HttpOnly = true // always require https connections cookie.Secure = true // write the cookie header to the given context ctx.SetCookie(&amp;cookie) } </code></pre></pre>luckyleprechaun98: <pre><p>Typically you put the JWT in the Auth header as <code>Bearer &lt;token&gt;</code> but you can also pass it as a cookie or as a URL query parameter. </p> <p>I wrote the JWT middleware for Caddy server. Feel free to check it out for some ideas. </p> <p><a href="https://github.com/BTBurke/caddy-jwt" rel="nofollow">https://github.com/BTBurke/caddy-jwt</a></p></pre>Asti_: <pre><p>I would love to see a tutorial from someone on how to implement JWTs from scratch, explaining benefits and reasons of choices that should be considered when implementing them. </p></pre>TheMue: <pre><p>Dunno exactly which package you&#39;ve chosen, but I developed my own one at <a href="https://godoc.org/github.com/tideland/gorest/jwt" rel="nofollow">https://godoc.org/github.com/tideland/gorest/jwt</a>. The unit tests at <a href="https://github.com/tideland/gorest/tree/master/jwt" rel="nofollow">https://github.com/tideland/gorest/tree/master/jwt</a> show how to use it.</p></pre>thewhitetulip: <pre><p>I invite you to take a look at this chapter: <a href="https://github.com/thewhitetulip/web-dev-golang-anti-textbook/blob/master/manuscript/8.0buildingAPI.md" rel="nofollow">https://github.com/thewhitetulip/web-dev-golang-anti-textbook/blob/master/manuscript/8.0buildingAPI.md</a></p> <p>Also at <a href="https://github.com/thewhitetulip/Tasks/" rel="nofollow">https://github.com/thewhitetulip/Tasks/</a>, I have implemented JWT</p></pre>

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

458 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传