├── .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 | Jokeish App 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 20 | 21 | 22 | 23 |
24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /views/js/app.jsx: -------------------------------------------------------------------------------- 1 | const AUTH0_CLIENT_ID = "aIAOt9fkMZKrNsSsFqbKj5KTI0ObTDPP"; 2 | const AUTH0_DOMAIN = "hakaselabs.auth0.com"; 3 | const AUTH0_CALLBACK_URL = location.href; 4 | const AUTH0_API_AUDIENCE = "golang-gin"; 5 | 6 | class App extends React.Component { 7 | parseHash() { 8 | this.auth0 = new auth0.WebAuth({ 9 | domain: AUTH0_DOMAIN, 10 | clientID: AUTH0_CLIENT_ID 11 | }); 12 | this.auth0.parseHash(window.location.hash, (err, authResult) => { 13 | if (err) { 14 | return console.log(err); 15 | } 16 | if ( 17 | authResult !== null && 18 | authResult.accessToken !== null && 19 | authResult.idToken !== null 20 | ) { 21 | localStorage.setItem("access_token", authResult.accessToken); 22 | localStorage.setItem("id_token", authResult.idToken); 23 | localStorage.setItem( 24 | "profile", 25 | JSON.stringify(authResult.idTokenPayload) 26 | ); 27 | window.location = window.location.href.substr( 28 | 0, 29 | window.location.href.indexOf("#") 30 | ); 31 | } 32 | }); 33 | } 34 | 35 | setup() { 36 | $.ajaxSetup({ 37 | beforeSend: (r) => { 38 | if (localStorage.getItem("access_token")) { 39 | r.setRequestHeader( 40 | "Authorization", 41 | "Bearer " + localStorage.getItem("access_token") 42 | ); 43 | } 44 | } 45 | }); 46 | } 47 | 48 | setState() { 49 | let idToken = localStorage.getItem("id_token"); 50 | if (idToken) { 51 | this.loggedIn = true; 52 | } else { 53 | this.loggedIn = false; 54 | } 55 | } 56 | 57 | componentWillMount() { 58 | this.setup(); 59 | this.parseHash(); 60 | this.setState(); 61 | } 62 | 63 | render() { 64 | if (this.loggedIn) { 65 | return ; 66 | } 67 | return ; 68 | } 69 | } 70 | 71 | class Home extends React.Component { 72 | constructor(props) { 73 | super(props); 74 | this.authenticate = this.authenticate.bind(this); 75 | } 76 | authenticate() { 77 | this.WebAuth = new auth0.WebAuth({ 78 | domain: AUTH0_DOMAIN, 79 | clientID: AUTH0_CLIENT_ID, 80 | scope: "openid profile", 81 | audience: AUTH0_API_AUDIENCE, 82 | responseType: "token id_token", 83 | redirectUri: AUTH0_CALLBACK_URL 84 | }); 85 | this.WebAuth.authorize(); 86 | } 87 | 88 | render() { 89 | return ( 90 |
91 |
92 |
93 |

Jokeish

94 |

A load of Dad jokes XD

95 |

Sign in to get access

96 | 100 | Sign In 101 | 102 |
103 |
104 |
105 | ); 106 | } 107 | } 108 | 109 | class LoggedIn extends React.Component { 110 | constructor(props) { 111 | super(props); 112 | this.state = { 113 | jokes: [] 114 | }; 115 | 116 | this.serverRequest = this.serverRequest.bind(this); 117 | this.logout = this.logout.bind(this); 118 | } 119 | 120 | logout() { 121 | localStorage.removeItem("id_token"); 122 | localStorage.removeItem("access_token"); 123 | localStorage.removeItem("profile"); 124 | location.reload(); 125 | } 126 | 127 | serverRequest() { 128 | $.get("http://localhost:3000/api/jokes", res => { 129 | this.setState({ 130 | jokes: res 131 | }); 132 | }); 133 | } 134 | 135 | componentDidMount() { 136 | this.serverRequest(); 137 | } 138 | 139 | render() { 140 | return ( 141 |
142 |
143 | 144 | Log out 145 | 146 |

Jokeish

147 |

Let's feed you with some funny Jokes!!!

148 |
149 |
150 | {this.state.jokes.map(function(joke, i) { 151 | return ; 152 | })} 153 |
154 |
155 |
156 | ); 157 | } 158 | } 159 | 160 | class Joke extends React.Component { 161 | constructor(props) { 162 | super(props); 163 | this.state = { 164 | liked: "", 165 | jokes: [] 166 | }; 167 | this.like = this.like.bind(this); 168 | this.serverRequest = this.serverRequest.bind(this); 169 | } 170 | 171 | like() { 172 | let joke = this.props.joke; 173 | this.serverRequest(joke); 174 | } 175 | serverRequest(joke) { 176 | $.post( 177 | "http://localhost:3000/api/jokes/like/" + joke.id, 178 | { like: 1 }, 179 | res => { 180 | console.log("res... ", res); 181 | this.setState({ liked: "Liked!", jokes: res }); 182 | this.props.jokes = res; 183 | } 184 | ); 185 | } 186 | 187 | render() { 188 | return ( 189 |
190 |
191 |
192 | #{this.props.joke.id}{" "} 193 | {this.state.liked} 194 |
195 |
{this.props.joke.joke}
196 |
197 | {this.props.joke.likes} Likes   198 | 199 | 200 | 201 |
202 |
203 |
204 | ); 205 | } 206 | } 207 | ReactDOM.render(, document.getElementById("app")); 208 | --------------------------------------------------------------------------------