【实践】如何用GO实现OAuth2授权功能

96
笔名辉哥
0.9 2019.05.17 11:29* 字数 426

1, 摘要

本文讲解了用GO实现OAuth2授权功能的调试方法,具体代码请参考工程文件,原理请参考另外2篇文章《OAuth 2.0 的四种方式》, 《OAuth2介绍与使用》

2,工程下载和编译

加入辉哥区块链下载对应的工程文件。

3,凭证式(client_credentials)模式授权

3.1 创建文件

在gopkg.in\oauth2.v3\example\server的目录下创建 server2.go文件。

package main

import (
    "log"
    "net/http"

    "gopkg.in/oauth2.v3/errors"
    "gopkg.in/oauth2.v3/manage"
    "gopkg.in/oauth2.v3/models"
    "gopkg.in/oauth2.v3/server"
    "gopkg.in/oauth2.v3/store"
)

func main() {
    manager := manage.NewDefaultManager()
    // token memory store
    manager.MustTokenStorage(store.NewMemoryTokenStore())

    // client memory store
    clientStore := store.NewClientStore()
    clientStore.Set("000000", &models.Client{
        ID:     "000000",
        Secret: "999999",
        Domain: "http://localhost",
    })
    manager.MapClientStorage(clientStore)

    srv := server.NewDefaultServer(manager)
    srv.SetAllowGetAccessRequest(true)
    srv.SetClientInfoHandler(server.ClientFormHandler)

    srv.SetInternalErrorHandler(func(err error) (re *errors.Response) {
        log.Println("Internal Error:", err.Error())
        return
    })

    srv.SetResponseErrorHandler(func(re *errors.Response) {
        log.Println("Response Error:", re.Error.Error())
    })

    http.HandleFunc("/authorize", func(w http.ResponseWriter, r *http.Request) {
        err := srv.HandleAuthorizeRequest(w, r)
        if err != nil {
            http.Error(w, err.Error(), http.StatusBadRequest)
        }
    })

    http.HandleFunc("/token", func(w http.ResponseWriter, r *http.Request) {
        srv.HandleTokenRequest(w, r)
    })

    log.Fatal(http.ListenAndServe(":9096", nil))
}

3.2 编译和运行

go build server2.go

./server2

3.3在本地浏览器打开

http://localhost:9096/token?grant_type=client_credentials&client_id=000000&client_secret=999999&scope=read

浏览器会返回JSON格式的ACCESS TOKEN授权码。

{
    "access_token": "IPBCRFH4N7CHPKWSXDDAQW",
    "expires_in": 7200,
    "scope": "read",
    "token_type": "Bearer"
}

截图:

4,完整四种授权方式代码

4.1 编译/运行授权服务器

进入GO 目录工程的gopkg.in\oauth2.v3\example\server下,编译运行OAUTH服务。


$ cd example/server
$ go build server.go
$ ./server

运行截图:

4.2 编译/运行客户端服务器

进入GO 目录工程的gopkg.in\oauth2.v3\example\client下,编译运行OAUTH服务。

$ cd example/client
$ go build client.go
$ ./client

运行截图:

4.3 授权码模式授权测试

4.3.1 浏览器打开

http://localhost:9094

{
  "access_token": eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiIyMjIyMjIiLCJleHAiOjE1NTgwNzAxNTMsInN1YiI6IjAwMDAwMCJ9.RPDu6BkZ9_ZFUWqbMkNbcwMukt2NXbd9S9GAdhQ0ZVtV7qfeBslvOQLyfHKPVT30dFaUoRZFxuIXTQCotN6Sqw",
  "token_type": "Bearer",
  "refresh_token": "E_DW6S_EURIMCJ1NATXSJA",
  "expiry": "2019-05-17T13:15:53.5879631+08:00""
}

运行截图:

4.3.2 使用access token

在浏览器输入 http://localhost:9094/try
有了ACCESS TOKEN,就可以直接打开客户端主页了,完成登录后的呈现。

{
  "client_id": "222222",
  "expires_in": 7195,
  "user_id": "000000"
}

4.3.3 更新 access token

浏览器输入 http://localhost:9094/refresh

{
  "access_token": "eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiIyMjIyMjIiLCJleHAiOjE1NTgwNzAzNTMsInN1YiI6IjAwMDAwMCJ9._El-BI4GWjqcpjXXmFr5ClIYrIoWeLWSiaDCECSw-2tHhffvbzdt8p0DzD_LH9V1mDgkrDo894ZLDE3W1uM4vA",
  "token_type": "Bearer",
  "refresh_token": "ABZBEXS4XYOVHYYOLQYSUQ",
  "expiry": "2019-05-17T13:19:13.9847635+08:00"
}

4.4 密码授权模式

浏览器输入 http://localhost:9094/pwd

{
  "access_token": "eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiIyMjIyMjIiLCJleHAiOjE1NTgwNzA0NTUsInN1YiI6InRlc3QifQ.X0ejwzSjzrWYz2Uoqm0jKkIo9hPcJvdDCW0spFmgCZyRzmgGWmKSjjNdUEfDVg4yM80zN0HJLmJRYhC4nG_mvQ",
  "token_type": "Bearer",
  "refresh_token": "YFKHVYGYVHSQKZ-9DKXVWW",
  "expiry": "2019-05-17T13:20:55.3377359+08:00"
}

截图输出:

4.5 凭证式(Client Credentials)授权模式

浏览器输入 http://localhost:9094/client

{
  "access_token": "eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiIyMjIyMjIiLCJleHAiOjE1NTgwNzA4ODZ9.F4qFiGc3BDb8dY_kOFzkLHa775bF9EliI6a47DFNQnQ4rn_qE9i4tD7rsC7YDG6IcNXtXWCh8VvGaUlVYKTYjQ",
  "token_type": "Bearer",
  "expiry": "2019-05-17T13:28:06.817969+08:00"
}

输出截图:

辉哥的技术投资之路
Gupao