Skip to main content

golang-jwt

JWT (JSON web token) is commonly used for authentication in projects with front-end and back-end separation. GoFrame does not provide built-in support for generating and validating JWTs, so third-party libraries like golang-jwt are often used.

Here's a simple usage example:

  • Installation
go get -u github.com/golang-jwt/jwt/v5
  • Import
import "github.com/golang-jwt/jwt/v5"
  • Generating a token
func (c *Controller) Jwt(req *ghttp.Request) {
type UserClaims struct {
UserID uint
UserName string
jwt.RegisteredClaims
}

const key = "arandomstring"

claim := UserClaims{
UserID: 1011,
UserName: "张之维",
RegisteredClaims: jwt.RegisteredClaims{
Subject: "张之维",
ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Minute * 10)),
},
}
token, err := jwt.NewWithClaims(jwt.SigningMethodHS256, claim).SignedString([]byte(key))
if err == nil {
req.Response.Writeln(token)
} else {
req.Response.Writeln(err)
}
}
  • Token validation
func (c *Controller) Jwt(req *ghttp.Request) {
type UserClaims struct {
UserID uint
UserName string
jwt.RegisteredClaims
}

const key = "arandomstring"

token := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJVc2VySUQiOjEwMTEsIlVzZXJOYW1lIjoi5byg5LmL57u0Iiwic3ViIjoi5byg5LmL57u0IiwiZXhwIjoxNjk4NjcxMjA3fQ.r11R1_WcDueBU52BoUjDS94jqemgrhU-V4WW7YSvXWE"
result, err := jwt.ParseWithClaims(token, &UserClaims{}, func(t *jwt.Token) (interface{}, error) {
return []byte(key), nil
})

if err == nil && result.Valid {
claim, ok := result.Claims.(*UserClaims)
if ok {
req.Response.Writeln("Token validation successful")
req.Response.Writeln(claim)
}
req.Response.Writeln(result.Claims)
} else {
req.Response.Writeln(err)
}
}

jwt.RegisteredClaims

type RegisteredClaims struct {
// Issuer
Issuer string `json:"iss,omitempty"`

// Subject - the subject of the token usage
Subject string `json:"sub,omitempty"`

// Audience
Audience ClaimStrings `json:"aud,omitempty"`

// Expiration time
ExpiresAt *NumericDate `json:"exp,omitempty"`

// Not before time
NotBefore *NumericDate `json:"nbf,omitempty"`

// Issued at time
IssuedAt *NumericDate `json:"iat,omitempty"`

// JWT ID - a unique identifier for this JWT to prevent reuse of the token
ID string `json:"jti,omitempty"`
}

Here's the translated Markdown content:

```markdown
# golang-jwt

JWT (JSON web token) is commonly used for authentication in projects with front-end and back-end separation. GoFrame does not provide built-in support for generating and validating JWTs, so third-party libraries like `golang-jwt` are often used.

Here's a simple usage example:

- Installation

```shell
go get -u github.com/golang-jwt/jwt/v5
  • Import
import "github.com/golang-jwt/jwt/v5"
  • Generating a token
func (c *Controller) Jwt(req *ghttp.Request) {
type UserClaims struct {
UserID uint
UserName string
jwt.RegisteredClaims
}

const key = "arandomstring"

claim := UserClaims{
UserID: 1011,
UserName: "张之维",
RegisteredClaims: jwt.RegisteredClaims{
Subject: "张之维",
ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Minute * 10)),
},
}
token, err := jwt.NewWithClaims(jwt.SigningMethodHS256, claim).SignedString([]byte(key))
if err == nil {
req.Response.Writeln(token)
} else {
req.Response.Writeln(err)
}
}
  • Token validation
func (c *Controller) Jwt(req *ghttp.Request) {
type UserClaims struct {
UserID uint
UserName string
jwt.RegisteredClaims
}

const key = "arandomstring"

token := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJVc2VySUQiOjEwMTEsIlVzZXJOYW1lIjoi5byg5LmL57u0Iiwic3ViIjoi5byg5LmL57u0IiwiZXhwIjoxNjk4NjcxMjA3fQ.r11R1_WcDueBU52BoUjDS94jqemgrhU-V4WW7YSvXWE"
result, err := jwt.ParseWithClaims(token, &UserClaims{}, func(t *jwt.Token) (interface{}, error) {
return []byte(key), nil
})

if err == nil && result.Valid {
claim, ok := result.Claims.(*UserClaims)
if ok {
req.Response.Writeln("Token validation successful")
req.Response.Writeln(claim)
}
req.Response.Writeln(result.Claims)
} else {
req.Response.Writeln(err)
}
}

jwt.RegisteredClaims

type RegisteredClaims struct {
// Issuer
Issuer string `json:"iss,omitempty"`

// Subject - the subject of the token usage
Subject string `json:"sub,omitempty"`

// Audience
Audience ClaimStrings `json:"aud,omitempty"`

// Expiration time
ExpiresAt *NumericDate `json:"exp,omitempty"`

// Not before time
NotBefore *NumericDate `json:"nbf,omitempty"`

// Issued at time
IssuedAt *NumericDate `json:"iat,omitempty"`

// JWT ID - a unique identifier for this JWT to prevent reuse of the token
ID string `json:"jti,omitempty"`
}