Created
February 6, 2019 12:28
-
-
Save cyantarek/5f06851e5c44d2ff6530869987ec5a0c to your computer and use it in GitHub Desktop.
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 ( | |
"encoding/json" | |
"fmt" | |
"github.com/google/uuid" | |
"gopkg.in/oauth2.v3/models" | |
"log" | |
"net/http" | |
"time" | |
"gopkg.in/oauth2.v3/errors" | |
"gopkg.in/oauth2.v3/manage" | |
"gopkg.in/oauth2.v3/server" | |
"gopkg.in/oauth2.v3/store" | |
) | |
func main() { | |
manager := manage.NewDefaultManager() | |
manager.SetAuthorizeCodeTokenCfg(manage.DefaultAuthorizeCodeTokenCfg) | |
// token memory store | |
manager.MustTokenStorage(store.NewMemoryTokenStore()) | |
// client memory store | |
clientStore := store.NewClientStore() | |
manager.MapClientStorage(clientStore) | |
srv := server.NewDefaultServer(manager) | |
srv.SetAllowGetAccessRequest(true) | |
srv.SetClientInfoHandler(server.ClientFormHandler) | |
manager.SetRefreshTokenCfg(manage.DefaultRefreshTokenCfg) | |
srv.SetInternalErrorHandler(func(err error) (re *errors.Response) { | |
log.Println("Internal Error:", err.Error()) | |
return | |
}) | |
srv.SetResponseErrorHandler(func(re *errors.Response) { | |
log.Println("Response Error:", re.Error.Error()) | |
}) | |
http.HandleFunc("/token", func(w http.ResponseWriter, r *http.Request) { | |
srv.HandleTokenRequest(w, r) | |
}) | |
http.HandleFunc("/credentials", func(w http.ResponseWriter, r *http.Request) { | |
clientId := uuid.New().String()[:8] | |
clientSecret := uuid.New().String()[:8] | |
err := clientStore.Set(clientId, &models.Client{ | |
ID: clientId, | |
Secret: clientSecret, | |
Domain: "http://localhost:9094", | |
}) | |
if err != nil { | |
fmt.Println(err.Error()) | |
} | |
w.Header().Set("Content-Type", "application/json") | |
json.NewEncoder(w).Encode(map[string]string{"CLIENT_ID": clientId, "CLIENT_SECRET": clientSecret}) | |
}) | |
http.HandleFunc("/protected", validateToken(func(w http.ResponseWriter, r *http.Request) { | |
w.Write([]byte("Hello, I'm protected")) | |
}, srv)) | |
log.Fatal(http.ListenAndServe(":9096", nil)) | |
} | |
func validateToken(f http.HandlerFunc, srv *server.Server) http.HandlerFunc { | |
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | |
_, err := srv.ValidationBearerToken(r) | |
if err != nil { | |
http.Error(w, err.Error(), http.StatusBadRequest) | |
return | |
} | |
f.ServeHTTP(w, r) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment