You all have definitely come across the Login page where the website or application provides you the option of Login with Google or Facebook. Doesn’t that reduce your efforts of registering your account for the respective website? Almost all the websites have a mandatory criterion of login before accessing the information or visiting other web pages. Imagine the scenario of signing up on these websites and remembering their credentials. Thus, social login saves your time and effort easing your process to surf various websites.
Now, the question is do you know to implement single sign-on (SSO) using OAuth in your golang app? If no, then don’t worry here is the tutorial: How to implement SSO using OAuth in golang application; if yes, then let me know any other better way for the same (constructive feedbacks always help). We will see a few theoretical parts regarding our topic and then get started with the coding part.
We also have a video tutorial on the same topic. The entire tutorial is covered in the video form and is attached in the below section.
One Time Log In.
Single Sign-On (SSO) provides users the opportunity to log in using a single user ID and password to related yet independent platforms. In layman terms, you can sign in to your Google account and use the same account to log in or sign up in various other software applications.
If you are someone who grasps more from video tutorials then here is a comprehensive video tutorial on implementing SSO using OAuth in Golang Application from our developer.
The video will show you each and everything with a few helpful insights that you need to know. It will cover registering the application to the Google Console, Backend, and Frontend coding part.
Want to develop a Scalable and Secure Golang project from scratch?
We’d never compromise the project quality, and that’s the reason why our clients love us! Leverage the advantage of our Golang development service.
The first step would be registering our golang application to Google Console Dashboard. For that Select Credentials under APIs and Services section. If you want you can choose the existing project, here we will create a New Project as shown in the below image.
Fill in the details as asked. Here my project name is Testing-SSO-Golang
Once done with creating the project make sure you have selected the project, here, Testing-SSO-Golang.
Now, it’s time to configure the OAuth Consent Screen. For that, we will need to Add Application Information,
Here is the Summary of all three steps.
Now, moving towards creating credentials.
Download the JSON file after the OAuth client is created.
So, this was about how to register your golang app and create an OAuth client. Now, it’s time to do some code.
Run the below command to create initiate the go.mod file.
This will be our project structure-
Create main.go and use the below-mentioned code.
package main import ( "golang-sso/controllers" "net/http" ) func main(){ fs := http.FileServer(http.Dir("public")) http.Handle("/",fs) http.HandleFunc("/signin",controllers.Signin) http.HandleFunc("/callback",controllers.Callback) http.ListenAndServe(":3000",nil) }
Explanation
Now, create two files: signin.go and callback.go within the folder controllers.
package controllers import ( "fmt" "log" "net/http" "os" "github.com/joho/godotenv" "golang.org/x/oauth2" "golang.org/x/oauth2/google" ) var ssogolang *oauth2.Config var RandomString = "random-string" func init(){ err := godotenv.Load("./.env") if err != nil { log.Fatal("Error loading .env file") } ssogolang = &oauth2.Config{ RedirectURL:os.Getenv("REDIRECT_URL"), ClientID:os.Getenv("CLIENT_ID"), ClientSecret:os.Getenv("CLIENT_SECRET"), Scopes: []string{"https://www.googleapis.com/auth/userinfo.email"}, Endpoint: google.Endpoint, } } func Signin(w http.ResponseWriter, r *http.Request){ url :=ssogolang.AuthCodeURL(RandomString) fmt.Println(url) http.Redirect(w,r,url,http.StatusTemporaryRedirect) }
This will our generated URL
Explanation
package controllers import ( "context" "errors" "fmt" "io/ioutil" "log" "net/http" ) func Callback(w http.ResponseWriter, r *http.Request){ state :=r.FormValue("state") code := r.FormValue("code") data,err:=getUserData(state,code) if err!=nil{ log.Fatal("error getting user data") } fmt.Fprintf(w,"Data : %s",data) } func getUserData(state,code string)([]byte,error){ if state != RandomString{ return nil,errors.New("invalid user state") } token,err:=ssogolang.Exchange(context.Background(),code) if err!=nil{ return nil,err } response,err :=http.Get("https://www.googleapis.com/oauth2/v2/userinfo?access_token=" + token.AccessToken) if err!=nil{ return nil,err } defer response.Body.Close() data,err:=ioutil.ReadAll(response.Body) if err!=nil{ return nil,err } return data,nil }
Explanation
So far we have covered the backend part for implementing SSO using OAuth in our golang app. Now, it’s time to write some front-end code.
Open index.html and use the below code for the user interface. You can surely change the UI according to your wish.
If you want to clone the project and play around with the code then here’s the source code: sso-using-oauth-demo
So, this was about how to implement SSO using OAuth in the Golang application. I hope the purpose of this step-by-step guideline has been served as expected. For more such Golang tutorials with github sources feel free to visit the Golang tutorials page.
Bacancy has skilled developers with fundamental and advanced knowledge. Are you looking for a helping hand for your golang project? If yes, then without a second thought, contact our Golang developers
Your Success Is Guaranteed !
We accelerate the release of digital product and guaranteed their success
We Use Slack, Jira & GitHub for Accurate Deployment and Effective Communication.