Skip to content

Instantly share code, notes, and snippets.

@hectorgool
Forked from err0r500/main.go
Created November 23, 2021 20:15
Show Gist options
  • Save hectorgool/03d8e144f3f200f8a7ebbc5ee9342342 to your computer and use it in GitHub Desktop.
Save hectorgool/03d8e144f3f200f8a7ebbc5ee9342342 to your computer and use it in GitHub Desktop.
gin gonic with jwt from auth0 (and CORS enabled)
package main
import (
"github.com/auth0/go-jwt-middleware"
"github.com/dgrijalva/jwt-go"
"gopkg.in/gin-gonic/gin.v1"
)
func main() {
startServer()
}
var jwtMiddleware = jwtmiddleware.New(jwtmiddleware.Options{
ValidationKeyGetter: func(token *jwt.Token) (interface{}, error) {
return []byte("your auth0 client secret here"), nil
},
SigningMethod: jwt.SigningMethodHS256,
})
func checkJWT() gin.HandlerFunc {
return func(c *gin.Context) {
jwtMid := *jwtMiddleware
if err := jwtMid.CheckJWT(c.Writer, c.Request); err != nil {
c.AbortWithStatus(401)
}
}
}
func corsMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
c.Writer.Header().Set("Access-Control-Allow-Origin", "http://localhost:3000")
c.Writer.Header().Set("Access-Control-Max-Age", "86400")
c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, UPDATE")
c.Writer.Header().Set("Access-Control-Allow-Headers", "Origin, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
c.Writer.Header().Set("Access-Control-Expose-Headers", "Content-Length")
c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
if c.Request.Method == "OPTIONS" {
c.AbortWithStatus(200)
} else {
c.Next()
}
}
}
func startServer() {
r := gin.Default()
r.Use(corsMiddleware())
r.GET("/ping", func(g *gin.Context) {
g.JSON(200, gin.H{"text": "Hello from public"})
})
r.GET("/secured/ping", checkJWT(), func(g *gin.Context) {
g.JSON(200, gin.H{"text": "Hello from private"})
})
r.Run(":3002")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment