Skip to content

Instantly share code, notes, and snippets.

@err0r500
Last active May 24, 2024 02:37
Show Gist options
  • Save err0r500/00c50d45a5337058c4c732206457bd64 to your computer and use it in GitHub Desktop.
Save err0r500/00c50d45a5337058c4c732206457bd64 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")
}
@hilmanski
Copy link

hey thanks for this snippet, help me a lot!
may i know where did you get the information about jwMiddleware has checkjwt() function? (line 23)

@sanderhelleso
Copy link

Awesome, you helped me out alot. None of the popular CORS frameworks was working for me, but this did!

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