I am trying to decode(not validate) a JWT token and read values from its body. And this part of my code also deals with non JWT tokens. So I need to handle both normal tokens (lets say some string) and JWT tokens.
To achieve that, I am splitting token with "." to read JWT body values, but the problem is "index out of range" when I get non JWT tokens(no '.'s)
package main
import (
"fmt"
"strings"
"encoding/base64"
"encoding/json"
)
func main() {
token := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ"
//nonJwtToken := "xxxxxxx"
// below line should gracefull throw error if it passed nonJwtToken
data, err := base64.RawURLEncoding.DecodeString(strings.Trim(strings.Split(token, ".")[1], "."))
if err !=nil {
fmt.Printf("error rahu : " , err)
}
var result map[string]interface{}
err = json.Unmarshal(data, &result)
fmt.Println(result["name"])
fmt.Println(err)
}
Note that I am not trying to validate JWT, all I am doing is just decoding JWT and reading values from it.
Any suggestions on this would be greatly appreciated.