Casdoor Go SDK is the official Go client library for Casdoor, which allows you to easily integrate Casdoor authentication and authorization into your Go applications. This SDK provides a comprehensive set of APIs to interact with Casdoor server, enabling you to manage users, organizations, applications, roles, permissions, and much more.
- Features
- Installation
- Quick Start
- Configuration
- Authentication
- Resource Management
- API Reference
- Examples
- Documentation
- Contributing
- License
- OAuth 2.0 Authentication: Complete OAuth 2.0 flow implementation with token refresh
- User Management: Create, read, update, and delete users with comprehensive profile support
- Organization Management: Manage organizations and organizational structures
- Role-Based Access Control (RBAC): Full support for roles, permissions, and policies
- Resource Management: Manage applications, certificates, providers, and more
- Session Management: Handle user sessions and authentication states
- Multi-Factor Authentication (MFA): Support for TOTP and other MFA methods
- Email & SMS: Send verification codes and notifications
- Payment & Subscriptions: Handle user payments and subscription management
- Webhook Support: Configure and manage webhooks for event notifications
- Global and Client-Specific Configuration: Flexible configuration options
To install the Casdoor Go SDK, you need Go 1.23 or higher. Run the following command in your Go project:
go get github.com/casdoor/casdoor-go-sdk@latestThen import the SDK in your Go files:
import "github.com/casdoor/casdoor-go-sdk/casdoorsdk"Here's a minimal example to get you started with Casdoor Go SDK:
package main
import (
"fmt"
"github.com/casdoor/casdoor-go-sdk/casdoorsdk"
)
func main() {
// Initialize the SDK with your Casdoor instance configuration
casdoorsdk.InitConfig(
"http://localhost:8000", // endpoint
"CLIENT_ID", // clientId
"CLIENT_SECRET", // clientSecret
"CERTIFICATE_CONTENT", // certificate (x509 format)
"my-organization", // organizationName
"my-application", // applicationName
)
// Get all users
users, err := casdoorsdk.GetUsers()
if err != nil {
panic(err)
}
fmt.Printf("Found %d users\n", len(users))
}The SDK requires six configuration parameters. You can configure the SDK in two ways:
Initialize once and use throughout your application:
casdoorsdk.InitConfig(endpoint, clientId, clientSecret, certificate, organizationName, applicationName)
// Then use SDK functions directly
users, err := casdoorsdk.GetUsers()
token, err := casdoorsdk.GetOAuthToken(code, state)Create multiple clients with different configurations:
client1 := casdoorsdk.NewClient(endpoint, clientId, clientSecret, certificate, organizationName, applicationName)
users, err := client1.GetUsers()
client2 := casdoorsdk.NewClient(endpoint2, clientId2, clientSecret2, certificate2, organizationName2, applicationName2)
users2, err := client2.GetUsers()| Parameter | Required | Description |
|---|---|---|
| endpoint | Yes | Casdoor server URL (e.g., http://localhost:8000) |
| clientId | Yes | Application client ID from Casdoor |
| clientSecret | Yes | Application client secret from Casdoor |
| certificate | Yes | x509 certificate content of your application (PEM format) |
| organizationName | Yes | Organization name in Casdoor |
| applicationName | Yes | Application name in Casdoor |
- endpoint: Your Casdoor server URL
- clientId and clientSecret: Found in your application settings in Casdoor admin panel
- certificate: Copy the certificate content from your application's "Cert" field (must be in x509 PEM format)
- organizationName: The organization that owns your application
- applicationName: Your application's name in Casdoor
You can customize the HTTP client used by the SDK to configure network behavior such as timeouts, proxies, or custom transport settings. This is particularly useful in restricted network environments or when you need specific connection parameters.
Use the SetHttpClient() function to provide a custom HTTP client:
import (
"net/http"
"time"
"github.com/casdoor/casdoor-go-sdk/casdoorsdk"
)
// Create a custom HTTP client
httpClient := &http.Client{
Timeout: 30 * time.Second,
Transport: &http.Transport{
MaxIdleConns: 100,
MaxIdleConnsPerHost: 10,
IdleConnTimeout: 90 * time.Second,
// Add proxy settings if needed
// Proxy: http.ProxyFromEnvironment,
},
}
// Set the custom HTTP client before making any API calls
casdoorsdk.SetHttpClient(httpClient)
// Now all SDK operations will use your custom HTTP client
token, err := casdoorsdk.GetOAuthToken(code, state)Note: Call SetHttpClient() before initializing the SDK configuration or making any API calls to ensure all operations use your custom client.
You can add custom HTTP headers to all API requests by directly accessing the CustomHeaders field. This is useful for:
- Setting localized error messages with
Accept-Language - Adding custom tenant identifiers
- Including trace IDs for debugging
- Passing application-specific metadata
// Create a client
client := casdoorsdk.NewClient(endpoint, clientId, clientSecret, certificate, organizationName, applicationName)
// Set custom headers by directly modifying the public field
client.CustomHeaders = map[string]string{
"Accept-Language": "de",
"X-Tenant-ID": "tenant-123",
"X-Trace-ID": "trace-abc-123",
}
// Or add individual headers
client.CustomHeaders["X-API-Version"] = "v2"
// Now all API calls will include these headers
users, err := client.GetUsers()
// Clear all custom headers
client.CustomHeaders = make(map[string]string)Note: Custom headers will override any existing headers with the same name, except for Content-Type and Authorization headers which are managed by the SDK.
The SDK provides complete OAuth 2.0 authentication flow support.
Direct users to your Casdoor login page:
https://your-casdoor-instance.com/login/oauth/authorize?client_id=CLIENT_ID&response_type=code&redirect_uri=REDIRECT_URI&scope=read&state=STATE
After successful authentication, Casdoor redirects back to your application with code and state parameters:
// Extract code and state from the callback URL
code := r.URL.Query().Get("code")
state := r.URL.Query().Get("state")
// Exchange code for access token
token, err := casdoorsdk.GetOAuthToken(code, state)
if err != nil {
panic(err)
}
// Parse the JWT token to get user information
claims, err := casdoorsdk.ParseJwtToken(token.AccessToken)
if err != nil {
panic(err)
}
// Store the access token in claims for future use
claims.AccessToken = token.AccessTokenAfter getting user information, store it in your session:
import "encoding/json"
data, err := json.Marshal(claims)
if err != nil {
panic(err)
}
// Store in session (implementation depends on your session management)
session.Set("user", data)Refresh an expired access token using the refresh token:
newToken, err := casdoorsdk.RefreshOAuthToken(refreshToken)
if err != nil {
panic(err)
}Parse and validate JWT tokens:
claims, err := casdoorsdk.ParseJwtToken(accessToken)
if err != nil {
panic(err)
}
// Access user information
fmt.Printf("User: %s\n", claims.Name)
fmt.Printf("Email: %s\n", claims.Email)
fmt.Printf("Organization: %s\n", claims.Owner)The SDK provides comprehensive APIs to manage various resources in Casdoor.
// Get all users in your organization
users, err := casdoorsdk.GetUsers()
// Get a specific user by name
user, err := casdoorsdk.GetUser("username")
// Get user by email
user, err := casdoorsdk.GetUserByEmail("user@example.com")
// Get user by phone number
user, err := casdoorsdk.GetUserByPhone("+1234567890")
// Get paginated users
users, totalCount, err := casdoorsdk.GetPaginationUsers(
1, // page number
10, // page size
map[string]string{}, // query filters
)
// Create a new user
user := &casdoorsdk.User{
Owner: "my-organization",
Name: "new-user",
DisplayName: "New User",
Email: "newuser@example.com",
Phone: "+1234567890",
Password: "password123",
}
success, err := casdoorsdk.AddUser(user)
// Update an existing user
user.DisplayName = "Updated Name"
success, err := casdoorsdk.UpdateUser(user)
// Update specific user fields
success, err := casdoorsdk.UpdateUserForColumns(user, []string{"displayName", "email"})
// Delete a user
success, err := casdoorsdk.DeleteUser(user)
// Set/change user password
success, err := casdoorsdk.SetPassword("owner", "username", "oldPassword", "newPassword")
// Get user count
count, err := casdoorsdk.GetUserCount("1") // "1" for online users, "0" for all users// Get all organizations
orgs, err := casdoorsdk.GetOrganizations()
// Get a specific organization
org, err := casdoorsdk.GetOrganization("org-name")
// Add a new organization
org := &casdoorsdk.Organization{
Name: "new-org",
DisplayName: "New Organization",
// ... other fields
}
success, err := casdoorsdk.AddOrganization(org)
// Update an organization
success, err := casdoorsdk.UpdateOrganization(org)
// Delete an organization
success, err := casdoorsdk.DeleteOrganization(org)// Get all roles
roles, err := casdoorsdk.GetRoles()
// Get a specific role
role, err := casdoorsdk.GetRole("role-name")
// Add a new role
role := &casdoorsdk.Role{
Owner: "my-organization",
Name: "admin",
DisplayName: "Administrator",
Users: []string{"user1", "user2"},
IsEnabled: true,
}
success, err := casdoorsdk.AddRole(role)
// Update a role
success, err := casdoorsdk.UpdateRole(role)
// Delete a role
success, err := casdoorsdk.DeleteRole(role)// Get all permissions
permissions, err := casdoorsdk.GetPermissions()
// Get a specific permission
permission, err := casdoorsdk.GetPermission("permission-name")
// Add a new permission
permission := &casdoorsdk.Permission{
Owner: "my-organization",
Name: "read-permission",
DisplayName: "Read Permission",
Resources: []string{"resource1", "resource2"},
Actions: []string{"read", "list"},
Effect: "Allow",
IsEnabled: true,
}
success, err := casdoorsdk.AddPermission(permission)
// Update a permission
success, err := casdoorsdk.UpdatePermission(permission)
// Delete a permission
success, err := casdoorsdk.DeletePermission(permission)
// Enforce permission check
allowed, err := casdoorsdk.Enforce("user", "resource", "action")// Get all applications
apps, err := casdoorsdk.GetApplications()
// Get a specific application
app, err := casdoorsdk.GetApplication("app-name")
// Add a new application
app := &casdoorsdk.Application{
Owner: "my-organization",
Name: "my-app",
DisplayName: "My Application",
// ... other configuration
}
success, err := casdoorsdk.AddApplication(app)
// Update an application
success, err := casdoorsdk.UpdateApplication(app)
// Delete an application
success, err := casdoorsdk.DeleteApplication(app)// Get all sessions
sessions, err := casdoorsdk.GetSessions()
// Get a specific session
session, err := casdoorsdk.GetSession("session-id")
// Delete a session
success, err := casdoorsdk.DeleteSession(session)Manage third-party authentication providers (OAuth, SAML, etc.):
// Get all providers
providers, err := casdoorsdk.GetProviders()
// Get a specific provider
provider, err := casdoorsdk.GetProvider("provider-name")
// Add, update, or delete providers
success, err := casdoorsdk.AddProvider(provider)
success, err := casdoorsdk.UpdateProvider(provider)
success, err := casdoorsdk.DeleteProvider(provider)// Get all certificates
certs, err := casdoorsdk.GetCertificates()
// Get a specific certificate
cert, err := casdoorsdk.GetCertificate("cert-name")
// Add, update, or delete certificates
success, err := casdoorsdk.AddCertificate(cert)
success, err := casdoorsdk.UpdateCertificate(cert)
success, err := casdoorsdk.DeleteCertificate(cert)// Send email
err := casdoorsdk.SendEmail("Email Title", "email-content", "sender@example.com", "receiver@example.com")
// Send SMS
err := casdoorsdk.SendSms("randomCode", "+1234567890")// Get all tokens
tokens, err := casdoorsdk.GetTokens()
// Get a specific token
token, err := casdoorsdk.GetToken("owner", "token-name")
// Update or delete tokens
success, err := casdoorsdk.UpdateToken(token)
success, err := casdoorsdk.DeleteToken(token)Upload and manage resources (files, images, etc.):
// Upload a resource
success, resource, err := casdoorsdk.UploadResource(
"user",
"tag",
"parent",
"fullFilePath",
fileBuffer,
)
// Delete a resource
success, err := casdoorsdk.DeleteResource(resource)// Get all webhooks
webhooks, err := casdoorsdk.GetWebhooks()
// Get a specific webhook
webhook, err := casdoorsdk.GetWebhook("webhook-name")
// Add, update, or delete webhooks
success, err := casdoorsdk.AddWebhook(webhook)
success, err := casdoorsdk.UpdateWebhook(webhook)
success, err := casdoorsdk.DeleteWebhook(webhook)The SDK provides comprehensive support for managing the following Casdoor resources:
| Resource | Description | Key Operations |
|---|---|---|
| User | User accounts and profiles | CRUD, authentication, password |
| Organization | Organization entities | CRUD operations |
| Application | Application configurations | CRUD operations |
| Role | User roles | CRUD, assignment |
| Permission | Access permissions | CRUD, enforcement |
| Provider | Third-party authentication providers | CRUD operations |
| Token | Access and refresh tokens | Get, update, delete |
| Certificate | SSL/TLS certificates | CRUD operations |
| Session | User sessions | Get, delete |
| Webhook | Event webhooks | CRUD operations |
| Group | User groups | CRUD operations |
| Syncer | User synchronization from external systems | CRUD operations |
| Adapter | Policy adapters | CRUD operations |
| Enforcer | Policy enforcers | CRUD operations |
| Model | Policy models | CRUD operations |
| Policy | Access control policies | CRUD operations |
| Payment | Payment records | CRUD operations |
| Product | Products/services | CRUD operations |
| Subscription | User subscriptions | CRUD operations |
| Plan | Subscription plans | CRUD operations |
| Pricing | Pricing configurations | CRUD operations |
| Transaction | Payment transactions | CRUD operations |
| Resource | File and media resources | Upload, delete |
| Invitation | User invitations | CRUD operations |
| Record | Audit and activity records | Get operations |
Most resources follow consistent method patterns:
Get{Resource}s()- Get all resourcesGet{Resource}(name)- Get a specific resourceAdd{Resource}(resource)- Create a new resourceUpdate{Resource}(resource)- Update an existing resourceDelete{Resource}(resource)- Delete a resource
package main
import (
"encoding/json"
"fmt"
"net/http"
"github.com/casdoor/casdoor-go-sdk/casdoorsdk"
)
func main() {
// Initialize SDK
casdoorsdk.InitConfig(
"http://localhost:8000",
"CLIENT_ID",
"CLIENT_SECRET",
"CERTIFICATE",
"my-organization",
"my-app",
)
// Handle OAuth callback
http.HandleFunc("/callback", func(w http.ResponseWriter, r *http.Request) {
code := r.URL.Query().Get("code")
state := r.URL.Query().Get("state")
token, err := casdoorsdk.GetOAuthToken(code, state)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
claims, err := casdoorsdk.ParseJwtToken(token.AccessToken)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Store in session
response, err := json.Marshal(claims)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(response)
})
http.ListenAndServe(":8080", nil)
}package main
import (
"fmt"
"github.com/casdoor/casdoor-go-sdk/casdoorsdk"
)
func main() {
casdoorsdk.InitConfig("http://localhost:8000", "CLIENT_ID", "CLIENT_SECRET", "CERT", "org", "app")
// Create a new user
newUser := &casdoorsdk.User{
Owner: "my-organization",
Name: "john_doe",
DisplayName: "John Doe",
Email: "john@example.com",
Password: "secure_password",
}
success, err := casdoorsdk.AddUser(newUser)
if err != nil {
panic(err)
}
fmt.Printf("User created: %v\n", success)
// Get and update user
user, err := casdoorsdk.GetUser("john_doe")
if err != nil {
panic(err)
}
user.DisplayName = "John D."
success, err = casdoorsdk.UpdateUser(user)
if err != nil {
panic(err)
}
fmt.Printf("User updated: %v\n", success)
}package main
import (
"fmt"
"github.com/casdoor/casdoor-go-sdk/casdoorsdk"
)
func main() {
casdoorsdk.InitConfig("http://localhost:8000", "CLIENT_ID", "CLIENT_SECRET", "CERT", "org", "app")
// Check if user has permission
allowed, err := casdoorsdk.Enforce("user123", "resource1", "read")
if err != nil {
panic(err)
}
if allowed {
fmt.Println("Access granted")
} else {
fmt.Println("Access denied")
}
}For more detailed information, please refer to:
This project is licensed under the Apache License 2.0 - see the LICENSE file for details.
If you find this project useful, please consider giving it a star! β