SDKsGo SDKOAuth 2.1
Authorization
Build OAuth 2.1 authorization URLs and handle redirects with the Go SDK.
Authorization
Build authorization URLs with PKCE for OAuth 2.1 flows.
BuildAuthorizationURL()
func (o *OAuthService) BuildAuthorizationURL(ctx context.Context, params *AuthorizationURLParams) (*AuthorizationURL, error)Parameters
| Field | Type | Required | Description |
|---|---|---|---|
Scopes | []string | yes | OAuth scopes |
RedirectURI | string | yes | Callback URL |
State | string | no | CSRF token (auto-generated if empty) |
Prompt | string | no | "none", "login", "consent" |
LoginHint | string | no | Pre-fill email |
OrganizationID | string | no | Restrict to org |
Basic usage
result, err := client.OAuth.BuildAuthorizationURL(ctx, &avnologyid.AuthorizationURLParams{
Scopes: []string{"openid", "profile", "email", "offline_access"},
RedirectURI: "https://myapp.com/callback",
})
if err != nil {
log.Fatal(err)
}
fmt.Println("Redirect to:", result.URL)
// Store code verifier in session for the callback
session.Set("code_verifier", result.CodeVerifier)
session.Set("oauth_state", result.State)ExchangeCode()
Exchange the authorization code for tokens.
tokens, err := client.OAuth.ExchangeCode(ctx, &avnologyid.ExchangeCodeParams{
Code: authCode,
CodeVerifier: codeVerifier,
RedirectURI: "https://myapp.com/callback",
})
if err != nil {
var invalidGrant *errors.InvalidGrantError
if errors.As(err, &invalidGrant) {
log.Println("Authorization code expired or invalid")
return
}
log.Fatal(err)
}
fmt.Println("Access token:", tokens.AccessToken)
fmt.Println("Refresh token:", tokens.RefreshToken)
fmt.Println("Expires in:", tokens.ExpiresIn, "seconds")Complete HTTP handler
func callbackHandler(w http.ResponseWriter, r *http.Request) {
code := r.URL.Query().Get("code")
state := r.URL.Query().Get("state")
// Validate state
savedState := getSession(r).Get("oauth_state")
if state != savedState {
http.Error(w, "State mismatch", http.StatusBadRequest)
return
}
codeVerifier := getSession(r).Get("code_verifier")
tokens, err := client.OAuth.ExchangeCode(r.Context(), &avnologyid.ExchangeCodeParams{
Code: code,
CodeVerifier: codeVerifier,
RedirectURI: "https://myapp.com/callback",
})
if err != nil {
http.Error(w, "Token exchange failed", http.StatusInternalServerError)
return
}
// Store tokens in session
session := getSession(r)
session.Set("access_token", tokens.AccessToken)
session.Set("refresh_token", tokens.RefreshToken)
session.Save(w)
http.Redirect(w, r, "/dashboard", http.StatusFound)
}See also
- Tokens -- Token management
- Client credentials -- M2M auth