How to Implement SSO using OAuth in Golang Application www.bacancytechnology.com
Introduction
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.
What is Single Sign-On (SSO)?
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.
Video Tutorial: Implementing SSO using OAuth in Golang Application
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!
Hire Golang Developers
Register Application to Google Console Dashboard
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.
Configure OAuth Consent Screen
Now, it’s time to configure the OAuth Consent Screen. For that, we will need to Add Application Information,
OAuth Consent Screen
Scopes
Test Users
Here is the Summary of all three steps.
Create Credentials
Now, moving towards creating credentials . Create OAuth Client ID
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. .
Backend Initial Set-Up
Run the below command to create initiate the go.mod file.
go mod init golang-sso
This will be our project structure
Create main.go and use the belowmentioned code.
// main.go package main import ( "golang-sso/controllers" "net/http" ) func main(){ fs := http.FileServer(http.Dir("public")) http.Handle("/",fs) http.HandleFunc("/signin",controllers.Signi n) http.HandleFunc("/callback",controllers.Cal lback) http.ListenAndServe(":3000",nil) }
Explanation
The /signin route in this line of code http.HandleFunc(“/signin”,controllers.Si gnin) is for handling URL generation and later after sign in redirecting to that URL. The /callback route in this line of code http.HandleFunc(“/callback”,controllers .Callback) is for getting code and state of the current user from Google console.
Controllers package
Now, create two files: signin.go and callback.go within the folder controllers.
// signin.go 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 {
p 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.StatusTemporary Redirect) }
This will our generated URL
Explanation ssogolang = &oauth2.Config{…} is to configure our backend code with our console app using the credentials we got from there. Further, we will enter the scope needed in the configuration. Here, we want the email id of the user so we’ve used []string{“https://www.googleapis.com/auth/ userinfo.email”}. Generate the random string to uniquely identify user from the user state and then pass it to the AuthcodeUrl function from the OAuth package that generates URL with the required configuration
// callback.go 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.Backgroun d(),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 }
fExplanation
state :=r.FormValue(“state”) ,code := r.FormValue(“code”) This line of code will fetch the user state and code from Google console. Further, check the user state to uniquely identify the user with the help of if state != RandomString Exchange the code for a token using the Exchange(…) function, a part of OAuth flow using the OAuth library. Now get the user data from Google APIs using the token we got using this line of code response,err :=http.Get(“https://www.googleapis.com/o auth2/v2/userinfo?access_token=” + token.AccessToken)
Front-end SetUp
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.
// index.html <div> <form action="/action_page.php"> <div class="row"> <h2 style="text-align:center"> Login with Social Media or Manually </h2> <div class="vl"> <span class="vl-innertext">or</span> </div> <div class="col">
<a href="#" class="fb btn"> <i class="fa fa-facebook fa-fw"></i> Login with Facebook </a> <a href="#" class="twitter btn"> <i class="fa fa-twitter fa-fw"></i> Login with Twitter </a> <a href="/signin" class="google btn"> <i class="fa fa-google fa-fw"></i> Login with Google+ </a> </div> <div class="col"> <div class="hide-md-lg"> <p>Or sign in manually:</p> </div> <input type="text" name="username" placeholder="Username" required
> <input type="password" name="password" placeholder="Password" required > <input type="submit" value="Login"> </div> </div> </form> <div class="bottom-container"> <div class="row"> <div class="col"> <a href="#" style="color:white" class="btn">Sign up</a> </div> <div class="col"> <a href="#" style="color:white" class="btn">Forgot password?</a> </div> </div> </div> </div>
<a href=”/signin ”> will redirect you to the sign-in route when you click the button.
Github Repository
If you want to clone the project and play around with the code then here’s the source code: sso-using-oauth-demo
Conclusion
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
Thank You
www.bacancytechnology.com