Users love convenience. If your goal is to make it easy for users to register with your app or website, then implementing the “Sign in with Google” option should be at the top of your priority list. If you are like me, then you may find Google’s documentation on the subject to be lackluster at best, and downright confusing at worst. Here we will go step-by-step through the authentication process that our Go servers at Qvault Classroom use for Google sign in.
We aren’t going to focus on the front-end part of the authentication process because that’s the easy part. That said, for any of this to make sense we will briefly touch on how it works.
The front-end’s job is to do some redirect OAuth magic to obtain a JWT signed by Google. This is accomplished by including Google’s SDK in your HTML, making an application in GCP, and creating a button using the proper class. I would recommend following Google’s quick tutorial to get this working.
Once you are done with all that, you should have a button on your web page. When a user clicks on the button and authorizes their Google account, you will get a JWT back in the onSignIn
callback function:
function onSignIn(googleUser) {
const googleJWT = googleUser.getAuthResponse().id_token
}
All we care about is that JWT. We are going to create a backend function in Go that receives the JWT and ensures it’s validity before allowing the user to login to our app.
Let’s build a single function that validates JWT’s from Google. It has the following function signature:
// ValidateGoogleJWT -
func ValidateGoogleJWT(tokenString string) (GoogleClaims, error) {
}
ValidateGoogleJWT
takes a JWT string (that we get from the front-end) and returns the validated GoogleClaims
struct if the JWT passes our checks. Otherwise, we will return an error explaining what went wrong.
JWT’s are just JSON objects that are signed with a private key to ensure they haven’t been tampered with. The signed JSON object’s fields are referred to as “claims”. We will be using the most popular JWT library in Go to build our solution: https://github.com/dgrijalva/jwt-go, and the claims that Google sends have the following shape:
// GoogleClaims -
type GoogleClaims struct {
Email string `json:"email"`
EmailVerified bool `json:"email_verified"`
FirstName string `json:"given_name"`
LastName string `json:"family_name"`
jwt.StandardClaims
}
#golang #languages #backend #golang #google #jwt #singlesignon #sso