Skip to content

Instantly share code, notes, and snippets.

@munierujp
Last active January 24, 2024 14:47
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save munierujp/e7dc02a0ec11559f9975350c9adbb065 to your computer and use it in GitHub Desktop.
Save munierujp/e7dc02a0ec11559f9975350c9adbb065 to your computer and use it in GitHub Desktop.
Echo's middleware for Firebase Authentication
package middleware
import (
"context"
"strings"
"github.com/labstack/echo/v4"
firebase "firebase.google.com/go"
"google.golang.org/api/option"
)
func Auth() echo.MiddlewareFunc {
return auth
}
func auth(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
opt := option.WithCredentialsFile("firebase_secret_key.json")
app, err := firebase.NewApp(context.Background(), nil, opt)
if err != nil {
return err
}
client, err := app.Auth(context.Background())
if err != nil {
return err
}
auth := c.Request().Header.Get("Authorization")
idToken := strings.Replace(auth, "Bearer ", "", 1)
token, err := client.VerifyIDToken(context.Background(), idToken)
if err != nil {
return err
}
c.Set("token", token)
return next(c)
}
}
@munierujp
Copy link
Author

munierujp commented Aug 14, 2019

Usage

e.GET("/api/private", privateAPI, middleware.Auth())
token := c.Get("token").(*auth.Token)
claims := token.Claims
name, ok := claims["name"].(string)
email, ok := claims["email"].(string)

@nidhish1
Copy link

Thanks, It was helpful.

@munierujp
Copy link
Author

@nidhish1 Glad I could help 😄

@vectorman1
Copy link

🙏 thank you for this

@munierujp
Copy link
Author

@vectorman1 It's been a long time since I've been away from Go, but I'm glad to be of service.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment