feat: initial commit
This commit is contained in:
@@ -0,0 +1,8 @@
|
||||
package auth
|
||||
|
||||
import "github.com/golang-jwt/jwt/v5"
|
||||
|
||||
type Authenticator interface {
|
||||
GenerateToken(jwt.Claims) (string, error)
|
||||
ValidateToken(string) (*jwt.Token, error)
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
)
|
||||
|
||||
type JWTAuthenticator struct {
|
||||
secret string
|
||||
aud string
|
||||
iss string
|
||||
}
|
||||
|
||||
func NewJWTAuthenticator(secret, aud, iss string) *JWTAuthenticator {
|
||||
return &JWTAuthenticator{
|
||||
secret: secret,
|
||||
aud: aud,
|
||||
iss: iss,
|
||||
}
|
||||
}
|
||||
|
||||
func (j *JWTAuthenticator) GenerateToken(claims jwt.Claims) (string, error) {
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
||||
|
||||
tokenString, err := token.SignedString([]byte(j.secret))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return tokenString, nil
|
||||
}
|
||||
|
||||
func (j *JWTAuthenticator) ValidateToken(tokenString string) (*jwt.Token, error) {
|
||||
return jwt.Parse(tokenString, func(t *jwt.Token) (any, error) {
|
||||
if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
|
||||
return nil, fmt.Errorf("unexpected signing method: %v", t.Header["alg"])
|
||||
}
|
||||
|
||||
return []byte(j.secret), nil
|
||||
},
|
||||
jwt.WithExpirationRequired(),
|
||||
jwt.WithAudience(j.aud),
|
||||
jwt.WithIssuer(j.iss),
|
||||
jwt.WithValidMethods([]string{jwt.SigningMethodHS256.Name}),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
)
|
||||
|
||||
type TestAuthenticator struct {
|
||||
}
|
||||
|
||||
const testToken = "test-token"
|
||||
|
||||
var testClaims = jwt.MapClaims{
|
||||
"aud": "test-audience",
|
||||
"iss": "test-issuer",
|
||||
"sub": 1,
|
||||
"exp": time.Now().Add(time.Hour * 24).Unix(),
|
||||
}
|
||||
|
||||
func (a *TestAuthenticator) GenerateToken(claims jwt.Claims) (string, error) {
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, testClaims)
|
||||
|
||||
return token.SignedString([]byte(testToken))
|
||||
}
|
||||
|
||||
func (a *TestAuthenticator) ValidateToken(token string) (*jwt.Token, error) {
|
||||
return jwt.Parse(token, func(token *jwt.Token) (any, error) {
|
||||
return []byte(testToken), nil
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user