17370845950

Golang如何实现用户登录功能_Golang 用户登录功能实践
使用Golang实现用户登录需定义User结构体并用SQLite存储,密码通过bcrypt哈希;2. 登录接口验证用户名密码,正确后设置Session Cookie;3. 通过中间件检查Session有效性以保护受控路由;4. 安全措施包括HTTPS、Cookie加密、Session过期与CSRF防护。

实现用户登录功能是大多数 Web 应用的基础需求。在 Golang 中,通过标准库 net/http 搭配合理的结构设计,可以高效、安全地完成这一功能。下面是一个实用的用户登录实现方案,涵盖路由处理、密码验证、Session 管理和基础安全措施。

1. 用户模型与数据库准备

定义一个简单的用户结构体,并使用 SQLite 或 MySQL 存储用户信息。示例使用 SQLite 和 database/sql 接口:

type User struct {
    ID       int
    Username string
    Password string // 实际存储应为哈希值
}

建表语句示例:

CREATE TABLE users (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    username TEXT UNIQUE NOT NULL,
    password TEXT NOT NULL
);

注册时使用 golang.org/x/crypto/bcrypt 对密码进行哈希:

import "golang.org/x/crypto/bcrypt"

hashed, _ := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)

2. 登录接口处理

编写登录处理器,接收用户名密码,验证后设置 Session:

func loginHandler(w http.ResponseWriter, r *http.Request) {
    if r.Method != "POST" {
        http.Error(w, "Method not allowed", 405)
        return
    }

    username := r.FormValue("username")
    password := r.FormValue("password")

    var user User
    err := db.QueryRow("SELECT id, username, password FROM users WHERE username = ?", username).
        Scan(&user.ID, &user.Username, &user.Password)

    if err != nil {
        http.Error(w, "Invalid credentials", 401)
        return
    }

    if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password)); err != nil {
        http.Error(w, "Invalid credentials", 401)
        return
    }

    // 设置 session(示例使用简单 cookie)
    sessionToken := generateSessionToken()
    http.SetCookie(w, &http.Cookie{
        Name:  "session_token",
        Value: sessionToken,
        Path:  "/",
    })

    // 可选:将 token 存入内存或 Redis 关联用户
    sessions[sessionToken] = user.ID

    w.Write([]byte("Login successful"))
}

3. Session 与身份验证中间件

通过中间件检查请求是否携带有效 Session,保护需要登录的接口:

func authMiddleware(next http.HandlerFunc) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        cookie, err := r.Cookie("session_token")
        if err != nil {
            http.Redirect(w, r, "/login", 302)
            return
        }

        userID, exists := sessions[cookie.Value]
        if !exists {
            http.Redirect(w, r, "/login", 302)
            return
        }

        // 将用户信息传递给后续处理函数
        ctx := context.WithValue(r.Context(), "userID", userID)
        next.ServeHTTP(w, r.WithContext(ctx))
    }
}

使用方式:

http.HandleFunc("/dashboard", authMiddleware(dashboardHandler))

4. 安全建议

  • 密码加密:永远不要明文存储密码,使用 bcrypt 或 argon2。
  • HTTPS:生产环境必须启用 HTTPS 防止 Cookie 被窃取。
  • Session 过期:为 Cookie 设置 MaxAge,定期清理过期 Session。
  • CSRF 防护:对关键操作添加 CSRF Token 验证。
  • 输入校验:限制用户名长度,过滤特殊字符。

基本上就这些。Golang 实现登录不复杂,关键是把每一步做扎实:安全存密码、合理管理会话、防止常见攻击。实际项目中可结合 Gin/Echo 框架提升开发效率,但底层逻辑不变。