Using OAuth and VK APIs in Go

Today's article will focus on developing a program on Go that uses the vk.com API to authorize and download user data.

Now itโ€™s almost impossible to find a modern service that would not use OAuth authorization. There are many scenarios for using this protocol. Letโ€™s try to write a simple client for working with this technology on Go.

First you need to create an application in the section for developers .

It is important to specify the correct project parameters, first you can specify the site address - localhost : 8080 and the base domain - localhost. I tested it using the ngrok proxy , so I entered here the url obtained from ngrok.

vk developer panel

After this, it remains only to indicate the Redirect URI - the address where the redirect will be made along with the code received as a result of authorization. For the sample, you can specify localhost : 8080 / auth.

image

The VK panel is configured. Now you can proceed to programming on Go.

All the program logic can be divided into 3 parts:

OAuth client settings and connection of html files.

Display a template with a button for authorization.

Authorization processing, collecting information from the VKontakte API, transferring it to the template.

To authorize Golang, I chose the standard package golang.org/x/oauth2. It is easy to configure and flexible enough to be suitable for use in a real application, and also contains links to the vk API, which developers of software packages do not spoil.

r := gin.Default()
r.LoadHTMLGlob("templates/*")
conf := &oauth2.Config{
  ClientID:     os.Getenv("CLIENT_ID"),
  ClientSecret: os.Getenv("CLIENT_SECRET"),
  RedirectURL:  os.Getenv("REDIRECT_URL"),
  Scopes:       []string{},
  Endpoint:     vkAuth.Endpoint,
}

Further, when accessing the root, it is necessary to render the template with an authorization link inserted into it.

r.GET("/", func(c *gin.Context) {
  url := conf.AuthCodeURL("state", oauth2.AccessTypeOffline)
  //  URL    OAuth API VK     
  c.HTML(http.StatusOK, "index.html", gin.H{
     "authUrl": url,
  })
})

The last step is to upload data from the social network after authorization. To do this, you first need to get a token from the authorization code to access the API. After that, turn to the social network API and get information about the current user. I get only some of the user API fields, you can get many others, for this you need to add the necessary ones to the vk.RequestParams.fields structure.

r.GET("/auth", func(c *gin.Context) {
  ctx := context.Background()
  //    API VK   
  authCode := c.Request.URL.Query()["code"]
  //    access 
  tok, err := conf.Exchange(ctx, authCode[0])
  if err != nil {
     log.Fatal(err)
  }
  //       API VK
  client, err := vk.NewClientWithOptions(vk.WithToken(tok.AccessToken))
  if err != nil {
     log.Fatal(err)
  }
  user := getCurrentUser(client)

  c.HTML(http.StatusOK, "auth.html", gin.H{
     "user": user,
  })
})
func getCurrentUser(api *vk.Client) User {
  var users []User

  api.CallMethod("users.get", vk.RequestParams{
     "fields": "photo_400_orig,city",
  }, &users)

  return users[0]
}

type User struct {
  ID        int64  `json:"id"`
  FirstName string `json:"first_name"`
  LastName  string `json:"last_name"`
  Photo     string `json:"photo_400_orig"`
  City      City   `json:"city"`
}

type City struct {
  Title string `json:"title"`
}

This is how the application window looks after authorization.

golang authentication vk

Done. This application does not have much functionality, but it is quite suitable as a working example of the implementation of oauth gin golang or golang vk api. It can be added to any of your existing projects to support authorization functionality using VK on golang.

Thanks for reading the article, and write your thoughts about the topic in the comments.

All Articles