Getting started overview
Micro User Service is designed for managing users, authentication, and authorization within distributed systems and microservices architectures. Getting started involves creating an account with Micro, configuring the local development environment, and making a first API call to interact with user data. The platform provides SDKs for Go and JavaScript, along with a CLI tool to facilitate these operations. This guide focuses on the initial configuration and a fundamental request to ensure successful integration.
Before proceeding, ensure you have a working development environment set up for either Go or JavaScript, including the respective package manager (Go Modules for Go, npm or yarn for JavaScript) and the Micro CLI, which is central to interacting with Micro services locally and in the cloud. The Micro CLI can be installed by following the Micro User Service documentation.
The following table outlines the key steps to get started with Micro User Service:
| Step | What to Do | Where |
|---|---|---|
| 1. Create Account | Register for a Micro Cloud account. | Micro Homepage |
| 2. Install CLI | Download and install the Micro Command Line Interface. | Micro User Service documentation |
| 3. Initialize Project | Create a new Micro project or configure an existing one. | Local terminal (using micro new or micro init) |
| 4. Obtain API Token | Generate a service token for authentication. | Micro Cloud dashboard or micro login / micro token CLI commands |
| 5. Make First Request | Use an SDK or the CLI to perform a user-related operation. | Code editor (Go/JavaScript) or local terminal |
Create an account and get keys
Access to Micro User Service typically begins with creating an account on the Micro Cloud platform or setting up a local Micro environment. A Micro Cloud account provides access to hosted services and simplifies key management. If you opt for Micro Cloud, navigate to the Micro homepage and follow the registration process. This usually involves providing an email address and setting a password.
Once your account is active, you will need to authenticate your local Micro CLI with your account. This is done by running micro login in your terminal. The CLI will guide you through the authentication process, typically by opening a browser window for you to sign in to your Micro Cloud account. Upon successful authentication, the CLI stores credentials locally, allowing it to interact with your Micro Cloud services.
For programmatic access, Micro services, including the User Service, rely on authentication tokens. While specific API keys like those found in traditional REST APIs might not be explicitly generated in the same fashion, the micro login process establishes the necessary credentials for the CLI and, by extension, your services to communicate securely. For service-to-service authentication or more granular access control, Micro provides mechanisms for creating and managing service tokens. You can generate a service token using the micro token create command after logging in, specifying the scope and expiry as needed. This token would then be used by your application or service to authenticate with the User Service. The Micro User Service API documentation details the token-based authentication methods.
It's important to manage these tokens securely. Best practices for API key management, such as storing tokens in environment variables or secure secret management systems, are applicable. For instance, Google Cloud's API key best practices provide a general framework for securing API credentials that can be adapted.
Your first request
After setting up your account and authenticating your CLI, you can make your first request to the Micro User Service. This example demonstrates creating a new user using the Go SDK. Ensure you have Go installed and the Micro CLI configured.
First, create a new Go module for your project:
mkdir my-user-app
cd my-user-app
go mod init my-user-app
micro new service myuser --output .
This command initializes a new Micro service project. Next, you'll modify the generated main.go file to interact with the User Service. You'll need to add the Micro User Service client library to your project. Add the following to your go.mod file or run go get go.micro.mu/micro/v3/service/user:
// main.go
package main
import (
"context"
"log"
"go.micro.mu/micro/v3/client"
user "go.micro.mu/micro/v3/service/user"
)
func main() {
// Create a new client
c := client.NewClient()
// Create a new user service client
userService := user.NewUserService("user", c)
// Define user details
createUserReq := &user.CreateRequest{
Email: "[email protected]",
Password: "SecurePassword123!",
Profile: &user.Profile{
FirstName: "Test",
LastName: "User",
},
}
// Call the Create method
resp, err := userService.Create(context.TODO(), createUserReq)
if err != nil {
log.Fatalf("Failed to create user: %v", err)
}
log.Printf("User created successfully. User ID: %s", resp.GetUser().GetId())
// Example: Read the created user
readUserReq := &user.ReadRequest{
Id: resp.GetUser().GetId(),
}
readResp, err := userService.Read(context.TODO(), readUserReq)
if err != nil {
log.Fatalf("Failed to read user: %v", err)
}
log.Printf("Read user: %s (Email: %s)", readResp.GetUser().GetProfile().GetFirstName(), readResp.GetUser().GetEmail())
}
To run this code, you need to have the Micro environment running, or be connected to Micro Cloud. If running locally, you can start the Micro runtime:
micro server
Then, build and run your Go application:
go run main.go
The output should indicate that the user was created successfully and then read back. This confirms your setup and basic interaction with the Micro User Service.
For JavaScript developers, the process is similar. First, initialize a new Node.js project and install the Micro JavaScript client:
mkdir my-js-user-app
cd my-js-user-app
npm init -y
npm install @micro/micro
Then, create an index.js file:
// index.js
const { Client, User } = require('@micro/micro');
const client = new Client();
const userService = User.NewUserService('user', client);
async function createUserAndRead() {
try {
const createReq = {
email: "[email protected]",
password: "SecurePassword123!",
profile: {
firstName: "JS Test",
lastName: "User",
},
};
const createResp = await userService.create(createReq);
console.log(`User created successfully. User ID: ${createResp.user.id}`);
const readReq = {
id: createResp.user.id,
};
const readResp = await userService.read(readReq);
console.log(`Read user: ${readResp.user.profile.firstName} (Email: ${readResp.user.email})`);
} catch (error) {
console.error(`Failed to interact with user service: ${error.message}`);
}
}
createUserAndRead();
Run the JavaScript application:
node index.js
This will execute the same logic, demonstrating user creation and retrieval using the JavaScript SDK.
Common next steps
After successfully making your first request, consider these common next steps to expand your usage of Micro User Service:
- Explore other User Service APIs: The User Service offers additional functionalities such as updating user profiles, listing users, and managing user deletion. Refer to the Micro User Service API reference for a complete list of available methods and their parameters.
- Integrate with Micro Auth Service: For robust authentication flows, integrate the User Service with the Micro Auth Service. This allows for session management, token validation, and single sign-on capabilities, which are crucial for secure applications. The Micro Auth documentation provides details on this integration.
- Implement role-based access control (RBAC): Micro User Service can be used in conjunction with other Micro capabilities to implement granular permission management. Define roles and assign them to users, then check permissions within your application logic before allowing access to resources. This is a fundamental aspect of secure multi-tenant applications.
- Deploy to Micro Cloud: Once your service is developed, deploy it to Micro Cloud for a managed, scalable environment. The Micro CLI provides commands like
micro runormicro deployto streamline this process. - Set up environment variables for credentials: Instead of hardcoding credentials, store them securely in environment variables or a secret management system. This is a standard security practice for production applications.
- Error Handling and Logging: Implement comprehensive error handling and logging to diagnose issues effectively. Micro services typically output logs that can be monitored via the Micro CLI or cloud dashboard.
Troubleshooting the first call
Encountering issues during your first API call is common. Here are some troubleshooting steps:
- Check Micro Server Status: Ensure the Micro server (runtime) is running. If you are running locally, execute
micro server. If using Micro Cloud, verify your connection and service status via the Micro dashboard. - Verify Authentication: Confirm that your Micro CLI is logged in and that any service tokens used are valid and have the necessary permissions. Use
micro loginto re-authenticate ormicro token listto check token validity. - Network Connectivity: Ensure your development machine has network access to the Micro services, whether local or cloud-hosted. Firewall rules or proxy settings can sometimes block connections.
- Correct Service Name: Double-check that the service name used in your client initialization (e.g.,
user.NewUserService("user", c)) matches the actual name of the User Service instance you are trying to connect to. The default is typicallyuser. - SDK and CLI Versions: Incompatibilities can arise from mismatched SDK or CLI versions. Ensure you are using recent and compatible versions as recommended in the Micro User Service documentation. Update your CLI with
micro update. - Review Logs: The Micro server and your application will generate logs. Examine these logs for specific error messages that can pinpoint the problem. For local development, these logs are often printed to the console where
micro serveris running. - Firewall Issues: If running Micro services locally, ensure your operating system's firewall is not blocking communication between your application and the Micro runtime.
- Resource Limits (Free Tier): If using the Micro Cloud free tier, check if you have exceeded any rate limits or storage quotas. These limits are detailed on the Micro User Service homepage.