Introduction
👉 The oAuth2 protocol has almost become a standard for securing websites and API services. Developers no longer need to store and manage userIDs and passwords for their users. Offloading the authentication to OAuth2 providers such as Google, Facebook, Linkedin, Github keeps the authentication with username and password, within those providers rather than passing through the developer’s application. This reduces the risk that an application will leak user credentials and puts more control in the user's hands on for managing authentication with their accounts.I wanted to provide this capability in my own apps and went looking for a pattern to use in Go. Typically when I’m on a hunt like this I find bits and pieces that I stitch together into a reference pattern. For this oAuth pattern most of the result I found referenced back to a couple limited examples on the google site.
Then it happened, I stumbled on a fantastic write-up and sample app that covers every main point better than I could have written.
Initial Login with oAuth:
In this example, the set is using Google oAuth2 credentials just for the site authentication
var ( | |
googleOauthConfig = &oauth2.Config{ | |
RedirectURL: "http://localhost:9000/GoogleCallback", | |
ClientID: "", | |
ClientSecret: " ", | |
Scopes: []string{"https://www.googleapis.com/auth/userinfo.profile", | |
"https://www.googleapis.com/auth/userinfo.email"}, | |
Endpoint: google.Endpoint, | |
} | |
oauthStateString = "random" | |
) | |
Token Reuse for API calls:
For my use not only did I want to log the user in but I also wanted to use those credentials for subsequent google API calls.
token, err := googleOauthConfig.Exchange(oauth2.NoContext, code) if err != nil { fmt.Println("Code exchange failed with '%s'\n", err) http.Redirect(w, r, "/", http.StatusTemporaryRedirect) return } response, err := http.Get("https://www.googleapis.com/oauth2/v2/userinfo?access_token=" + token.AccessToken) |
Mysql - Database Table Struct :
type GoogleUserTable struct { | |
Id int `orm:"column(id);auto"` | |
Name string `orm:"column(name);size(225)"` | |
Email string `orm:"column(email);size(225)"` | |
Role string `orm:"column(role)"` | |
Picture string `orm:"column(picture)"` | |
Hd string `orm:"column(hd)"` | |
VerifiedEmail int8 `orm:"column(verified_email)"` | |
AuthId string `orm:"column(auth_id);size(256)"` | |
} |
we’ve used google OAuth2 to log the user in the mysqli database , then we reused those tokens for future calls by the user. This allow us to create an interface to google APIs that act based on the users credentials and access rights.
Source Code link:
OAuth 2.0 client IDs:
Create credentials to access your enabled APIs.
Comments
Post a Comment