MCPcopy
hub / github.com/go-oauth2/oauth2

github.com/go-oauth2/oauth2 @v4.5.4 sqlite

repository ↗ · DeepWiki ↗ · release v4.5.4 ↗
292 symbols 898 edges 34 files 192 documented · 66%
README

Golang OAuth 2.0 Server

An open protocol to allow secure authorization in a simple and standard method from web, mobile and desktop applications.

Build Codecov ReportCard GoDoc License

Protocol Flow

     +--------+                               +---------------+
     |        |--(A)- Authorization Request ->|   Resource    |
     |        |                               |     Owner     |
     |        |<-(B)-- Authorization Grant ---|               |
     |        |                               +---------------+
     |        |
     |        |                               +---------------+
     |        |--(C)-- Authorization Grant -->| Authorization |
     | Client |                               |     Server    |
     |        |<-(D)----- Access Token -------|               |
     |        |                               +---------------+
     |        |
     |        |                               +---------------+
     |        |--(E)----- Access Token ------>|    Resource   |
     |        |                               |     Server    |
     |        |<-(F)--- Protected Resource ---|               |
     +--------+                               +---------------+

Quick Start

Download and install

go get -u -v github.com/go-oauth2/oauth2/v4/...

Create file server.go

package main

import (
    "log"
    "net/http"

    "github.com/go-oauth2/oauth2/v4/errors"
    "github.com/go-oauth2/oauth2/v4/manage"
    "github.com/go-oauth2/oauth2/v4/models"
    "github.com/go-oauth2/oauth2/v4/server"
    "github.com/go-oauth2/oauth2/v4/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.UserAuthorizationHandler = func(w http.ResponseWriter, r *http.Request) (userID string, err error) {
        return "000000", nil
    }

    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))
}

Build and run

go build server.go

./server

Open in your web browser

Authorization Request: http://localhost:9096/authorize?client_id=000000&response_type=code

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

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

Features

  • Easy to use
  • Based on the RFC 6749 implementation
  • Token storage support TTL
  • Support custom expiration time of the access token
  • Support custom extension field
  • Support custom scope
  • Support jwt to generate access tokens

Example

A complete example of simulation authorization code model

Simulation examples of authorization code model, please check example

Use jwt to generate access tokens


import (
    "github.com/go-oauth2/oauth2/v4/generates"
    "github.com/dgrijalva/jwt-go"
)

// ...
manager.MapAccessGenerate(generates.NewJWTAccessGenerate("", []byte("00000000"), jwt.SigningMethodHS512))

// Parse and verify jwt access token
token, err := jwt.ParseWithClaims(access, &generates.JWTAccessClaims{}, func(t *jwt.Token) (interface{}, error) {
    if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
        return nil, fmt.Errorf("parse error")
    }
    return []byte("00000000"), nil
})
if err != nil {
    // panic(err)
}

claims, ok := token.Claims.(*generates.JWTAccessClaims)
if !ok || !token.Valid {
    // panic("invalid token")
}

Store Implements

Handy Utilities

MIT License

Copyright (c) 2016 Lyric

Extension points exported contracts — how you extend this code

AuthorizeGenerate (Interface)
AuthorizeGenerate generate the authorization code interface [3 implementers]
generate.go
ClientInfo (Interface)
ClientInfo the client information model interface [1 implementers]
model.go
ClientStore (Interface)
ClientStore the client information storage interface [1 implementers]
store.go
Manager (Interface)
Manager authorization management interface [1 implementers]
manage.go
ValidateURIHandler (FuncType)
ValidateURIHandler validates that redirectURI is contained in baseURI
manage/util.go
ClientInfoHandler (FuncType)
ClientInfoHandler get client info from request
server/handler.go
AccessGenerate (Interface)
AccessGenerate generate the access and refresh tokens interface [3 implementers]
generate.go
TokenInfo (Interface)
TokenInfo the token information model interface [1 implementers]
model.go

Core symbols most depended-on inside this repo

New
called by 32
model.go
Set
called by 28
store/client.go
String
called by 17
const.go
GetAccess
called by 10
model.go
GetRefresh
called by 10
model.go
MapClientStorage
called by 9
manage/manager.go
GetAccessExpiresIn
called by 8
model.go
GetRefreshExpiresIn
called by 8
model.go

Shape

Method 186
Function 59
FuncType 18
Struct 17
Interface 9
TypeAlias 3

Languages

Go100%

Modules by API surface

model.go43 symbols
models/token.go35 symbols
manage/manager.go30 symbols
server/server.go22 symbols
server/handler.go22 symbols
server/server_config.go20 symbols
store/token.go13 symbols
server/server_test.go11 symbols
store.go10 symbols
manage.go10 symbols
generates/jwt_access.go9 symbols
example/server/server.go7 symbols

Dependencies from manifests, versioned

github.com/ajg/formv1.5.1 · 1×
github.com/andybalholm/brotliv1.0.4 · 1×
github.com/bytedance/gopkgv0.0.0-2022112212563 · 1×
github.com/fasthttp-contrib/websocketv0.0.0-2016051121553 · 1×
github.com/fatih/structsv1.1.0 · 1×
github.com/gavv/httpexpectv2.0.0+incompatible · 1×
github.com/go-session/session/v3v3.2.1 · 1×
github.com/google/go-querystringv1.0.0 · 1×

For agents

$ claude mcp add oauth2 \
  -- python -m otcore.mcp_server <graph>

⬇ download graph artifact