Integrate with CLI agents - Stytch Docs
Command Line Interface Application Guide
In this guide, we’ll walk through the creation of a simple Command Line Interface application which utilizes Stytch Connected Apps for authentication via an existing web application. This guide will reference two example apps:
- stytch-react-example - used as the base web app that will authorize the CLI app.
- stytch-connected-apps-cli-example - a basic CLI app made with Cobra.
Users will initiate authorization from within the CLI, redirect to the web app, authorize the CLI app from within the web app, and then be redirected back to the CLI where a Connected Apps access_token will be minted.
Pre-requisites
In order to complete this guide, you’ll need:
- A Stytch project. If you don’t have one already, or would like to create a new one, in the Dashboard, click on your existing project name in the top left corner of the Dashboard, click Create Project, and then select Consumer Authentication.
- A web app that uses Stytch for authentication (this guide will use stytch-react-example).
- A basic CLI app (this guide will use stytch-connected-apps-cli-example).
Create a CLI app
Create a Connected App
Navigate to the Connected Apps section of your Stytch Dashboard, and create a new Connected App.
Configure the app as First Party Public.
Addhttp://127.0.0.1/callbackas a login redirect URL in the Connected App configuration - this is the URL our CLI app will use to receive the authorizationcode.
Omitting a port in the redirect URL permits any port to be used, allowing the CLI application to use dynamic port allocation.
Set the authorization URL in Connected Apps page tohttp://localhost:3000/oauth/authorize- this is the URL that our web app will expose to mount the<IdentityProvider />component for authorization.Add an authorization route to your web app
Add a route in your web app that mounts the<IdentityProvider />component. In stytch-react-example, we do this here:
import { IdentityProvider, useStytchUser } from '@stytch/react';
import { useEffect } from 'react';
const Authorize = () => {
const { user } = useStytchUser();
useEffect(() => {
if (!user) {
window.location.href = '/';
}
}, [user]);
return <IdentityProvider />;
};
export default Authorize;
- Configure CLI app to initiate authorization flow with PKCE
To initiate the authorization flow, configure your CLI app to navigate to your web app’s page that mounts<IdentityProvider />. The list of URL parameters required for this request can be found here.
- If you’d like to receive a
refresh_token, make sure your request includesscope=offline_access.- Because this is a public Connected App, we need to use PKCE rather than a
client_secret.
- Because this is a public Connected App, we need to use PKCE rather than a
In stytch-connected-apps-cli-example, we do this in cmd/auth.go. Relevant snippets below:
// Get a free port for the callback server
port := utils.GetOpenPort()
redirectURI := fmt.Sprintf("http://127.0.0.1:%d/callback", port)
// Generate PKCE values
codeVerifier, err := generateCodeVerifier()
if err != nil {
fmt.Printf("Error generating code verifier: %%v\n", err)
return
}
codeChallenge := generateCodeChallenge(codeVerifier);
// Construct the auth URL with PKCE parameters
params := url.Values{}
params.Add("client_id", clientID)
params.Add("redirect_uri", redirectURI)
params.Add("response_type", "code")
params.Add("code_challenge", codeChallenge)
params.Add("code_challenge_method", "S256")
params.Add("scope", "offline_access")
authURL := fmt.Sprintf("%s?%%s", authorizeURL, params.Encode())
fmt.Println("Opening browser for authentication...")
// Open the browser with the auth URL
err = openBrowser(authURL)
if err != nil {
fmt.Println("Please open the following URL in your browser:", authURL)
}
- Handle callback and exchange code for access token
Set up a callback handler in your CLI app that authenticates the authorizationcodereceived back from<IdentityProvider />via the Get Access Token endpoint.
// Channel to receive the auth code
codeChan := make(chan string)
errorChan := make(chan error)
// Set up the callback handler
http.HandleFunc("/callback", func(w http.ResponseWriter, r *http.Request) {
code := r.URL.Query().Get("code")
if code == "" {
errorChan <- fmt.Errorf("no code received in callback")
return
}
// Send success response to browser
w.Write([]byte("Authentication successful! You can close this window."))
codeChan <- code
})
// Start the server in a goroutine
go func() {
if err := server.ListenAndServe(); err != http.ErrServerClosed {
errorChan <- err
}
}()
// Wait for either the code or an error
var code string
select {
case code = <-codeChan:
fmt.Println("Received authorization code")
case err := <-errorChan:
fmt.Printf("Error: %%v\n", err)
return
case <-time.After(5 * time.Minute):
fmt.Println("Timeout waiting for authentication")
return
}
// Exchange the code for a token
token, err := exchangeCodeForToken(code, codeVerifier)
Testing
To test the flow with the example apps above:- Set up and run stytch-react-example locally, following the instructions in the README.
- Authenticate into the example app, so that you have an active Session.
- Run stytch-connected-apps-cli-example, following the instructions in the README.
- You should be automatically redirected to the authorization flow in your browser, redirect back to your CLI, and see a Connected Apps
access_token!
Next steps
Now that you’re authenticated with a Connected Appsaccess_tokenin your CLI app, your backend can authenticate API requests by verifying this token. For example, if your CLI app callsGET https://yourapp.com/api/resources:
func resourcesHandler(w http.ResponseWriter, r *http.Request) {
auth := r.Header.Get("Authorization")
if !strings.HasPrefix(auth, "Bearer ") {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
token := strings.TrimPrefix(auth, "Bearer ")
resp, err := stytchClient.IDP.IntrospectTokenLocal(r.Context(), &idp.IntrospectTokenLocalParams{
Token: token,
})
if err != nil || !resp.TokenActive {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
// Token is valid — respond with protected data
w.WriteHeader(http.StatusOK)
w.Write([]byte(`{"message": "Authenticated!"}`))
}