AuthFunc returns a [grpc_auth.AuthFunc] that authenticates incoming gRPC requests based on the configuration properties.
()
| 105 | // AuthFunc returns a [grpc_auth.AuthFunc] that authenticates incoming gRPC requests based on the configuration |
| 106 | // properties. |
| 107 | func (config *AuthConfig) AuthFunc() grpc_auth.AuthFunc { |
| 108 | return func(ctx context.Context) (newCtx context.Context, err error) { |
| 109 | // Lazy loading of JWKS |
| 110 | if config.jwks == nil && config.useJWKS { |
| 111 | log.Debugf("Trying to retrieve JWKS from %s", config.jwksURL) |
| 112 | config.jwks, err = keyfunc.Get(config.jwksURL, keyfunc.Options{ |
| 113 | RefreshInterval: time.Hour, |
| 114 | }) |
| 115 | if err != nil { |
| 116 | log.Debugf("Could not retrieve JWKS. API authentication will fail: %v", err) |
| 117 | return nil, status.Errorf(codes.FailedPrecondition, "could not retrieve JWKS: %v", err) |
| 118 | } |
| 119 | } |
| 120 | |
| 121 | token, err := grpc_auth.AuthFromMD(ctx, "bearer") |
| 122 | if err != nil { |
| 123 | log.Debugf("Could not retrieve bearer token from header metadata: %v", err) |
| 124 | |
| 125 | // We do not want to disclose any error details which could be security related, |
| 126 | // so we do not wrap the original error |
| 127 | return nil, status.Error(codes.Unauthenticated, "invalid auth token") |
| 128 | } |
| 129 | |
| 130 | tokenInfo, err := parseToken(token, config) |
| 131 | if err != nil { |
| 132 | log.Debugf("Could not parse token in request: %v", err) |
| 133 | |
| 134 | // We do not want to disclose any error details which could be security related, |
| 135 | // so we do not wrap the original error |
| 136 | return nil, status.Errorf(codes.Unauthenticated, "invalid auth token") |
| 137 | } |
| 138 | |
| 139 | newCtx = context.WithValue(ctx, AuthContextKey, tokenInfo) |
| 140 | |
| 141 | return newCtx, nil |
| 142 | } |
| 143 | } |
| 144 | |
| 145 | func parseToken(token string, authConfig *AuthConfig) (jwt.Claims, error) { |
| 146 | var parsedToken *jwt.Token |