Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
101 changes: 34 additions & 67 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,111 +1,78 @@
基于Golang的OAuth2服务实现
=======================
OAuth 2.0
=========
> [OAuth 2.0](http://oauth.net/2/) is the next evolution of the OAuth protocol which was originally created in late 2006.

> 完全模块化、支持http/fasthttp的服务端处理、令牌存储支持redis/mongodb
[![GoDoc](https://godoc.org/gopkg.in/oauth2.v3?status.svg)](https://godoc.org/gopkg.in/oauth2.v3)
[![Go Report Card](https://goreportcard.com/badge/gopkg.in/oauth2.v3)](https://goreportcard.com/report/gopkg.in/oauth2.v3)

[![GoDoc](https://godoc.org/gopkg.in/oauth2.v2?status.svg)](https://godoc.org/gopkg.in/oauth2.v2)
[![Go Report Card](https://goreportcard.com/badge/gopkg.in/oauth2.v2)](https://goreportcard.com/report/gopkg.in/oauth2.v2)
Quick Start
-----------

获取
----
### Download and install

``` bash
$ go get -u gopkg.in/oauth2.v2/...
$ go get -u gopkg.in/oauth2.v3/...
```

HTTP服务端
--------
### Create file `server.go`

``` go
package main

import (
"log"
"net/http"

"gopkg.in/oauth2.v2/manage"
"gopkg.in/oauth2.v2/models"
"gopkg.in/oauth2.v2/server"
"gopkg.in/oauth2.v2/store/client"
"gopkg.in/oauth2.v2/store/token"
"gopkg.in/oauth2.v3/manage"
"gopkg.in/oauth2.v3/server"
"gopkg.in/oauth2.v3/store/token"
)

func main() {
manager := manage.NewRedisManager(
&token.RedisConfig{Addr: "192.168.33.70:6379"},
)
manager.MapClientStorage(client.NewTempStore())
srv := server.NewServer(server.NewConfig(), manager)

srv.SetUserAuthorizationHandler(func(w http.ResponseWriter, r *http.Request) (userID string, err error) {
// validation and to get the user id
userID = "000000"
return
})
http.HandleFunc("/authorize", func(w http.ResponseWriter, r *http.Request) {
authReq, err := srv.GetAuthorizeRequest(r)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// TODO: 登录验证、授权处理
authReq.UserID = "000000"

err = srv.HandleAuthorizeRequest(w, authReq)
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) {
err := srv.HandleTokenRequest(w, r)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
}
})

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

```

FastHTTP服务端
-------------

``` go
srv := server.NewFastServer(server.NewConfig(), manager)

fasthttp.ListenAndServe(":9096", func(ctx *fasthttp.RequestCtx) {
switch string(ctx.Request.URI().Path()) {
case "/authorize":
authReq, err := srv.GetAuthorizeRequest(ctx)
if err != nil {
ctx.Error(err.Error(), 400)
return
}
authReq.UserID = "000000"
// TODO: 登录验证、授权处理
err = srv.HandleAuthorizeRequest(ctx, authReq)
if err != nil {
ctx.Error(err.Error(), 400)
}
case "/token":
err := srv.HandleTokenRequest(ctx)
if err != nil {
ctx.Error(err.Error(), 400)
}
}
})
```

测试
----
> [goconvey](https://github.com/smartystreets/goconvey)
### Build and run

``` bash
$ goconvey -port=9092
$ go build server.go
$ ./server
```

范例
----
Features
--------

* Based on the [RFC 6749](https://tools.ietf.org/html/rfc6749) implementation
* Easy to use
* Modularity
* Flexible
* Elegant

模拟授权码模式的测试范例,请查看[example](/example)
Example
-------

Simulation examples of authorization code model, please check [example](/example)

License
-------
Expand Down
22 changes: 12 additions & 10 deletions const.go
Original file line number Diff line number Diff line change
@@ -1,31 +1,33 @@
package oauth2

// ResponseType 定义授权类型
// ResponseType Response Type
type ResponseType string

const (
// Code 授权码类型
// Code Authorization code type
Code ResponseType = "code"
// Token 令牌类型
// Token Token type
Token ResponseType = "token"
)

func (rt ResponseType) String() string {
return string(rt)
}

// GrantType 定义授权模式
// GrantType Authorization Grant
type GrantType string

const (
// AuthorizationCodeCredentials 授权码模式
AuthorizationCodeCredentials GrantType = "authorization_code"
// PasswordCredentials 密码模式
// AuthorizationCode Authorization Code
AuthorizationCode GrantType = "authorization_code"
// PasswordCredentials Resource Owner Password Credentials
PasswordCredentials GrantType = "password"
// ClientCredentials 客户端模式
// ClientCredentials Client Credentials
ClientCredentials GrantType = "clientcredentials"
// RefreshCredentials 更新令牌模式
RefreshCredentials GrantType = "refreshtoken"
// Refreshing Refresh Token
Refreshing GrantType = "refreshtoken"
// Implicit Implicit Grant
Implicit GrantType = "__implicit"
)

func (gt GrantType) String() string {
Expand Down
55 changes: 55 additions & 0 deletions errors/error.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
package errors

import "errors"

var (
// ErrUnauthorizedClient unauthorized client
ErrUnauthorizedClient = errors.New("unauthorized_client")

// ErrAccessDenied access denied
ErrAccessDenied = errors.New("access_denied")

// ErrUnsupportedResponseType unsupported response type
ErrUnsupportedResponseType = errors.New("unsupported_response_type")

// ErrInvalidScope invalid scope
ErrInvalidScope = errors.New("invalid_scope")

// ErrInvalidRequest invalid request
ErrInvalidRequest = errors.New("invalid_request")

// ErrInvalidClient invalid client
ErrInvalidClient = errors.New("invalid_client")

// ErrInvalidGrant invalid grant
ErrInvalidGrant = errors.New("invalid_grant")

// ErrUnsupportedGrantType unsupported grant type
ErrUnsupportedGrantType = errors.New("unsupported_grant_type")

// ErrServerError server error
ErrServerError = errors.New("server_error")
)

var (
// ErrNilValue Nil Value
ErrNilValue = errors.New("nil value")

// ErrInvalidRedirectURI invalid redirect uri
ErrInvalidRedirectURI = errors.New("invalid redirect uri")

// ErrInvalidAuthorizeCode invalid authorize code
ErrInvalidAuthorizeCode = errors.New("invalid authorize code")

// ErrInvalidAccessToken invalid access token
ErrInvalidAccessToken = errors.New("invalid access token")

// ErrInvalidRefreshToken invalid refresh token
ErrInvalidRefreshToken = errors.New("invalid refresh token")

// ErrExpiredAccessToken expired access token
ErrExpiredAccessToken = errors.New("expired access token")

// ErrExpiredRefreshToken expired refresh token
ErrExpiredRefreshToken = errors.New("expired refresh token")
)
19 changes: 9 additions & 10 deletions example/README.md
Original file line number Diff line number Diff line change
@@ -1,25 +1,24 @@
OAuth2授权码模式模拟
=================
Authorization code simulation
=============================

运行服务端
--------
> 运行fasthttp服务端,请使用`cd example/fastserver`
Run Server
---------

```
``` bash
$ cd example/server
$ go run main.go
```

运行客户端
--------
Run Client
----------

```
$ cd example/client
$ go run main.go
```

打开浏览器
--------
Open the browser
----------------

[http://localhost:9094](http://localhost:9094)

Expand Down
2 changes: 1 addition & 1 deletion example/client/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,6 @@ func main() {
io.Copy(w, resp.Body)
})

log.Println("OAuth2 client is running at 9094 port.")
log.Println("Client is running at 9094 port.")
log.Fatal(http.ListenAndServe(":9094", nil))
}
50 changes: 0 additions & 50 deletions example/fastserver/main.go

This file was deleted.

Loading