Senior
If a user received a token, changed the role within it, and then used the modified token to access a service — how to handle this?
sobes.tech AI
Answer from AI
If a user receives a token and changes the role within it, this indicates that the token is not properly protected. To combat this, a digital signature of the token is used (for example, JWT with an HMAC or RSA signature). When the token is received, the service verifies the signature — if the token has been altered, the signature will not match, and the token will be rejected.
An example of JWT validation in Go using the github.com/dgrijalva/jwt-go library:
import (
"fmt"
"github.com/dgrijalva/jwt-go"
)
func validateToken(tokenString string, secret []byte) (*jwt.Token, error) {
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method")
}
return secret, nil
})
if err != nil {
return nil, err
}
if !token.Valid {
return nil, fmt.Errorf("invalid token")
}
return token, nil
}
Thus, any modifications to the token's content without a proper signature make it invalid.