在从Golang Buffalo webapp发送推文时设置CSRF令牌时遇到问题

问题描述 投票:1回答:2

我正在努力建立一个Go Buffalo网络应用程序。我基本上在前端有一个标准表单,当点击时,应该发送一条推文到用户的Twitter帐户。这样做时我得到“500:CSRF Not found”。我正在使用Go Buffalo框架用于web应用程序和go-twitter来处理twitter API。

我对CSRF几乎没有经验,所以希望有人可以帮助我解决这个问题。

tweet.HTML:

<h3>Tweet tweet!</h3>
<form action="/tweet" method="POST">
    <div class="form-group">
        <label for="tweet">Your tweet:</label>
        <input type="text" name="tweet" class="form-control" id="tweet" placeholder="Tweet body" 
        value="">
    </div>
    <button type="submit" class="btn btn-primary">Send</button>
</form>

路由器:

app.POST("/tweet", SendHandler)

Tweet.go(包含SendHandler函数):

package actions

import (
    "fmt"
    "log"
    "os"

    "twitapp/twitter"

    "github.com/gobuffalo/buffalo"
)

var creds = twitter.Credentials{
    AccessToken:       os.Getenv("ACCESS_TOKEN"),
    AccessTokenSecret: os.Getenv("ACCESS_TOKEN_SECRET"),
    APIKey:            os.Getenv("API_KEY"),
    APISecret:         os.Getenv("API_SECRET"),
}

type TweetForm struct {
    TweetBody string
}

// TweetHandler is the handler for the Tweet page
func TweetHandler(c buffalo.Context) error {
    return c.Render(200, r.HTML("tweet.html"))
}

//SendHandler Function used by tweet.html to send the tweet/
//Takes in variables from twitter/server.go
func SendHandler(c buffalo.Context) error {

    var form TweetForm
    body := form.TweetBody

    fmt.Printf("%+v\n", creds)

    //Gets the client from the twitter package
    client, err := twitter.GetClient(&creds)
    if err != nil {
        log.Println("Error getting Twitter Client")
        log.Println(err)
    }

    //Sending the actual tweet. Body from the form
    tweet, resp, err := client.Statuses.Update(body, nil)
    if err != nil {
        log.Println(err)
    }
    log.Printf("%+v\n", resp)
    log.Printf("%+v\n", tweet)
    return c.Redirect(302, "/tweet/confirm")

}

还有一个从SendHandler函数调用的GetClient函数,但我无法想象问题在于那里,因为它为调用设置了twitter客户端的标准代码。感谢任何帮助/指向正确的方向。我目前还没有足够的CSRF知识来应用它。

go csrf buffalo
2个回答
1
投票

CSRF是一种攻击布法罗试图保护你免受攻击。

为此,它使用CSRF middleware检查每个可以改变数据的请求(例如POST,PUT,DELETE等)并查找特定的令牌。在您的用例中,Buffalo希望您发送一个名为“authenticity_token”的输入字段,其中包含CSRF中间件放在上下文中的值。您可以在上下文中的相同“authenticity_token”键中找到此值。

另一种解决方案是使用标签助手(https://github.com/gobuffalo/tags)库为您生成此预期输入:https://github.com/gobuffalo/tags/wiki/Form


0
投票

在查看GoBuffalo文档,特别是表单页面的THIS部分之后,我所要做的就是将这行代码添加到我的表单(tweet.html)来处理真实性令牌。

<input name="authenticity_token" type="hidden" value="<%= authenticity_token %>">
© www.soinside.com 2019 - 2024. All rights reserved.