-
-
Save mannharleen/9fc805c2bcae73a1e6315520e6ee88ae to your computer and use it in GitHub Desktop.
gin gonic with jwt from auth0 (and CORS enabled)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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