Home > Backend Development > Golang > Implement third-party login using Beego and OAuth2

Implement third-party login using Beego and OAuth2

王林
Release: 2023-06-22 20:34:37
Original
1264 people have browsed it

With the rapid development of the Internet, third-party login has become an indispensable part of online life. Third-party login provides users with a more convenient, faster, and safer login method, and is more popular than the traditional registration login method. Currently, third-party logins on the market mainly include large social platforms such as QQ, WeChat, and Weibo. How to quickly implement the third-party login function? This article will introduce how to use Beego and OAuth2 to implement third-party login functionality.

1. Introduction to Beego

Beego is an open source, fast Go programming framework. It is highly flexible and extensible and provides a large number of tools and libraries. Beego can help developers quickly build web applications and provides some important features, such as automatic route management, template system and static file serving.

2. Introduction to OAuth2 protocol

OAuth2 is an authorization framework protocol that allows users to authorize other applications to operate on their behalf without sharing passwords and other sensitive information to third parties. Users access third-party services. This protocol defines four roles: resource owner, resource server, client, and authentication server. Among them, the resource owner refers to the user with access rights, the resource server refers to the server that hosts the information resources, the client refers to the software program that requests access to protected resources, and the authentication server refers to verifying the client's identity and authorizing access to protected resources. services.

3. Use Beego and OAuth2 to implement third-party login

  1. Create Beego project

First, we need to create a Beego project for local development and testing. Use the following command (Beego needs to be installed first):

bee new thirdpartylogin
Copy after login
  1. Install the necessary libraries

We need to install some necessary libraries, including github.com/astaxie /beego and github.com/astaxie/beego/orm, can be installed using the following command:

go get github.com/astaxie/beego
go get github.com/astaxie/beego/orm
Copy after login
  1. Create database

us A database needs to be created to store user information and third-party login information. You can use MySQL or PostgreSQL databases. In this article, we use the MySQL database. The following is the SQL statement to create the user table and third-party login table:

CREATE TABLE `user` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(64) NOT NULL,
  `password` varchar(128) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE `oauth` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `user_id` int(11) unsigned NOT NULL,
  `provider` varchar(64) NOT NULL,
  `provider_user_id` varchar(64) NOT NULL,
  `access_token` varchar(128) NOT NULL,
  `refresh_token` varchar(128) NOT NULL,
  `expire_at` int(11) unsigned NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
Copy after login
  1. Configuring third-party login

We need to use third-party login for authentication. There are currently a variety of third-party login methods on the market, including large social platforms such as QQ, WeChat, and Weibo. Let’s take QQ login as an example to explain.

First, we need to register an application on the QQ Internet Open Platform (https://connect.qq.com/) to obtain App ID and App Key. Secondly, we need to add the following code to the Beego project to obtain user authorization:

func QQLogin(c *beego.Controller) {
    var state = c.GetString("state")
    var oauth = conf.GetQQOAuthConfig(state)

    authURL := oauth.AuthCodeURL(state)
    c.Redirect(http.StatusTemporaryRedirect, authURL)
} 
Copy after login

In the above code, the state parameter is used to identify the user request, oauth object Contains the configuration information required for QQ login. We use the AuthCodeURL method to generate the authorization address and redirect the user to the authorization page.

Next, we need to add the following code to receive the QQ callback request and obtain the access token:

func QQLoginCallback(c *beego.Controller) {
    var state = c.GetString("state")
    var code = c.GetString("code")
    var oauth = conf.GetQQOAuthConfig(state)

    token, err := oauth.Exchange(context.TODO(), code)
    if err != nil {
        log.Println(err)
        c.Abort("500")
    }

    data, err := fetchQQUserInfo(token.AccessToken)
    if err != nil {
        log.Println(err)
        c.Abort("500")
    }

    openid := data.GetString("openid")
    if openid == "" {
        log.Println("openid is blank")
        c.Abort("500")
    }

    account := models.GetAccountByProvider("qq", openid)
    if account != nil {
        _ = models.UpdateAccountAccessToken(account, token.AccessToken)
        c.Redirect(http.StatusTemporaryRedirect, "/")
    } else {
        err := models.CreateAccount("qq", openid, token.AccessToken)
        if err != nil {
            log.Println(err)
            c.Abort("500")
        }

        c.Redirect(http.StatusTemporaryRedirect, "/")
    }
}
Copy after login

In the above code, we use the Exchange method to obtain the access token , use the fetchQQUserInfo method to obtain QQ user information, where openid is used to uniquely identify the QQ user. Next, we check whether the QQ user record exists in the database, and if so, update its access token, otherwise create a new account record.

  1. Authentication and Authorization

Finally, we need to add the authentication and authorization function to ensure that the user has logged in and authorized through a third party.

func AuthRequired(handler http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        sess, err := store.Get(r, "session")
        if err != nil {
            http.Error(w, err.Error(), http.StatusInternalServerError)
            return
        }

        if _, ok := sess.Values["user_id"]; !ok {
            w.Header().Set("Location", "/login")
            w.WriteHeader(http.StatusSeeOther)
            return
        }

        handler.ServeHTTP(w, r)
    })
}
Copy after login

In the above code, we check if the user ID exists in the session, if not, redirect to the login page, otherwise continue processing the request.

4. Summary

This article introduces how to use Beego and OAuth2 to implement third-party login. We use QQ login as an example to introduce how to obtain user authorization, obtain access tokens, check user records and other functions. Using Beego and OAuth2 to implement the third-party login function can provide users with a more convenient, faster, and safer login method, and can also bring developers a more efficient and better development experience.

The above is the detailed content of Implement third-party login using Beego and OAuth2. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template