Parse/Validate JWT token from AzureAD in golang

Issue

I have Azure AD setup with OAuth2 and have it issuing a JWT for my web app. On subsequent requests, I want to validate the JWT that was issued. I’m using github.com/dgrijalva/jwt-go to do so however it always fails.

token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
    if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
        return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
    }
    return []byte("bW8ZcMjBCnJZS-ibX5UQDNStvx4"), nil
})
if err != nil {
    return nil, err
}

I’m picking at random the kid claim from the public keys listed by MS here https://login.microsoftonline.com/common/discovery/v2.0/keys so I’m lost as this isn’t working.

Has anyone done this before or have any pointers?

Solution

Annoyingly it was a Azure AD config issue and out of the box it will generate a JWT token for MS Graph and the whole auth process succeeds but when you try to validate the token it fails for some reason. Once you have setup Azure AD correctly for your app with a correct scope it validates properly. I blogged about the specifics here – https://blog.jonathanchannon.com/2022-01-29-azuread-golang/

Answered By – Jon

Answer Checked By – Jay B. (GoLangFix Admin)

Leave a Reply

Your email address will not be published.