Golang中如何获取JWT令牌

Golang中如何获取JWT令牌 我想实现以下JavaScript逻辑,在Go中获取用户的JWT令牌(从Cognito用户池接收JWT令牌。 我查看了https://github.com/aws/aws-sdk-go但找不到对应的类。 有人能指导我如何在Go中实现这个吗?

谢谢

var authenticationData = {
    Username : 'username',
    Password : 'password',
};
var authenticationDetails = new AmazonCognitoIdentity.AuthenticationDetails(authenticationData);
var poolData = { UserPoolId : 'us-east-1_xxxxx',
    ClientId : 'xxxxxxxxxxxxxxxx'
};
var userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData);
var userData = {
    Username : 'username',
    Pool : userPool
};
var cognitoUser = new AmazonCognitoIdentity.CognitoUser(userData);
cognitoUser.authenticateUser(authenticationDetails, {
    onSuccess: function (result) {
        console.log('access token + ' + result.getAccessToken().getJwtToken());
        /*Use the idToken for Logins Map when Federating User Pools with identity pools or when passing through an Authorization Header to an API Gateway Authorizer*/
        console.log('idToken + ' + result.idToken.jwtToken);
    },

    onFailure: function(err) {
        alert(err);
    },

});

更多关于Golang中如何获取JWT令牌的实战教程也可以访问 https://www.itying.com/category-94-b0.html

6 回复

看看这个代码库:似乎能解决你的问题(https://github.com/mura123yasu/go-cognito

更多关于Golang中如何获取JWT令牌的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


对于JWT,我使用了github.com/dgrijalva/jwt-go库以及Echo框架中的JWT中间件。

我是否正确理解了您的问题:您想将这段JavaScript代码移植到Go语言吗?您在这里使用了哪些JS库,它们分别有什么功能?

Rio_M:

对于 JWT,我使用这个库 GitHub - dgrijalva/jwt-go: ARCHIVE - Golang implementation of JSON Web Tokens (JWT). This project is now maintained at:

需要补充的是,很多流行的 JWT 中间件实际上也使用了这个库。

是的。我想将这段代码移植到 Go 语言中。我是 Go 语言的新手,正在学习过程中。

以下是我想要实现的目标:
通过 Go 调用 AWS Cognito API,使用用户名和密码获取 JWT 令牌。

我从亚马逊文档的 JavaScript SDK 示例中获得了这段示例代码,这正是我想在 Go 中实现的。
https://docs.aws.amazon.com/cognito/latest/developerguide/using-amazon-cognito-user-identity-pools-javascript-examples.html

在 Go SDK 中,我找不到与 JavaScript 示例中类似的类/方法,因此正在寻找能够帮助我实现相同功能的映射类及其方法。

在Go中获取Cognito用户池的JWT令牌,可以使用AWS SDK for Go的cognitoidentityprovider包。以下是完整的示例代码:

package main

import (
    "context"
    "fmt"
    "log"

    "github.com/aws/aws-sdk-go-v2/aws"
    "github.com/aws/aws-sdk-go-v2/config"
    "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider"
    "github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider/types"
)

func main() {
    // 配置AWS客户端
    cfg, err := config.LoadDefaultConfig(context.TODO(),
        config.WithRegion("us-east-1"),
    )
    if err != nil {
        log.Fatalf("无法加载AWS配置: %v", err)
    }

    client := cognitoidentityprovider.NewFromConfig(cfg)

    // 认证参数
    authInput := &cognitoidentityprovider.InitiateAuthInput{
        AuthFlow: types.AuthFlowTypeUserPasswordAuth,
        ClientId: aws.String("xxxxxxxxxxxxxxxx"), // 替换为你的ClientId
        AuthParameters: map[string]string{
            "USERNAME": "username", // 替换为实际用户名
            "PASSWORD": "password", // 替换为实际密码
        },
    }

    // 发起认证请求
    authOutput, err := client.InitiateAuth(context.TODO(), authInput)
    if err != nil {
        log.Fatalf("认证失败: %v", err)
    }

    // 从响应中提取令牌
    if authOutput.AuthenticationResult != nil {
        accessToken := authOutput.AuthenticationResult.AccessToken
        idToken := authOutput.AuthenticationResult.IdToken
        
        fmt.Printf("Access Token: %s\n", *accessToken)
        fmt.Printf("ID Token: %s\n", *idToken)
        
        // 使用令牌进行后续操作
        // accessToken和idToken都是JWT令牌
    }
}

如果需要处理刷新令牌,可以这样实现:

// 使用刷新令牌获取新的访问令牌
refreshInput := &cognitoidentityprovider.InitiateAuthInput{
    AuthFlow: types.AuthFlowTypeRefreshTokenAuth,
    ClientId: aws.String("xxxxxxxxxxxxxxxx"),
    AuthParameters: map[string]string{
        "REFRESH_TOKEN": *authOutput.AuthenticationResult.RefreshToken,
    },
}

refreshOutput, err := client.InitiateAuth(context.TODO(), refreshInput)
if err != nil {
    log.Fatalf("刷新令牌失败: %v", err)
}

if refreshOutput.AuthenticationResult != nil {
    newAccessToken := refreshOutput.AuthenticationResult.AccessToken
    fmt.Printf("新的Access Token: %s\n", *newAccessToken)
}

首先安装必要的依赖:

go mod init your-project
go get github.com/aws/aws-sdk-go-v2
go get github.com/aws/aws-sdk-go-v2/config
go get github.com/aws/aws-sdk-go-v2/service/cognitoidentityprovider

这段代码使用USER_PASSWORD_AUTH流程进行认证,成功后会返回包含JWT令牌的认证结果。确保在Cognito用户池中启用了此认证流程。

回到顶部