Skip to content

Instantly share code, notes, and snippets.

Last active April 16, 2023 02:18
What would you like to do?
gin gonic with jwt from auth0 (and CORS enabled)
package main
import (
func main() {
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 {
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" {
} else {
func startServer() {
r := gin.Default()
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"})
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)

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