Download and install it:
go get github.com/TJM/gin-gonic-oidcauth
Import it in your code:
import oidcauth "github.com/TJM/gin-gonic-oidcauth"
Use it: (see complete examples)
// NOTE: oidcauth *requires* sessions *before* oidcauth
// SEE Examples to see how.
// Authentication Config
auth, err := oidcauth.GetOidcAuth(oidcauth.DefaultConfig())
if err != nil {
panic("auth setup failed")
}
router.GET("/login", auth.Login) // Unnecessary, as requesting a "AuthRequired" resource will initiate login, but potentially convenient
router.GET("/callback", auth.AuthCallback)
router.GET("/logout", auth.Logout)
// Private Route Group...
private := r.Group("/private", auth.AuthRequired())
{
private.GET("", func(c *gin.Context) {
c.String(http.StatusOK, "Private!")
}
// ...
}
Prerequisites:
- Oauth2 Identity Provider (IdP) service that supports OIDC
The example below will use DEX IdP. Please clone their repo and start DEX in a separate window.
- Start DEX IdP:
./bin/dex serve examples/config-dev.yaml
- Start [DEX ExampleApp(example/dex/main.go)]:
go run example/dex/main.go
- Visit: http://127.0.0.1:5555/
- Attempt to access something "private" http://127.0.0.1:5555/private
- Login: http://127.0.0.1:5555/login
- Logout: http://127.0.0.1:5555/logout
The example below will use Google Accounts. See: go-oidc examples readme.
NOTE: This example used port 5556
to be compatible with the other go-oidc examples, but it will clash with "dex" which runs on the same port by default.
-
Setup Google
- Visit your Google Developer Console.
- Click "Credentials" on the left column.
- Click the "Create credentials" button followed by "OAuth client ID".
- Select "Web application" and add "http://127.0.0.1:5556/auth/google/callback" as an authorized redirect URI.
- Click create and add the printed client ID and secret to your environment using the following variables:
export GOOGLE_OAUTH2_CLIENT_ID= export GOOGLE_OAUTH2_CLIENT_SECRET=
-
Start Google Example example/google/main.go:
go run example/google/main.go
- Visit: http://127.0.0.1:5556/
- Attempt to access something "private" http://127.0.0.1:5556/private
- Login: http://127.0.0.1:5556/login
- Logout: http://127.0.0.1:5556/logout
Licensed under the Apache License, Version 2.0.