Genkit supports flow-level authentication, allowing you to secure your flows and ensure that only authorized users can execute them. This is particularly useful when deploying flows as HTTP endpoints.
Configuring Flow Authentication
To add authentication to a flow, you can use the WithFlowAuth
option when defining the flow. This option takes an implementation of the FlowAuth
interface, which provides methods for handling authentication and authorization.
Here's an example of how to define a flow with authentication:
ctx := context.Background()
// Define an auth policy and create a Firebase auth provider
firebaseAuth, err := firebase.NewAuth(ctx, func(authContext genkit.AuthContext, input any) error {
// The type must match the input type of the flow.
userID := input.(string)
if authContext == nil || authContext["UID"] != userID {
return errors.New("user ID does not match")
}
return nil
}, true)
if err != nil {
log.Fatalf("failed to set up Firebase auth: %v", err)
}
// Define a flow with authentication
authenticatedFlow := genkit.DefineFlow(
"authenticated-flow",
func(ctx context.Context, userID string) (string, error) {
return fmt.Sprintf("Secure data for user %s", userID), nil
},
genkit.WithFlowAuth(firebaseAuth),
)
In this example, we're using the Firebase auth plugin to handle authentication. The policy
function defines the authorization logic, checking if the user ID in the auth context matches the input user ID.
Using the Firebase Auth Plugin
The Firebase auth plugin provides an easy way to integrate Firebase Authentication with your Genkit flows. Here's how to use it:
Import the Firebase plugin:
import "github.com/firebase/genkit/go/plugins/firebase"
Create a Firebase auth provider:
firebaseAuth, err := firebase.NewAuth(ctx, policy, required)
The
NewAuth
function takes three arguments:ctx
: The context for Firebase initialization.policy
: A function that defines your authorization logic.required
: A boolean indicating whether authentication is required for direct calls.
Use the auth provider when defining your flow:
genkit.DefineFlow("secureUserFlow", userDataFunc, genkit.WithFlowAuth(firebaseAuth))
Handling Authentication in HTTP Requests
When your flow is deployed as an HTTP endpoint, the Firebase auth plugin will automatically handle authentication for incoming requests. It expects a Bearer token in the Authorization header of the HTTP request.
Running Authenticated Flows Locally
When running authenticated flows locally or from within other flows, you can provide local authentication context using the WithLocalAuth
option:
response, err := authenticatedFlow.Run(ctx, "user123",
genkit.WithLocalAuth(map[string]any{"UID": "user123"}))
This allows you to test authenticated flows without needing to provide a valid Firebase token.