Authentication overview
Micro User Service provides user management capabilities within the broader Micro platform, a framework for building distributed systems. Authentication for the Micro User Service is handled in conjunction with the Micro Auth Service, which underpins the security model for all Micro platform components. This integrated approach ensures consistent security policies and streamlined credential management across microservices. Developers interact with the Micro User Service and its authentication mechanisms primarily through the Micro CLI and dedicated SDKs for Go and JavaScript.
The core principle involves verifying the identity of a user or a service attempting to access resources managed by the Micro User Service. This typically involves presenting a credential, such as an API token or a session identifier, which the Micro Auth Service validates. Upon successful validation, the authenticated entity is granted access based on its associated permissions. The system is designed to support various deployment scenarios, from local development to production-grade distributed environments, making authentication a critical component of its operational security.
Supported authentication methods
Micro User Service leverages the Micro Auth Service to provide robust authentication options suitable for microservices architectures. The primary methods supported are API tokens for programmatic access and session-based authentication for interactive user flows. These methods are designed to integrate seamlessly with the Micro API Gateway and other Micro services.
API tokens are generally used for machine-to-machine communication or when an application needs to interact with the Micro User Service programmatically without direct user intervention. These tokens are typically long-lived and require careful management to prevent unauthorized access. Session-based authentication, on the other hand, is more common for user-facing applications where a user logs in and establishes a temporary, stateful session.
The Micro Auth Service supports industry-standard protocols like OAuth 2.0 for delegated authorization and JSON Web Tokens (JWTs) for secure information exchange. While the Micro User Service itself consumes these authenticated identities, the underlying mechanisms are managed by the Auth Service. This separation of concerns allows the User Service to focus on user data management while relying on a specialized service for identity verification.
The table below outlines the primary authentication methods and their typical use cases within the Micro ecosystem:
| Method | When to Use | Security Level |
|---|---|---|
| API Tokens (JWT-based) | Programmatic access, service-to-service communication, CLI interactions, long-lived integrations. | High (requires secure storage and rotation) |
| Session-based (via Micro Auth Service) | User-facing applications, web and mobile client authentication, interactive logins. | High (requires secure session management) |
| OAuth 2.0 (via Micro Auth Service) | Delegated authorization to third-party applications, integrating with external identity providers. | High (standardized, secure delegation) |
Getting your credentials
To authenticate with the Micro User Service, you will typically need to obtain credentials from the Micro platform. The specific steps depend on whether you are authenticating as a user or a service, and whether you are using the Micro Cloud or a self-hosted Micro environment.
For Micro Cloud Users:
- Sign Up/Log In to Micro Cloud: Access the Micro Cloud Dashboard.
- Generate API Keys: Within the dashboard, navigate to the 'Settings' or 'API Keys' section. Here, you can generate new API tokens. These tokens are crucial for programmatic access to your Micro services, including the User Service. Ensure you store these keys securely, as they grant significant access.
- CLI Login: Use the Micro CLI to log in to your Micro Cloud account. This process typically involves running
micro loginand following the prompts, which might open a browser for OAuth-based authentication. Once logged in, the CLI manages your session token for subsequent commands.
For Self-Hosted Micro Environments:
- Deploy Micro Auth Service: Ensure the Micro Auth Service is properly deployed and configured within your self-hosted Micro cluster. This service is responsible for issuing and validating credentials. Refer to the Micro Auth Service documentation for deployment details.
- Create Service Accounts/Users: Use the Micro CLI or the Micro Dashboard (if deployed) to create service accounts or user accounts. For service accounts, you can generate API tokens directly. For user accounts, the Auth Service will manage session creation upon successful login.
- Configure Auth Service Endpoints: Ensure your applications are configured to communicate with your self-hosted Micro Auth Service's endpoints for token issuance and validation.
Regardless of your deployment model, it is critical to treat all generated credentials as sensitive information. Compromised credentials can lead to unauthorized access to your user data and other Micro services.
Authenticated request example
Authenticating requests to the Micro User Service typically involves including an API token in the request headers. The following examples demonstrate how to make an authenticated request using the Micro Go SDK and a direct HTTP request with a JWT. These examples assume you have already obtained an API token.
Go SDK Example:
When using the Go SDK, authentication is often handled implicitly after you configure the client with your credentials or log in via the CLI. However, for direct service calls, you might configure a client with a token.
package main
import (
"context"
"fmt"
"log"
"go.micro.mu/api/user"
"go.micro.mu/client"
)
func main() {
// Initialize a Micro client with an API token
// In a real application, obtain this token securely (e.g., from environment variables)
apiToken := "YOUR_MICRO_API_TOKEN"
// Create a new client. The client will use the provided token for authentication.
// For Micro Cloud, the client automatically handles token refreshing if configured.
cl := client.NewClient(
client.AuthToken(apiToken),
)
// Create a User Service client using the initialized Micro client
userService := user.NewUserService("user", cl)
// Call a method on the User Service, e.g., Read a user by ID
resp, err := userService.Read(context.TODO(), &user.ReadRequest{
Id: "user-id-123",
})
if err != nil {
log.Fatalf("Failed to read user: %v", err)
}
fmt.Printf("Successfully read user: %v\n", resp.GetUser().GetUsername())
}
HTTP Request Example (using cURL):
For direct HTTP interactions, you would include your API token (often a JWT) in the Authorization header using the Bearer scheme. This is common when integrating with the Micro API Gateway or when debugging.
curl -X GET \
"https://api.micro.mu/user/read" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_MICRO_API_TOKEN" \
-d '{ "id": "user-id-123" }'
Replace YOUR_MICRO_API_TOKEN with your actual API token and user-id-123 with the ID of the user you wish to retrieve. The endpoint https://api.micro.mu is for Micro Cloud; self-hosted deployments will use their configured API Gateway URL.
Security best practices
Securing access to the Micro User Service is crucial for protecting sensitive user data and maintaining the integrity of your distributed system. Adhering to established security best practices can mitigate common vulnerabilities.
- Secure Credential Storage: Never hardcode API tokens or other sensitive credentials directly into your application code. Utilize environment variables, secret management services (e.g., AWS Secrets Manager, Google Secret Manager), or secure configuration files. For client-side applications, avoid storing long-lived tokens in local storage; prefer HTTP-only cookies for session tokens.
- Token Rotation and Expiration: Implement a policy for regularly rotating API tokens. Short-lived tokens with frequent rotation reduce the window of opportunity for attackers if a token is compromised. Configure appropriate expiration times for JWTs and session tokens to limit their validity.
- Least Privilege Principle: Grant only the minimum necessary permissions to users and services interacting with the Micro User Service. For example, a service that only needs to read user profiles should not be given permissions to create or delete users. Micro's role-based access control (RBAC) features, managed through the Auth Service, can help enforce this principle.
- Input Validation and Sanitization: While authentication verifies identity, robust input validation and sanitization are essential to prevent injection attacks (e.g., SQL injection, XSS) when interacting with user data. Ensure all data sent to and received from the User Service is properly validated against expected formats and sanitized before processing or display.
- HTTPS/TLS Everywhere: Always use HTTPS (TLS) for all communication with the Micro User Service and the Micro API Gateway. This encrypts data in transit, protecting credentials and user information from eavesdropping. Micro services are designed to operate securely over TLS, and it should be enabled in all production deployments.
- Logging and Monitoring: Implement comprehensive logging for authentication attempts, access failures, and critical actions performed via the Micro User Service. Regularly monitor these logs for suspicious patterns, such as repeated failed login attempts or unusual access patterns, which could indicate a security incident.
- Regular Security Audits: Conduct periodic security audits and penetration tests on your Micro deployment, including the User Service and its authentication flows. This helps identify and address vulnerabilities before they can be exploited.
- Multi-Factor Authentication (MFA): Where applicable for user-facing applications, enable multi-factor authentication through the Micro Auth Service. MFA adds an extra layer of security by requiring users to provide two or more verification factors to gain access.
- Stay Updated: Keep your Micro platform components, including the User Service and Auth Service, updated to the latest stable versions. Updates often include critical security patches and improvements.
By integrating these practices into your development and operational workflows, you can significantly enhance the security posture of your Micro User Service implementation and safeguard your user data.