The use of OAuth2.0 in Go combat--golang (login verification using Google account)

Source: Internet
Author: User
Tags oauth
This is a creation in Article, where the information may have evolved or changed.

Life goes on and on go Go go!!!

Today continue to share the Golang in the certification problem, previously wrote two:

One is about basic certification: Go Combat – Basic Certified HTTP (Basic authentication)

One is about JWT: Go combat –golang using JWT (JSON Web Token)

Here is an introduction to the use of oauth2.0 in Golang.

OAuth2.0

OAuth2.0 is the next version of the OAuth protocol, but does not backwards-compatible with OAuth 1.0, which completely abolishes the OAuth1.0. OAuth 2.0 focuses on the simplicity of the client developer. Either represent the user through an approved interaction between the resource owner and the HTTP service provider, or allow third-party apps to gain access on behalf of the user. It also provides a dedicated certification process for Web applications, desktop applications, mobile phones, and living room devices. In October 2012, the OAuth 2.0 protocol was formally released as RFC 6749.

The three parties involved in the process of certification and authorization include:
1, the service provider, the user to use the service provider to store protected resources, such as photos, videos, contacts list.
2. The user, the owner of the protected resource stored in the service provider.
3, the client, to access the service provider resources of third-party applications, usually the site, such as providing photo printing service site. Before the authentication process, the client will request a client identity from the service provider.

The process of authenticating and authorizing with OAuth is as follows:

(A) After the user opens the client, the client asks the user to grant authorization.
(B) The user agrees to grant the client authorization.
(C) The client uses the authorization obtained in the previous step to request a token from the authentication server.
(D) After the authentication server authenticates the client, it confirms the error and agrees to issue the token.
(E) The client uses a token to request a resource from the resource server.
(F) The resource server confirms that the token is correct and agrees to open the resource to the client

For more detailed information, refer to: http://www.ruanyifeng.com/blog/2014/05/oauth_2_0.html

Package Oauth2

Package Oauth2 provides support for making OAuth2 authorized and authenticated HTTP requests. IT can additionally grant authorization with Bearer JWT.

Get:

go get golang.org/x/oauth2

Type Config

typeConfigstruct{//ClientID is the application ' s ID.ClientIDstring    //Clientsecret is the application ' s secret.Clientsecretstring    //Endpoint contains the resource server ' s token Endpoint    //URLs. These is constants specific to each server and is    //often available via site-specific packages, such as    //Google. Endpoint or GitHub. Endpoint.Endpoint Endpoint//RedirectURL is the URL to redirect users going through    //The OAuth flow, after the resource owner ' s URLs.RedirectURLstring    //Scope specifies optional requested permissions.Scopes []string}

Func (*config) Authcodeurl

funcstringstring

Authcodeurl returns a URL to OAuth 2.0 provider ' s consent page, asks for permissions for the required scopes Explicitl Y.

Func (*config) Exchange

funcstring) (*Token, error)

Exchange converts an authorization code into a token.

Type Endpoint

typestruct {    AuthURL  string    string}

Endpoint contains the OAuth 2.0 provider ' s authorization and token Endpoint URLs.

Login verification with Google account

1. Go to Google Cloud Platform to create a project

2. Credentials, create credentials, select OAuth Client ID

3.
Select the app type for web App
Input JavaScript Source: http://localhost:8000
Enter the redirected uri:http://localhost:8000/googlecallback that has been authorized

4. Log the client ID and client key

Coding

 PackageMainImport("FMT"    "Io/ioutil"    "Net/http"    "Golang.org/x/oauth2")ConstHtmlindex =' varEndpotin = Oauth2. endpoint{AuthUrl:"Https://accounts.google.com/o/oauth2/auth", Tokenurl:"Https://accounts.google.com/o/oauth2/token",}varGoogleoauthconfig = &oauth2. config{ClientID:"your_client_id", Clientsecret:"Your_client_secret", RedirectURL:"Http://localhost:8000/GoogleCallback", Scopes: []string{"Https://www.googleapis.com/auth/userinfo.profile","Https://www.googleapis.com/auth/userinfo.email"}, Endpoint:endpotin,}ConstOauthstatestring ="Random"funcMain () {http. Handlefunc ("/", Handlemain) http. Handlefunc ("/googlelogin", Handlegooglelogin) http. Handlefunc ("/googlecallback", Handlegooglecallback) fmt. Println (http. Listenandserve (": 8000",Nil))}funcHandlemain (w http. Responsewriter, R *http. Request) {fmt. fprintf (W, Htmlindex)}funcHandlegooglelogin (w http. Responsewriter, R *http. Request) {URL: = Googleoauthconfig.authcodeurl (oauthstatestring) fmt. Println (URL) http. Redirect (W, r, URL, http. Statustemporaryredirect)}funcHandlegooglecallback (w http. Responsewriter, R *http. Request) {state: = R.formvalue ("State")ifState! = oauthstatestring {fmt. Printf ("Invalid OAuth state, expected '%s ', got '%s ' \ n", oauthstatestring, State) HTTP. Redirect (W, R,"/", HTTP. Statustemporaryredirect)return} FMT. PRINTLN (state) Code: = R.formvalue ("Code") FMT. PRINTLN (code) token, Err: = Googleoauthconfig.exchange (oauth2. Nocontext, code) FMT. PRINTLN (token)ifErr! =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)deferResponse. Body.close () contents, err: = Ioutil. ReadAll (response. Body) fmt. fprintf (W,"Content:%s\n", contents)}

Change ClientID and Clientsecret to your own!!!

Browser access: http://localhost:8000

Click Log in with Google

Results:

"id""114512230444013345330""email""wangshubo1989@126.com""verified_email"true"name""王书博""given_name""书博""family_name""王""picture""https://lh3.googleusercontent.com/-XdUIqdMkCWA/AAAAAAAAAAI/AAAAAAAAAAA/4252rscbv5M/photo.jpg""locale""zh-CN"}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.