最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

authentication - Using Clerk with Gin for Protected Routes to Retrieve Appointments - Stack Overflow

programmeradmin3浏览0评论

I'm building a SaaS application for professional masseurs using Gin in Go, and I want to integrate Clerk for authentication. I need to protect some routes (e.g., GET /api/appointments) so that only authenticated users can access them, and then retrieve appointments from my PostgreSQL database

I've set up Clerk using their Go SDK and currently have a basic HTTP server using the standard library's ServeMux that protects a sample /protected route with Clerk's WithHeaderAuthorization() middleware. Here's an example of that code:

package main

import (
    "fmt"
    "net/http"
    "strings"

    "github/clerk/clerk-sdk-go/v2"
    "github/clerk/clerk-sdk-go/v2/jwt"
    "github/clerk/clerk-sdk-go/v2/user"
)

func main() {
    clerk.SetKey("sk_test_X1nrGSq5xHvjhIusKfQA3J6v6QMIjTAm6XscRJKRL5")

    mux := http.NewServeMux()
    mux.HandleFunc("/", publicRoute)
    mux.HandleFunc("/protected", protectedRoute)

    http.ListenAndServe(":3000", mux)
}

func publicRoute(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte(`{"access": "public"}`))
}

func protectedRoute(w http.ResponseWriter, r *http.Request) {
    sessionToken := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")

    claims, err := jwt.Verify(r.Context(), &jwt.VerifyParams{
        Token: sessionToken,
    })
    if err != nil {
        w.WriteHeader(http.StatusUnauthorized)
        w.Write([]byte(`{"access": "unauthorized"}`))
        return
    }

    usr, err := user.Get(r.Context(), claims.Subject)
    if err != nil {
        // Handle error accordingly.
    }
    fmt.Fprintf(w, `{"user_id": "%s", "user_banned": "%t"}`, usr.ID, usr.Banned)
}

Now I want to switch over to using Gin (instead of the default mux) so I can add additional routes such as:

  • GET /api/appointments
  • POST /api/appointments
  • PUT /api/appointments/:id
  • DELETE /api/appointments/:id

These routes should be protected by Clerk. I already have my PostgreSQL connection and CRUD endpoints set up in my Gin server.

My question:

How can I modify this code to use Gin instead of ServeMux, and add the CRUD routes for appointments (GET, POST, PUT, DELETE) under a protected route group (e.g., /api/appointments) that uses Clerk middleware? Any code examples or guidance on adapting Clerk’s middleware for Gin would be much appreciated.

发布评论

评论列表(0)

  1. 暂无评论