|
| 1 | +package sign |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "io" |
| 6 | + "os" |
| 7 | + "time" |
| 8 | + |
| 9 | + "github.com/golang-jwt/jwt" |
| 10 | +) |
| 11 | + |
| 12 | +func GenerateToken() (string, error) { |
| 13 | + privateKeyFile, err := os.Open("/home/ivan/Projects/go/golang-jwt/go-jws/sign_rsa/certs/id_rsa") |
| 14 | + if err != nil { |
| 15 | + panic(err) |
| 16 | + } |
| 17 | + defer privateKeyFile.Close() |
| 18 | + privateKeyBytes, err := io.ReadAll(privateKeyFile) |
| 19 | + if err != nil { |
| 20 | + panic(err) |
| 21 | + } |
| 22 | + |
| 23 | + privateKey, err := jwt.ParseRSAPrivateKeyFromPEM(privateKeyBytes) |
| 24 | + if err != nil { |
| 25 | + panic(err) |
| 26 | + } |
| 27 | + |
| 28 | + token := jwt.New(jwt.SigningMethodRS256) |
| 29 | + |
| 30 | + claims := token.Claims.(jwt.MapClaims) |
| 31 | + claims["exp"] = time.Now().Add(10 * time.Minute).Unix() |
| 32 | + claims["username"] = "test" |
| 33 | + claims["password"] = "test" |
| 34 | + |
| 35 | + tokenString, err := token.SignedString(privateKey) |
| 36 | + if err != nil { |
| 37 | + panic(err) |
| 38 | + } |
| 39 | + |
| 40 | + return tokenString, nil |
| 41 | +} |
| 42 | + |
| 43 | +type CustomClaims struct { |
| 44 | + Username string `json:"username"` |
| 45 | + Password string `json:"password"` |
| 46 | + jwt.StandardClaims |
| 47 | +} |
| 48 | + |
| 49 | +func ValidateToken(tokenSigned string) (res map[string]interface{}, err error) { |
| 50 | + publicKeyFile, err := os.Open("/home/ivan/Projects/go/golang-jwt/go-jws/sign_rsa/certs/id_rsa.pub") |
| 51 | + if err != nil { |
| 52 | + panic(err) |
| 53 | + } |
| 54 | + defer publicKeyFile.Close() |
| 55 | + |
| 56 | + publicKeyBytes, err := io.ReadAll(publicKeyFile) |
| 57 | + if err != nil { |
| 58 | + panic(err) |
| 59 | + } |
| 60 | + |
| 61 | + publicKey, err := jwt.ParseRSAPublicKeyFromPEM(publicKeyBytes) |
| 62 | + if err != nil { |
| 63 | + panic(err) |
| 64 | + } |
| 65 | + |
| 66 | + token, err := jwt.ParseWithClaims(tokenSigned, &CustomClaims{}, func(token *jwt.Token) (interface{}, error) { |
| 67 | + _, ok := token.Method.(*jwt.SigningMethodRSA) |
| 68 | + if !ok { |
| 69 | + return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"]) |
| 70 | + } |
| 71 | + return publicKey, nil |
| 72 | + }) |
| 73 | + if err != nil { |
| 74 | + panic(err) |
| 75 | + } |
| 76 | + |
| 77 | + if claims, ok := token.Claims.(*CustomClaims); ok && token.Valid { |
| 78 | + res = make(map[string]interface{}, 2) |
| 79 | + res["username"] = claims.Username |
| 80 | + res["password"] = claims.Password |
| 81 | + return |
| 82 | + } |
| 83 | + |
| 84 | + return nil, fmt.Errorf("token invalid: %v", tokenSigned) |
| 85 | +} |
0 commit comments