Skip to content

用户认证

用户认证模块提供用户注册、登录、身份验证等功能。

接口概览

方法路径描述权限要求
POST/api/v1/auth/register用户注册
POST/api/v1/auth/login用户登录

用户注册

创建新用户账号。

接口信息

  • URL: /api/v1/auth/register
  • 方法: POST
  • 内容类型: application/json

请求参数

字段类型必填描述示例
usernamestring用户名"johndoe"
emailstring邮箱地址"john@example.com"
passwordstring密码(至少6位)"password123"
phonestring手机号码"13800138000"

请求示例

json
{
  "username": "johndoe",
  "email": "john@example.com",
  "password": "password123",
  "phone": "13800138000"
}

响应示例

成功响应 (201)

json
{
  "code": 201,
  "message": "注册成功",
  "data": {
    "id": 1,
    "username": "johndoe",
    "email": "john@example.com",
    "phone": "13800138000",
    "status": 1,
    "created_at": "2024-01-01T12:00:00Z"
  },
  "timestamp": "2024-01-01T12:00:00Z"
}

错误响应 (400)

json
{
  "code": 400,
  "message": "请求参数错误",
  "error": "邮箱已被注册",
  "timestamp": "2024-01-01T12:00:00Z"
}

用户登录

使用用户名/邮箱和密码进行登录。

接口信息

  • URL: /api/v1/auth/login
  • 方法: POST
  • 内容类型: application/json

请求参数

字段类型必填描述示例
usernamestring用户名或邮箱"johndoe" 或 "john@example.com"
passwordstring密码"password123"

请求示例

json
{
  "username": "john@example.com",
  "password": "password123"
}

响应示例

成功响应 (200)

json
{
  "code": 200,
  "message": "登录成功",
  "data": {
    "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c",
    "user": {
      "id": 1,
      "username": "johndoe",
      "email": "john@example.com",
      "phone": "13800138000",
      "status": 1,
      "roles": ["employee"]
    }
  },
  "timestamp": "2024-01-01T12:00:00Z"
}

错误响应 (401)

json
{
  "code": 401,
  "message": "认证失败",
  "error": "用户名或密码错误",
  "timestamp": "2024-01-01T12:00:00Z"
}

使用 Token

登录成功后,获得 JWT token,需要在后续 API 请求中携带:

bash
# 在 HTTP Header 中添加
Authorization: Bearer <your-jwt-token>

示例

bash
curl -X GET http://localhost:8080/api/v1/users/profile \
  -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."

Token 有效期

  • 有效期: 24 小时
  • 过期处理: 重新登录获取新 token
  • 存储建议: 使用安全的存储方式(如 httpOnly cookies)

错误代码

错误代码描述解决方案
400请求参数错误检查请求参数格式和必填字段
401认证失败检查用户名/密码是否正确
409邮箱已被注册使用其他邮箱地址
500服务器内部错误联系系统管理员

安全注意事项

  1. 密码安全: 密码使用 bcrypt 加密存储
  2. 传输安全: 建议使用 HTTPS 传输
  3. Token 安全:
    • 不要在客户端长期存储
    • 定期更换 token
    • 避免在 URL 中传递

集成示例

JavaScript

javascript
class AuthAPI {
  // 用户注册
  static async register(userData) {
    const response = await fetch('/api/v1/auth/register', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(userData)
    });

    const data = await response.json();
    if (data.code === 201) {
      return data.data;
    }
    throw new Error(data.message);
  }

  // 用户登录
  static async login(username, password) {
    const response = await fetch('/api/v1/auth/login', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ username, password })
    });

    const data = await response.json();
    if (data.code === 200) {
      localStorage.setItem('token', data.data.token);
      return data.data;
    }
    throw new Error(data.message);
  }

  // 检查登录状态
  static isLoggedIn() {
    return !!localStorage.getItem('token');
  }

  // 获取当前 token
  static getToken() {
    return localStorage.getItem('token');
  }

  // 登出
  static logout() {
    localStorage.removeItem('token');
  }
}

// 使用示例
try {
  const result = await AuthAPI.login('john@example.com', 'password123');
  console.log('登录成功:', result.user);
} catch (error) {
  console.error('登录失败:', error.message);
}

Go

go
package main

import (
    "bytes"
    "encoding/json"
    "net/http"
)

type AuthClient struct {
    BaseURL string
    Token   string
    Client  *http.Client
}

type LoginRequest struct {
    Username string `json:"username"`
    Password string `json:"password"`
}

type LoginResponse struct {
    Code    int `json:"code"`
    Message string `json:"message"`
    Data    struct {
        Token string `json:"token"`
        User  User  `json:"user"`
    } `json:"data"`
}

func NewAuthClient(baseURL string) *AuthClient {
    return &AuthClient{
        BaseURL: baseURL,
        Client:  &http.Client{},
    }
}

func (c *AuthClient) Login(username, password string) (*LoginResponse, error) {
    loginReq := LoginRequest{
        Username: username,
        Password: password,
    }

    jsonData, _ := json.Marshal(loginReq)

    resp, err := c.Client.Post(
        c.BaseURL+"/api/v1/auth/login",
        "application/json",
        bytes.NewBuffer(jsonData),
    )
    if err != nil {
        return nil, err
    }
    defer resp.Body.Close()

    var loginResp LoginResponse
    if err := json.NewDecoder(resp.Body).Decode(&loginResp); err != nil {
        return nil, err
    }

    if loginResp.Code == 200 {
        c.Token = loginResp.Data.Token
    }

    return &loginResp, nil
}

func (c *AuthClient) MakeRequest(method, url string, body []byte) (*http.Response, error) {
    req, err := http.NewRequest(method, c.BaseURL+url, bytes.NewBuffer(body))
    if err != nil {
        return nil, err
    }

    req.Header.Set("Authorization", "Bearer "+c.Token)
    req.Header.Set("Content-Type", "application/json")

    return c.Client.Do(req)
}

相关链接

基于 MIT 许可发布