Last active
October 25, 2017 04:31
-
-
Save paked/6c35ad42f8bb9a760d6b to your computer and use it in GitHub Desktop.
Basic OAuth with goth in golang.
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 ( | |
"flag" | |
"fmt" | |
"net/http" | |
"github.com/gorilla/mux" | |
"github.com/markbates/goth" | |
"github.com/markbates/goth/gothic" | |
"github.com/markbates/goth/providers/facebook" | |
"github.com/markbates/goth/providers/gplus" | |
"github.com/markbates/goth/providers/twitter" | |
) | |
var ( | |
twitterKey = flag.String("twitter_key", "", "this is your twitter API key") | |
twitterSecret = flag.String("twitter_secret", "", "this is your twitter secre") | |
facebookKey = flag.String("facebook_key", "", "this is your facebook API key") | |
facebookSecret = flag.String("facebook_secret", "", "this is your facebook API secret") | |
gplusKey = flag.String("gplus_key", "", "this is your gplus API key") | |
gplusSecret = flag.String("gplus_secret", "", "this is your gplus API secret") | |
) | |
func main() { | |
flag.Parse() | |
goth.UseProviders( | |
twitter.New(*twitterKey, *twitterSecret, "http://localhost:8888/auth/twitter/callback?provider=twitter"), | |
facebook.New(*facebookKey, *facebookSecret, "http://localhost:8888/auth/twitter/callback?provider=facebook"), | |
gplus.New(*gplusKey, *gplusSecret, "http://localhost:8888/auth/gplus/callback?provider=gplus"), | |
) | |
gothic.GetState = func(r *http.Request) string { | |
return r.URL.Query().Get("state") | |
} | |
r := mux.NewRouter() | |
r.HandleFunc("/auth/{provider}/callback", func(w http.ResponseWriter, r *http.Request) { | |
fmt.Println(gothic.GetState(r)) | |
user, err := gothic.CompleteUserAuth(w, r) | |
if err != nil { | |
panic(err) | |
} | |
fmt.Fprintln(w, "logged in!", user) | |
}) | |
r.HandleFunc("/auth/{provider}", gothic.BeginAuthHandler) | |
r.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { | |
fmt.Fprintf(w, "<p><a href='/auth/twitter?provider=twitter'>Click to log in with twitter</a></p>") | |
fmt.Fprintf(w, "<p><a href='/auth/facebook?provider=facebook'>Click to log in with facebook</a></p>") | |
fmt.Fprintf(w, "<p><a href='/auth/gplus?provider=gplus'>Click to log in with gplus</a></p>") | |
}) | |
http.ListenAndServe("localhost:8888", r) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment