├── .env.sample ├── .gitignore ├── LICENSE ├── README.md ├── main.go └── views ├── index.html └── js └── app.jsx /.env.sample: -------------------------------------------------------------------------------- 1 | export AUTH0_API_CLIENT_SECRET="" 2 | export AUTH0_CLIENT_ID="" 3 | export AUTH0_DOMAIN="" 4 | export AUTH0_API_AUDIENCE="" 5 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .env 2 | main 3 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 Francis Sunday 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Build a Golang app with the Gin framework, and authenticate with Auth0 + JWT 2 | 3 | This repo contains the code samples for the [Build a Golang app with the Gin framework, and authenticate with Auth0 + JWT ](https://hakaselogs.me/2018-04-20/building-a-web-app-with-go-gin-and-react) article. 4 | 5 | ## Setup 6 | 7 | 1. Update the `main.go` file with your Auth0 Credentials. [Sign up](https://auth0.com) for an account for free if you don't have one. 8 | 2. Update the `views/app.jsx` file with your Auth0 Credentials. 9 | 3. Add `http://localhost:3000` to your Allowed Callback, and Allowed Logout URL's in your [Auth0 Management Dashboard](https://manage.auth0.com). 10 | 4. Run `mv .env.sample .env` and update with valid credentials 11 | 5. Source the environment variables - `source .env` 12 | 6. Update dependencies `go get` 13 | 7. Launch the application by running `go run main.go` 14 | 8. Navigate to `localhost:3000` to view the application 15 | 16 | ## Author 17 | [Francis Sunday](https://twitter.com/codehakase) 18 | 19 | ## License 20 | 21 | This project is licensed under the MIT license. See the [LICENSE](LICENSE) file for more info. 22 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "encoding/json" 5 | "errors" 6 | "fmt" 7 | "log" 8 | "net/http" 9 | "os" 10 | "strconv" 11 | 12 | jwtmiddleware "github.com/auth0/go-jwt-middleware" 13 | jwt "github.com/dgrijalva/jwt-go" 14 | "github.com/gin-gonic/contrib/static" 15 | "github.com/gin-gonic/gin" 16 | ) 17 | 18 | type Response struct { 19 | Message string `json:"message"` 20 | } 21 | 22 | type Jwks struct { 23 | Keys []JSONWebKeys `json:"keys"` 24 | } 25 | 26 | type JSONWebKeys struct { 27 | Kty string `json:"kty"` 28 | Kid string `json:"kid"` 29 | Use string `json:"use"` 30 | N string `json:"n"` 31 | E string `json:"e"` 32 | X5c []string `json:"x5c"` 33 | } 34 | 35 | type Joke struct { 36 | ID int `json:"id" binding:"required"` 37 | Likes int `json:"likes"` 38 | Joke string `json:"joke" binding:"required"` 39 | } 40 | 41 | /** we'll create a list of jokes */ 42 | var jokes = []Joke{ 43 | Joke{1, 0, "Did you hear about the restaurant on the moon? Great food, no atmosphere."}, 44 | Joke{2, 0, "What do you call a fake noodle? An Impasta."}, 45 | Joke{3, 0, "How many apples grow on a tree? All of them."}, 46 | Joke{4, 0, "Want to hear a joke about paper? Nevermind it's tearable."}, 47 | Joke{5, 0, "I just watched a program about beavers. It was the best dam program I've ever seen."}, 48 | Joke{6, 0, "Why did the coffee file a police report? It got mugged."}, 49 | Joke{7, 0, "How does a penguin build it's house? Igloos it together."}, 50 | Joke{8, 0, "Dad, did you get a haircut? No I got them all cut."}, 51 | Joke{9, 0, "What do you call a Mexican who has lost his car? Carlos."}, 52 | Joke{10, 0, "Dad, can you put my shoes on? No, I don't think they'll fit me."}, 53 | Joke{11, 0, "Why did the scarecrow win an award? Because he was outstanding in his field."}, 54 | Joke{12, 0, "Why don't skeletons ever go trick or treating? Because they have no body to go with."}, 55 | } 56 | 57 | var jwtMiddleWare *jwtmiddleware.JWTMiddleware 58 | 59 | func main() { 60 | jwtMiddleware := jwtmiddleware.New(jwtmiddleware.Options{ 61 | ValidationKeyGetter: func(token *jwt.Token) (interface{}, error) { 62 | aud := os.Getenv("AUTH0_API_AUDIENCE") 63 | checkAudience := token.Claims.(jwt.MapClaims).VerifyAudience(aud, false) 64 | if !checkAudience { 65 | return token, errors.New("Invalid audience.") 66 | } 67 | // verify iss claim 68 | iss := os.Getenv("AUTH0_DOMAIN") 69 | checkIss := token.Claims.(jwt.MapClaims).VerifyIssuer(iss, false) 70 | if !checkIss { 71 | return token, errors.New("Invalid issuer.") 72 | } 73 | 74 | cert, err := getPemCert(token) 75 | if err != nil { 76 | log.Fatalf("could not get cert: %+v", err) 77 | } 78 | 79 | result, _ := jwt.ParseRSAPublicKeyFromPEM([]byte(cert)) 80 | return result, nil 81 | }, 82 | SigningMethod: jwt.SigningMethodRS256, 83 | }) 84 | 85 | jwtMiddleWare = jwtMiddleware 86 | // Set the router as the default one shipped with Gin 87 | router := gin.Default() 88 | 89 | // Serve the frontend 90 | router.Use(static.Serve("/", static.LocalFile("./views", true))) 91 | 92 | api := router.Group("/api") 93 | { 94 | api.GET("/", func(c *gin.Context) { 95 | c.JSON(http.StatusOK, gin.H{ 96 | "message": "pong", 97 | }) 98 | }) 99 | api.GET("/jokes", authMiddleware(), JokeHandler) 100 | api.POST("/jokes/like/:jokeID", authMiddleware(), LikeJoke) 101 | } 102 | // Start the app 103 | router.Run(":3000") 104 | } 105 | 106 | func getPemCert(token *jwt.Token) (string, error) { 107 | cert := "" 108 | resp, err := http.Get(os.Getenv("AUTH0_DOMAIN") + ".well-known/jwks.json") 109 | if err != nil { 110 | return cert, err 111 | } 112 | defer resp.Body.Close() 113 | 114 | var jwks = Jwks{} 115 | err = json.NewDecoder(resp.Body).Decode(&jwks) 116 | 117 | if err != nil { 118 | return cert, err 119 | } 120 | 121 | x5c := jwks.Keys[0].X5c 122 | for k, v := range x5c { 123 | if token.Header["kid"] == jwks.Keys[k].Kid { 124 | cert = "-----BEGIN CERTIFICATE-----\n" + v + "\n-----END CERTIFICATE-----" 125 | } 126 | } 127 | 128 | if cert == "" { 129 | return cert, errors.New("unable to find appropriate key") 130 | } 131 | 132 | return cert, nil 133 | } 134 | 135 | // authMiddleware intercepts the requests, and check for a valid jwt token 136 | func authMiddleware() gin.HandlerFunc { 137 | return func(c *gin.Context) { 138 | // Get the client secret key 139 | err := jwtMiddleWare.CheckJWT(c.Writer, c.Request) 140 | if err != nil { 141 | // Token not found 142 | fmt.Println(err) 143 | c.Abort() 144 | c.Writer.WriteHeader(http.StatusUnauthorized) 145 | c.Writer.Write([]byte("Unauthorized")) 146 | return 147 | } 148 | } 149 | } 150 | 151 | // JokeHandler returns a list of jokes available (in memory) 152 | func JokeHandler(c *gin.Context) { 153 | c.Header("Content-Type", "application/json") 154 | 155 | c.JSON(http.StatusOK, jokes) 156 | } 157 | 158 | func LikeJoke(c *gin.Context) { 159 | // Check joke ID is valid 160 | if jokeid, err := strconv.Atoi(c.Param("jokeID")); err == nil { 161 | // find joke and increment likes 162 | for i := 0; i < len(jokes); i++ { 163 | if jokes[i].ID == jokeid { 164 | jokes[i].Likes = jokes[i].Likes + 1 165 | } 166 | } 167 | c.JSON(http.StatusOK, &jokes) 168 | } else { 169 | // the jokes ID is invalid 170 | c.AbortWithStatus(http.StatusNotFound) 171 | } 172 | } 173 | 174 | // getJokesByID returns a single joke 175 | func getJokesByID(id int) (*Joke, error) { 176 | for _, joke := range jokes { 177 | if joke.ID == id { 178 | return &joke, nil 179 | } 180 | } 181 | return nil, errors.New("Joke not found") 182 | } 183 | -------------------------------------------------------------------------------- /views/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 |
5 | 6 | 7 |Let's feed you with some funny Jokes!!!
148 |