Library for integrating a Go Gin project with sf-auth
| sfauthgin | ||
| .envrc | ||
| .gitignore | ||
| devenv.lock | ||
| devenv.nix | ||
| devenv.yaml | ||
| go.mod | ||
| go.sum | ||
| README.md | ||
| requirements.md | ||
sf-auth-gin-middleware
This project provides a small Go library that integrates the Snazzyfellas sf-auth redirect flow with the Gin web framework. It exposes a middleware that enforces authenticated sessions and a prebuilt callback handler that validates sf-auth keys, stores user data in the session, and redirects back to your application.
Usage
package main
import (
"net/http"
"github.com/gin-contrib/sessions"
"github.com/gin-contrib/sessions/cookie"
"github.com/gin-gonic/gin"
"sf-auth-gin-middleware/sfauthgin"
)
func main() {
router := gin.Default()
store := cookie.NewStore([]byte("super-secret"))
router.Use(sessions.Sessions("sf_auth", store))
authMiddleware := sfauthgin.NewMiddleware(func(c *gin.Context) string {
return "http://localhost:3000/auth_callback"
})
router.GET("/", func(c *gin.Context) {
c.String(http.StatusOK, "Welcome to the demo")
})
router.GET("/auth_callback", sfauthgin.CreateAuthCallbackHandler("/user_info"))
router.GET("/user_info", authMiddleware, func(c *gin.Context) {
session := sessions.Default(c)
userID := session.Get("sf_user_id")
username := session.Get("sf_username")
c.String(http.StatusOK, "User ID: %v\nUsername: %v", userID, username)
})
router.GET("/settings", authMiddleware, func(c *gin.Context) {
session := sessions.Default(c)
userID := session.Get("sf_user_id")
c.String(http.StatusOK, "Settings for user: %v", userID)
})
_ = router.Run(":3000")
}
User identity note
Usernames can change, so avoid using sf_username as a stable identifier. Store any user-related data under the sf_user_id value instead.
If you have many protected routes, you can also attach the middleware to a group, for example:
protected := router.Group("/")
protected.Use(authMiddleware)
protected.GET("/user_info", userInfoHandler)
protected.GET("/settings", settingsHandler)