ginoauth is a Go library that simplifies the integration of OAuth2 authentication into applications built with the Gin web framework. It supports providers such as Google and Casdoor.
- Easy OAuth2 authentication integration with Gin.
- Support for multiple providers (Google, Casdoor).
- Token and user data stored in signed and compressed cookies.
- Token refresh mechanism for expired tokens.
- Fetching user information from the provider.
- Flexible hooks:
OnAuthenticateSuccess,OnUpdateUserInfo.
go get github.com/nullpointerfan/gin-oauthimport (
"github.com/nullpointerfan/gin-oauth"
)
cfg := ginoauth.GoogleConfig{
OAuthConfig: ginoauth.OAuthConfig{
ClientID: "your-google-client-id",
ClientSecret: "your-google-client-secret",
RedirectURL: "http://localhost:8080/auth/callback",
Secret: []byte("your-jwt-secret"),
},
}
auth := ginoauth.NewGoogleAuth(cfg)cfg := ginoauth.CasdoorConfig{
OAuthConfig: ginoauth.OAuthConfig{
ClientID: "casdoor-client-id",
ClientSecret: "casdoor-client-secret",
RedirectURL: "http://localhost:8080/auth/callback",
Secret: []byte("your-jwt-secret"),
},
CasdoorHost: "https://your-casdoor-host",
}
auth := ginoauth.NewCasdoorAuth(cfg)r := gin.Default()
r.GET("/login", auth.LoginHandler)
r.GET("/auth/callback", auth.CallbackHandler)
r.GET("/logout", auth.LogoutHandler)
// Protected route
protected := r.Group("/")
protected.Use(auth.Authenticate)
{
protected.GET("/profile", func(c *gin.Context) {
user, _ := c.Get("user")
c.JSON(200, gin.H{"user": user})
})
}- OAuth2 tokens are stored in secure cookies with HMAC signature and gzip compression.
- When a token expires, it's automatically refreshed using the
refresh_token. - User information is also stored in cookies and can be extended via
OnUpdateUserInfo.
Called after receiving user data from the provider. Useful for adding custom fields or logic:
auth.OnUpdateUserInfo(func(userInfo *ginoauth.UserInfoResponse) error {
userInfo.Name = strings.ToUpper(userInfo.Name)
return nil
})Executed upon successful authentication:
auth.OnAuthenticateSuccess(func(c *gin.Context) error {
c.Set("custom_user_data", "some_extra_info")
return nil
})To log out a user, simply call /logout:
r.GET("/logout", auth.LogoutHandler)This will remove all session-related data (tokens and user info).