The Solutions:
Solution 1: Parse JWT using Google’s Public Keys
Validate the Google OAuth 2.0 JWT using Google’s public keys rather than the secret you created. Here’s how to do it:
- Fetch the JSON Web Key Set (JWKS) from Google’s public keys URL:
https://www.googleapis.com/oauth2/v3/certs
. - Create a new
keyfunc
object from the fetched JWKS using theNewJSON
function from thekeyfunc
library. - Use the
Parse
function from thejwt
library to parse the JWT from Google using theKeyfunc
as the key retrieval function. - Check if the JWT is valid and access the claims if it is.
Example code for parsing the JWT using Google’s public keys:
func parseJWT(tokenString string) {
jwksJSON := json.RawMessage(getGoogleCerts())
jwks, _ := keyfunc.NewJSON(jwksJSON)
token, _ := jwt.Parse(tokenString, jwks.Keyfunc)
if token.Valid {
claims := token.Claims.(jwt.MapClaims)
fmt.Println(claims["email"], claims)
} else {
fmt.Println("Invalid JWT")
}
}
- Remember to cache the JWKS JSON for a period of time as specified in the Cache-Control header of the response from Google’s public keys URL.
Q&A
How do I parse the returned JWT token from google OAuth 2.0?
Use Google’s public keys at https://www.googleapis.com/oauth2/v3/certs to verify the token’s signature.
How do I cache the public keys?
Hit the URL and cache the JSON response for a period defined in the Cache-Control header.
Can you provide code example?
Check out the main.go file at https://github.com/MicahParks/keyfunc/blob/master/examples/json/main.go
Video Explanation:
The following video, titled "How to fix Unexpected Token in JSON error (for web developers ...", provides additional insights and in-depth exploration related to the topics discussed in this post.
Not a programmer? Read this! ** - If you get this error in an app you didn't make, and/or you're not a web developer... this video will not ...
The following video, titled "How to fix Unexpected Token in JSON error (for web developers ...", provides additional insights and in-depth exploration related to the topics discussed in this post.
Not a programmer? Read this! ** - If you get this error in an app you didn't make, and/or you're not a web developer... this video will not ...