dongluanan7163
dongluanan7163
2019-09-05 17:34
浏览 353
已采纳

验证Go中的Google聊天机器人消息

I am trying to create a google chat bot that is receiving some post via google chat and sends the data to a spreadsheet. All of this is working fine but I am struggling with doing the authentication.

I followed the docs provided here and tried to translate functionality to go. Unfortunately I fail miserably. ;-D

What did I do?

I use "github.com/coreos/go-oidc" to run the verification.

Setup the verifier like that:

const (
    audience            string = "my-project-id"
    publicCertUrlPrefix string = "https://www.googleapis.com/service_accounts/v1/metadata/x509/"
    chatIssuer          string = "chat@system.gserviceaccount.com"
)

func init() {
    context = cnx.Background()
    keySet := oidc.NewRemoteKeySet(context, publicCertUrlPrefix+chatIssuer)
    config := &oidc.Config{
        SkipClientIDCheck: true,
        ClientID:          audience,
    }
    verifier = oidc.NewVerifier(chatIssuer, keySet, config)
}

And try to run verification by doing:

func VerifyToken(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {

        // no authorization for health endpoint
        if r.URL.Path == "/health" {
            next.ServeHTTP(w, r)
            return
        }

        authHeader := r.Header.Get("Authorization")
        if authHeader == "" {
            logger.Debug("No authorization header is provided")
            http.Error(w, "Forbidden", http.StatusForbidden)
            return
        }

        authHeaderParts := strings.Fields(authHeader)
        if len(authHeaderParts) != 2 || strings.ToLower(authHeaderParts[0]) != "bearer" {
            logger.Debug("Authorization header is not valid")
            http.Error(w, "Authorization header format must be Bearer {token}", http.StatusForbidden)
            return
        }

        token := authHeaderParts[1]
        if _, e := verifier.Verify(context, token); e != nil {
            logger.Debug("Invalid token: ", e.Error())
            http.Error(w, "Invalid token", http.StatusUnauthorized)
            return
        }

        next.ServeHTTP(w, r)
    })
}

Unfortunately this fails with the following error:

Invalid token: failed to verify signature: failed to verify id token signature

any idea what I am doing wrong?

Best

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • duangonglian6028
    duangonglian6028 2019-09-06 06:36
    已采纳

    So we got it working by setting the proper URL for the key as we are expecting a jwt token, the URL has to be: https://www.googleapis.com/service_accounts/v1/jwk/.

    点赞 评论

相关推荐