oauth2

package module
v0.4.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 6, 2023 License: MIT Imports: 16 Imported by: 5

README

oauth2

Usage

go get -u github.com/nilorg/oauth2

Import

import "github.com/nilorg/oauth2"

例子

oauth2-server

server/client

文档参考

  1. 《理解OAuth 2.0》阮一峰
  2. 《RFC 6749》 | 《RFC 6749》
  3. 《OAuth 2.0 Device Authorization Grant(RFC8628)》
  4. 《OAuth 2.0 Token Introspection(RFC7662)》
  5. 《OAuth 2.0 Token Revocation(RFC7009)》
AuthorizationCode

授权码模式(authorization code)是功能最完整、流程最严密的授权模式。

它的特点就是通过客户端的后台服务器,与"服务提供商"的认证服务器进行互动。

Implicit

简化模式(implicit grant type)不通过第三方应用程序的服务器,直接在浏览器中向认证服务器申请令牌,跳过了"授权码"这个步骤,因此得名。

所有步骤在浏览器中完成,令牌对访问者是可见的,且客户端不需要认证。

ResourceOwnerPasswordCredentials

密码模式(Resource Owner Password Credentials Grant)中,用户向客户端提供自己的用户名和密码。

客户端使用这些信息,向"服务商提供商"索要授权。

在这种模式中,用户必须把自己的密码给客户端,但是客户端不得储存密码。

这通常用在用户对客户端高度信任的情况下,比如客户端是操作系统的一部分,或者由一个著名公司出品。

而认证服务器只有在其他授权模式无法执行的情况下,才能考虑使用这种模式。

ClientCredentials

客户端模式(Client Credentials Grant)指客户端以自己的名义,而不是以用户的名义,向"服务提供商"进行认证。

严格地说,客户端模式并不属于OAuth框架所要解决的问题。

在这种模式中,用户直接向客户端注册,客户端以自己的名义要求"服务提供商"提供服务,其实不存在授权问题。

DeviceCode

设备模式(Device Code)

TokenIntrospection

内省端点(Token Introspection)

TokenRevocation

Token销毁端点(Token Revocation)

Server

package main

import (
	"fmt"
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/nilorg/oauth2"
)

var (
	clients = map[string]string{
		"oauth2_client": "password",
	}
)

func main() {
	srv := oauth2.NewServer()
	srv.VerifyClient = func(basic *oauth2.ClientBasic) (err error) {
		pwd, ok := clients[basic.ID]
		if !ok {
			err = oauth2.ErrInvalidClient
			return
		}
		basic = &oauth2.ClientBasic{
			ID:     basic.ID,
			Secret: pwd,
		}
		return
	}
	srv.VerifyClientID = func(clientID string) (err error) {
		_, ok := clients[clientID]
		if !ok {
			err = oauth2.ErrInvalidClient
		}
		return
	}
	srv.VerifyCode = func(code, clientID, redirectURI string) (value *oauth2.CodeValue, err error) {
		//err = oauth2.ErrUnauthorizedClient
		// 查询缓存/数据库中的code信息
		value = &oauth2.CodeValue{
			ClientID:    clientID,
			RedirectURI: redirectURI,
			Scope:       []string{"a", "b", "c"},
		}
		return
	}
	srv.GenerateCode = func(clientID, openID, redirectURI string, scope []string) (code string, err error) {
		code = oauth2.RandomCode()
		return
	}
	srv.VerifyRedirectURI = func(clientID, redirectURI string) (err error) {
		fmt.Println(clientID)
		fmt.Println(redirectURI)
		// err = oauth2.ErrInvalidRedirectURI
		return
	}

	srv.VerifyPassword = func(username, password string) (openID string, err error) {
		if username != "a" || password != "b" {
			err = oauth2.ErrUnauthorizedClient
			return
		}
		openID = "xxxx"
		return
	}

	srv.VerifyScope = func(scopes []string, clientID string) (err error) {
		// err = oauth2.ErrInvalidScope
		return
	}

	srv.GenerateAccessToken = oauth2.NewDefaultGenerateAccessToken([]byte("xxxxx"))
	srv.RefreshAccessToken = oauth2.NewDefaultRefreshAccessToken([]byte("xxxxx"))
	srv.ParseAccessToken = oauth2.NewDefaultParseAccessToken([]byte("xxxxx"))

	srv.GenerateDeviceAuthorization = func(issuer, verificationURI, clientID, scope string) (resp *oauth2.DeviceAuthorizationResponse, err error) {
		resp = &oauth2.DeviceAuthorizationResponse{
			DeviceCode:            oauth2.RandomCode(),
			UserCode:              oauth2.RandomUserCode(),
			VerificationURI:       verificationURI,
			VerificationURIQrcode: "",
			ExpiresIn:             0,
			Interval:              5,
		}
		return
	}

	srv.VerifyDeviceCode = func(deviceCode, clientID string) (value *oauth2.DeviceCodeValue, err error) {
		// err = oauth2.ErrAuthorizationPending
		return
	}

	srv.Init()

	// =============Http Default=============
	// http.HandleFunc("/authorize", srv.HandleAuthorize)
	// http.HandleFunc("/token", srv.HandleToken)
	// if err := http.ListenAndServe(":8003", srv); err != nil {
	// 	fmt.Printf("%+v\n", err)
	// }

	// =============Gin=============
	r := gin.Default()
	oauth2Group := r.Group("/oauth2")
	{
		oauth2Group.GET("/authorize", func(c *gin.Context) {
			srv.HandleAuthorize(c.Writer, c.Request)
		})
		oauth2Group.POST("/token", func(c *gin.Context) {
			srv.HandleToken(c.Writer, c.Request)
		})
		oauth2Group.POST("/device_authorization", func(c *gin.Context) {
			srv.HandleDeviceAuthorization(c.Writer, c.Request)
		})
	}

	if err := http.ListenAndServe(":8003", r); err != nil {
		fmt.Printf("%+v\n", err)
	}
}

Client

package main

import (
	"github.com/gin-gonic/gin"
	"github.com/nilorg/oauth2"
	"github.com/nilorg/pkg/logger"
)

var (
	client *oauth2.Client
)

func init()  {
	logger.Init()
	client = oauth2.NewClient("http://localhost:8003", "oauth2_client", "password")
	client.Log = logger.Default()
}
func main() {
	r := gin.Default()
	r.GET("/ping", func(c *gin.Context) {
		//err := client.AuthorizeImplicit(c.Writer, "http://localhost:8080/callback", "test", "aaaaa")
		//if err != nil {
		//	logger.Errorln(err)
		//	return
		//}
		err := client.AuthorizeAuthorizationCode(c.Writer, "http://localhost:8080/callback", "test", "bbbbb")
		if err != nil {
			logger.Errorln(err)
			return
		}
	})
	r.GET("/callback", func(c *gin.Context) {
		code := c.Query("code")
		state := c.Query("state")
		token, err := client.TokenAuthorizationCode(code, c.Request.URL.String(), state)
		if err != nil {
			c.JSON(200, gin.H{
				"message": "callback",
				"err":     err.Error(),
			})
		} else {
			c.JSON(200, gin.H{
				"message": "callback",
				"token":   token,
			})
		}
	})

	r.Run() // listen and serve on 0.0.0.0:8080
}

jwt playload

标准中注册的声明 (建议但不强制使用) :

iss: 令牌颁发者。它表示该令牌是由谁创建的,在好很多OAuth部署中会将它设为授权服务器的URL。该声明是一个字符串

sub: 令牌的主体。它表示该令牌是关于谁的,在很多OAuth部署中会将它设为资源拥有者的唯一标识。在大多数情况下,主题在同一个颁发者的范围内必须是唯一的。该声明是一个字符串

aud: 令牌的受众。它表示令牌的接收者,在很多OAuth部署中,它包含受保护资源的URI或者能够接收该令牌的受保护资源。该声明可以是一个字符串数组,如果只有一个值,也可以是一个不用数组包装的单个字符串

exp: 令牌的过期时间戳。它表示令牌将在何时过期,以便部署应用让令牌自行失效。该声明是一个整数,表示自UNIX新世纪(即格林威治标准时间GMT,1970年1月1日零点)以来的秒数

nbf: 令牌的生效时的时间戳。它表示令牌从什么时候开始生效,以便部署应用可以在令牌生效之前颁发令牌。该声明是一个整数,表示自UNIX新世纪(即格林威治标准时间GMT,1970年1月1日零点)以来的秒数

iat: 令牌颁发时的时间戳。它表示令牌是何时被创建的,它通常是颁发者在生成令牌时的系统时间戳。该声明是一个整数,表示自UNIX新世纪(即格林威治标准时间GMT,1970年1月1日零点)以来的秒数

jti: 令牌的唯一标识符。该声明的值在令牌颁发者创建的每个令牌中都是唯一的,为了防止冲突,它通常是一个密码学随机值。这个值相当于向结构化令牌中加入了一个攻击者无法获得的随机熵组件,有利于防止令牌猜测攻击和重放攻击


公共的声明 : 公共的声明可以添加任何的信息,一般添加用户的相关信息或其他业务需要的必要信息.但不建议添加敏感信息,因为该部分在客户端可解密.

私有的声明 : 私有声明是提供者和消费者所共同定义的声明,一般不建议存放敏感信息,因为base64是对称解密的,意味着该部分信息可以归类为明文信息。

Documentation

Index

Constants

View Source
const (

	// AccessTokenExpire ...
	AccessTokenExpire = time.Second * 3600
	// RefreshTokenExpire ...
	RefreshTokenExpire = AccessTokenExpire / 2
	// TokenTypeBearer ...
	TokenTypeBearer = "Bearer"
	// ScopeRefreshToken ...
	ScopeRefreshToken = "refresh_token"
	// DefaultJwtIssuer ...
	DefaultJwtIssuer = "github.com/nilorg/oauth2"
)
View Source
const (
	// ResponseTypeKey ...
	ResponseTypeKey = "response_type"
	// ClientIDKey ...
	ClientIDKey = "client_id"
	// ClientSecretKey ...
	ClientSecretKey = "client_secret"
	// RedirectURIKey ...
	RedirectURIKey = "redirect_uri"
	// ScopeKey ...
	ScopeKey = "scope"
	// StateKey ...
	StateKey = "state"
	// GrantTypeKey ...
	GrantTypeKey = "grant_type"
	// CodeKey ...
	CodeKey = "code"
	// TokenKey ...
	TokenKey = "token"
	// ErrorKey ...
	ErrorKey = "error"
	// AccessTokenKey ...
	AccessTokenKey = "access_token"
	// TokenTypeKey ...
	TokenTypeKey = "token_type"
	// ClientCredentialsKey ...
	ClientCredentialsKey = "client_credentials"
	// PasswordKey ...
	PasswordKey = "password"
	// UsernameKey ...
	UsernameKey = "username"
	// RefreshTokenKey ...
	RefreshTokenKey = "refresh_token"
	// AuthorizationCodeKey ...
	AuthorizationCodeKey = "authorization_code"
	// DeviceCodeKey ...
	DeviceCodeKey = "device_code"
	// UrnIetfParamsOAuthGrantTypeDeviceCodeKey ...
	UrnIetfParamsOAuthGrantTypeDeviceCodeKey = "urn:ietf:params:oauth:grant-type:device_code"
	// TokenTypeHintKey ...
	TokenTypeHintKey = "token_type_hint"
	// ImplicitKey ...
	ImplicitKey = "implicit"
)

Variables

View Source
var (
	// ErrInvalidRequest 无效的请求
	ErrInvalidRequest = errors.New("invalid_request")
	// ErrUnauthorizedClient 未经授权的客户端
	ErrUnauthorizedClient = errors.New("unauthorized_client")
	// ErrAccessDenied 拒绝访问
	ErrAccessDenied = errors.New("access_denied")
	// ErrUnsupportedResponseType 不支持的response类型
	ErrUnsupportedResponseType = errors.New("unsupported_response_type")
	// ErrUnsupportedGrantType 不支持的grant类型
	ErrUnsupportedGrantType = errors.New("unsupported_grant_type")
	// ErrInvalidGrant 无效的grant
	ErrInvalidGrant = errors.New("invalid_grant")
	// ErrInvalidScope 无效scope
	ErrInvalidScope = errors.New("invalid_scope")
	// ErrTemporarilyUnavailable 暂时不可用
	ErrTemporarilyUnavailable = errors.New("temporarily_unavailable")
	// ErrServerError 服务器错误
	ErrServerError = errors.New("server_error")
	// ErrInvalidClient 无效的客户
	ErrInvalidClient = errors.New("invalid_client")
	// ErrExpiredToken 过期的令牌
	ErrExpiredToken = errors.New("expired_token")
	// ErrAuthorizationPending 授权待定
	// https://tools.ietf.org/html/rfc8628#section-3.5
	ErrAuthorizationPending = errors.New("authorization_pending")
	// ErrSlowDown 轮询太频繁
	// https://tools.ietf.org/html/rfc8628#section-3.5
	ErrSlowDown = errors.New("slow_down")
	// ErrUnsupportedTokenType 不支持的令牌类型
	// https://tools.ietf.org/html/rfc7009#section-4.1.1
	ErrUnsupportedTokenType = errors.New("unsupported_token_type")
)
View Source
var (
	// ErrVerifyClientFuncNil ...
	ErrVerifyClientFuncNil = errors.New("OAuth2 Server VerifyClient Is Nil")
	// ErrVerifyClientIDFuncNil ...
	ErrVerifyClientIDFuncNil = errors.New("OAuth2 Server VerifyClientID Is Nil")
	// ErrVerifyPasswordFuncNil ...
	ErrVerifyPasswordFuncNil = errors.New("OAuth2 Server VerifyPassword Is Nil")
	// ErrVerifyRedirectURIFuncNil ...
	ErrVerifyRedirectURIFuncNil = errors.New("OAuth2 Server VerifyRedirectURI Is Nil")
	// ErrGenerateCodeFuncNil ...
	ErrGenerateCodeFuncNil = errors.New("OAuth2 Server GenerateCode Is Nil")
	// ErrVerifyCodeFuncNil ...
	ErrVerifyCodeFuncNil = errors.New("OAuth2 Server VerifyCode Is Nil")
	// ErrVerifyScopeFuncNil ...
	ErrVerifyScopeFuncNil = errors.New("OAuth2 Server VerifyScope Is Nil")
	// ErrGenerateAccessTokenFuncNil ...
	ErrGenerateAccessTokenFuncNil = errors.New("OAuth2 Server GenerateAccessTokenFunc Is Nil")
	// ErrGenerateDeviceAuthorizationFuncNil ...
	ErrGenerateDeviceAuthorizationFuncNil = errors.New("OAuth2 Server GenerateDeviceAuthorizationFunc Is Nil")
	// ErrVerifyDeviceCodeFuncNil ...
	ErrVerifyDeviceCodeFuncNil = errors.New("OAuth2 Server ErrVerifyDeviceCodeFunc Is Nil")
	// ErrRefreshAccessTokenFuncNil ...
	ErrRefreshAccessTokenFuncNil = errors.New("OAuth2 Server ErrRefreshAccessTokenFuncNil Is Nil")
	// ErrParseAccessTokenFuncNil ...
	ErrParseAccessTokenFuncNil = errors.New("OAuth2 Server ParseAccessTokenFunc Is Nil")
	// ErrVerifyIntrospectionTokenFuncNil ...
	ErrVerifyIntrospectionTokenFuncNil = errors.New("OAuth2 Server VerifyIntrospectionToken Is Nil")
	// ErrTokenRevocationFuncNil ...
	ErrTokenRevocationFuncNil = errors.New("OAuth2 Server TokenRevocation Is Nil")
	// ErrVerifyGrantTypeFuncNil ...
	ErrVerifyGrantTypeFuncNil = errors.New("OAuth2 Server VerifyGrantType Is Nil")
	// ErrInvalidAccessToken 无效的访问令牌
	ErrInvalidAccessToken = errors.New("invalid_access_token")
	// ErrInvalidRedirectURI 无效的RedirectURI
	ErrInvalidRedirectURI = errors.New("invalid_redirect_uri")
	// ErrStateValueDidNotMatch ...
	ErrStateValueDidNotMatch = errors.New("state value did not match")
	// ErrMissingAccessToken ...
	ErrMissingAccessToken = errors.New("missing access token")
	// ErrAccessToken ...
	ErrAccessToken = errors.New("OAuth2 Server AccessToken Is Nil")
)
View Source
var (
	// Errors ...
	Errors = map[string]error{
		ErrVerifyClientFuncNil.Error():   ErrVerifyClientFuncNil,
		ErrInvalidAccessToken.Error():    ErrInvalidAccessToken,
		ErrStateValueDidNotMatch.Error(): ErrStateValueDidNotMatch,
		ErrMissingAccessToken.Error():    ErrMissingAccessToken,

		ErrInvalidRequest.Error():          ErrInvalidRequest,
		ErrUnauthorizedClient.Error():      ErrUnauthorizedClient,
		ErrAccessDenied.Error():            ErrAccessDenied,
		ErrUnsupportedResponseType.Error(): ErrUnsupportedResponseType,
		ErrUnsupportedGrantType.Error():    ErrUnsupportedGrantType,
		ErrInvalidGrant.Error():            ErrInvalidGrant,
		ErrInvalidScope.Error():            ErrInvalidScope,
		ErrTemporarilyUnavailable.Error():  ErrTemporarilyUnavailable,
		ErrServerError.Error():             ErrServerError,
		ErrInvalidClient.Error():           ErrInvalidClient,
		ErrExpiredToken.Error():            ErrExpiredToken,
		ErrAuthorizationPending.Error():    ErrAuthorizationPending,
		ErrSlowDown.Error():                ErrSlowDown,
		ErrUnsupportedTokenType.Error():    ErrUnsupportedTokenType,
	}
	// ErrStatusCodes ...
	ErrStatusCodes = map[error]int{
		ErrInvalidRequest:          http.StatusBadRequest,
		ErrUnauthorizedClient:      http.StatusUnauthorized,
		ErrAccessDenied:            http.StatusForbidden,
		ErrUnsupportedResponseType: http.StatusUnauthorized,
		ErrInvalidScope:            http.StatusBadRequest,
		ErrServerError:             http.StatusInternalServerError,
		ErrTemporarilyUnavailable:  http.StatusServiceUnavailable,
		ErrInvalidClient:           http.StatusUnauthorized,
		ErrInvalidGrant:            http.StatusUnauthorized,
		ErrUnsupportedGrantType:    http.StatusUnauthorized,
		ErrExpiredToken:            http.StatusUnauthorized,
		ErrAuthorizationPending:    http.StatusPreconditionRequired,
		ErrSlowDown:                http.StatusForbidden,
		ErrUnsupportedTokenType:    http.StatusServiceUnavailable,
	}
)
View Source
var (
	// ErrContextNotFoundOpenID 上下文不存在OpenID
	ErrContextNotFoundOpenID = errors.New("OAuth2上下文不存在OpenID")
)

Functions

func NewHS256JwtClaimsToken added in v0.2.1

func NewHS256JwtClaimsToken(claims *JwtClaims, jwtVerifyKey []byte) (string, error)

NewHS256JwtClaimsToken ...

func NewJwtClaimsToken added in v0.2.1

func NewJwtClaimsToken(claims *JwtClaims, algorithm string, key interface{}) (string, error)

NewJwtClaimsToken ...

func NewJwtStandardClaimsToken added in v0.2.1

func NewJwtStandardClaimsToken(claims *JwtStandardClaims, algorithm string, key interface{}) (string, error)

NewJwtStandardClaimsToken ...

func NewJwtToken added in v0.2.0

func NewJwtToken(v interface{}, algorithm string, key interface{}) (string, error)

NewJwtToken ...

func NewOpenIDContext added in v0.0.3

func NewOpenIDContext(ctx context.Context, openID string) context.Context

NewOpenIDContext 创建OpenID上下文

func OpenIDFromContext added in v0.0.3

func OpenIDFromContext(ctx context.Context) (string, error)

OpenIDFromContext ...

func RandomCode

func RandomCode() string

RandomCode 随机Code

func RandomDeviceCode added in v0.2.0

func RandomDeviceCode() string

RandomDeviceCode 随机DeviceCode

func RandomState

func RandomState() string

RandomState 随机State

func RandomUserCode added in v0.2.0

func RandomUserCode() string

RandomUserCode 随机用户code

func RedirectError

func RedirectError(w http.ResponseWriter, r *http.Request, redirectURI *url.URL, err error)

RedirectError 重定向错误

func RedirectSuccess

func RedirectSuccess(w http.ResponseWriter, r *http.Request, redirectURI *url.URL, code string)

RedirectSuccess 重定向成功

func StringSplit added in v0.0.4

func StringSplit(s, sep string) (results []string)

StringSplit strings.Split

func WriterError

func WriterError(w http.ResponseWriter, err error)

WriterError 写入Error

func WriterJSON

func WriterJSON(w http.ResponseWriter, value interface{})

WriterJSON 写入Json

Types

type AccessTokener added in v0.4.2

type AccessTokener interface {
	Generate(ctx context.Context, issuer, clientID, scope, openID string, code *CodeValue) (token *TokenResponse, err error)
	Refresh(ctx context.Context, clientID, refreshToken string) (token *TokenResponse, err error)
	Parse(ctx context.Context, accessToken string) (claims *JwtClaims, err error)
}

AccessTokener AccessToken接口

type Client

type Client struct {
	Log Logger

	ServerBaseURL               string
	AuthorizationEndpoint       string
	TokenEndpoint               string
	IntrospectEndpoint          string
	DeviceAuthorizationEndpoint string
	TokenRevocationEndpoint     string
	ID                          string
	Secret                      string
	// contains filtered or unexported fields
}

Client oauth2 client

func NewClient

func NewClient(serverBaseURL, id, secret string) *Client

NewClient new oauth2 client

func (*Client) AuthorizeAuthorizationCode

func (c *Client) AuthorizeAuthorizationCode(ctx context.Context, w http.ResponseWriter, redirectURI, scope, state string) (err error)

AuthorizeAuthorizationCode ...

func (*Client) AuthorizeImplicit

func (c *Client) AuthorizeImplicit(ctx context.Context, w http.ResponseWriter, redirectURI, scope, state string) (err error)

AuthorizeImplicit ...

func (*Client) DeviceAuthorization added in v0.2.0

func (c *Client) DeviceAuthorization(ctx context.Context, w http.ResponseWriter, scope string) (err error)

DeviceAuthorization ...

func (*Client) RefreshToken

func (c *Client) RefreshToken(ctx context.Context, refreshToken string) (model *TokenResponse, err error)

RefreshToken ...

func (*Client) Token added in v0.3.3

func (c *Client) Token(ctx context.Context, grantType string, values url.Values) (token *TokenResponse, err error)

func (*Client) TokenAuthorizationCode

func (c *Client) TokenAuthorizationCode(ctx context.Context, code, redirectURI, clientID string) (token *TokenResponse, err error)

TokenAuthorizationCode ... TokenAuthorizationCode(code, redirectURI, state string)

func (*Client) TokenClientCredentials

func (c *Client) TokenClientCredentials(ctx context.Context, scope ...string) (model *TokenResponse, err error)

TokenClientCredentials ...

func (*Client) TokenDeviceCode added in v0.2.0

func (c *Client) TokenDeviceCode(ctx context.Context, deviceCode string) (model *TokenResponse, err error)

TokenDeviceCode ...

func (*Client) TokenIntrospect added in v0.2.0

func (c *Client) TokenIntrospect(ctx context.Context, token string, tokenTypeHint ...string) (introspection *IntrospectionResponse, err error)

TokenIntrospect ...

func (*Client) TokenResourceOwnerPasswordCredentials

func (c *Client) TokenResourceOwnerPasswordCredentials(ctx context.Context, username, password string) (model *TokenResponse, err error)

TokenResourceOwnerPasswordCredentials ...

func (*Client) TokenRevocation added in v0.2.0

func (c *Client) TokenRevocation(ctx context.Context, token string, tokenTypeHint ...string) (introspection *IntrospectionResponse, err error)

TokenRevocation token撤销

type ClientBasic

type ClientBasic struct {
	ID     string `json:"client_id"`
	Secret string `json:"client_secret"`
}

ClientBasic 客户端基础

func RequestClientBasic

func RequestClientBasic(r *http.Request) (basic *ClientBasic, err error)

RequestClientBasic 获取请求中的客户端信息

type CodeValue

type CodeValue struct {
	ClientID    string   `json:"client_id"`
	OpenID      string   `json:"open_id"`
	RedirectURI string   `json:"redirect_uri"`
	Scope       []string `json:"scope"`
}

CodeValue code值

func (*CodeValue) MarshalBinary added in v0.0.4

func (code *CodeValue) MarshalBinary() ([]byte, error)

MarshalBinary json

func (*CodeValue) UnmarshalBinary added in v0.0.4

func (code *CodeValue) UnmarshalBinary(data []byte) error

UnmarshalBinary json

type CustomGrantTypeAuthenticationFunc added in v0.3.3

type CustomGrantTypeAuthenticationFunc func(ctx context.Context, client *ClientBasic, req *http.Request) (openID string, err error)

CustomGrantTypeAuthenticationFunc 自定义GrantType身份验证委托

type DefaultAccessToken added in v0.4.2

type DefaultAccessToken struct {
	AccessTokener
	JwtVerifyKey []byte
}

func NewDefaultAccessToken added in v0.4.2

func NewDefaultAccessToken(jwtVerifyKey []byte) *DefaultAccessToken

func (*DefaultAccessToken) Generate added in v0.4.2

func (d *DefaultAccessToken) Generate(ctx context.Context, issuer, clientID, scope, openID string, code *CodeValue) (token *TokenResponse, err error)

Generate 生成AccessToken

func (*DefaultAccessToken) Parse added in v0.4.2

func (d *DefaultAccessToken) Parse(ctx context.Context, accessToken string) (claims *JwtClaims, err error)

Parse 解析AccessToken

func (*DefaultAccessToken) Refresh added in v0.4.2

func (d *DefaultAccessToken) Refresh(ctx context.Context, clientID, refreshToken string) (token *TokenResponse, err error)

Refresh 刷新AccessToken

type DefaultLogger

type DefaultLogger struct{}

DefaultLogger ...

func (*DefaultLogger) Debugf

func (*DefaultLogger) Debugf(_ context.Context, format string, args ...interface{})

Debugf ...

func (*DefaultLogger) Debugln

func (*DefaultLogger) Debugln(_ context.Context, args ...interface{})

Debugln ...

func (*DefaultLogger) Errorf

func (*DefaultLogger) Errorf(_ context.Context, format string, args ...interface{})

Errorf ...

func (*DefaultLogger) Errorln

func (*DefaultLogger) Errorln(_ context.Context, args ...interface{})

Errorln ...

type DeviceAuthorizationResponse added in v0.2.0

type DeviceAuthorizationResponse struct {
	DeviceCode              string `json:"device_code"`
	UserCode                string `json:"user_code"`
	VerificationURI         string `json:"verification_uri"`
	VerificationURIComplete string `json:"verification_uri_complete,omitempty"`
	ExpiresIn               int64  `json:"expires_in"`
	Interval                int    `json:"interval"`
}

DeviceAuthorizationResponse Device Authorization Response. https://tools.ietf.org/html/rfc8628#section-3.2

type DeviceCodeValue added in v0.2.0

type DeviceCodeValue struct {
	OpenID string   `json:"open_id"`
	Scope  []string `json:"scope"`
}

DeviceCodeValue device_code值

func (*DeviceCodeValue) MarshalBinary added in v0.2.0

func (code *DeviceCodeValue) MarshalBinary() ([]byte, error)

MarshalBinary json

func (*DeviceCodeValue) UnmarshalBinary added in v0.2.0

func (code *DeviceCodeValue) UnmarshalBinary(data []byte) error

UnmarshalBinary json

type ErrorResponse

type ErrorResponse struct {
	Error string `json:"error"`
}

ErrorResponse error response.

type GenerateAccessTokenFunc added in v0.1.0

type GenerateAccessTokenFunc func(ctx context.Context, issuer, clientID, scope, openID string, code *CodeValue) (token *TokenResponse, err error)

GenerateAccessTokenFunc 生成AccessToken委托

func NewDefaultGenerateAccessToken added in v0.1.0

func NewDefaultGenerateAccessToken(jwtVerifyKey []byte) GenerateAccessTokenFunc

NewDefaultGenerateAccessToken 创建默认生成AccessToken方法

type GenerateCodeFunc

type GenerateCodeFunc func(ctx context.Context, clientID, openID, redirectURI string, scope []string) (code string, err error)

GenerateCodeFunc 生成Code委托

type GenerateDeviceAuthorizationFunc added in v0.2.0

type GenerateDeviceAuthorizationFunc func(ctx context.Context, issuer, verificationURI, clientID string, scope []string) (resp *DeviceAuthorizationResponse, err error)

GenerateDeviceAuthorizationFunc 生成设备授权

type IntrospectionResponse added in v0.2.0

type IntrospectionResponse struct {
	Active   bool   `json:"active"`
	ClientID string `json:"client_id,omitempty"`
	Username string `json:"username,omitempty"`
	Scope    string `json:"scope,omitempty"`
	Sub      string `json:"sub,omitempty"`
	Aud      string `json:"aud,omitempty"`
	Iss      int64  `json:"iss,omitempty"`
	Exp      int64  `json:"exp,omitempty"`
}

IntrospectionResponse Introspection Response. https://tools.ietf.org/html/rfc7662#section-2.2

type JwtClaims

type JwtClaims struct {
	JwtStandardClaims
	Scope string `json:"scope,omitempty"`
}

JwtClaims 在jwt标准上的扩展

func NewJwtClaims

func NewJwtClaims(issuer, audience, scope, openID string) *JwtClaims

NewJwtClaims ...

func ParseHS256JwtClaimsToken added in v0.2.1

func ParseHS256JwtClaimsToken(token string, jwtVerifyKey []byte) (claims *JwtClaims, err error)

ParseHS256JwtClaimsToken ...

func ParseJwtClaimsToken added in v0.2.1

func ParseJwtClaimsToken(token string, key interface{}) (claims *JwtClaims, err error)

ParseJwtClaimsToken ...

func (*JwtClaims) VerifyScope added in v0.2.0

func (c *JwtClaims) VerifyScope(scope string, req bool) bool

VerifyScope Compares the aud claim against cmp. If required is false, this method will return true if the value matches or is unset 如果required为false,如果值匹配或未设置,此方法将返回true

type JwtStandardClaims added in v0.2.0

type JwtStandardClaims struct {
	Audience  []string `json:"aud,omitempty"`
	ExpiresAt int64    `json:"exp,omitempty"`
	ID        string   `json:"jti,omitempty"`
	IssuedAt  int64    `json:"iat,omitempty"`
	Issuer    string   `json:"iss,omitempty"`
	NotBefore int64    `json:"nbf,omitempty"`
	Subject   string   `json:"sub,omitempty"`
}

JwtStandardClaims as referenced at https://tools.ietf.org/html/rfc7519#section-4.1

func ParseJwtStandardClaimsToken added in v0.2.1

func ParseJwtStandardClaimsToken(token string, key interface{}) (claims *JwtStandardClaims, err error)

ParseJwtStandardClaimsToken ...

func (JwtStandardClaims) Valid added in v0.2.0

func (c JwtStandardClaims) Valid() error

Valid time based claims "exp, iat, nbf". There is no accounting for clock skew. As well, if any of the above claims are not in the token, it will still be considered a valid claim.

func (*JwtStandardClaims) VerifyAudience added in v0.2.0

func (c *JwtStandardClaims) VerifyAudience(cmp []string, req bool) bool

VerifyAudience Compares the aud claim against cmp. If required is false, this method will return true if the value matches or is unset 如果required为false,如果值匹配或未设置,此方法将返回true

func (*JwtStandardClaims) VerifyExpiresAt added in v0.2.0

func (c *JwtStandardClaims) VerifyExpiresAt(cmp int64, req bool) bool

VerifyExpiresAt Compares the exp claim against cmp. If required is false, this method will return true if the value matches or is unset 如果required为false,如果值匹配或未设置,此方法将返回true

func (*JwtStandardClaims) VerifyIssuedAt added in v0.2.0

func (c *JwtStandardClaims) VerifyIssuedAt(cmp int64, req bool) bool

VerifyIssuedAt Compares the iat claim against cmp. If required is false, this method will return true if the value matches or is unset 如果required为false,如果值匹配或未设置,此方法将返回true

func (*JwtStandardClaims) VerifyIssuer added in v0.2.0

func (c *JwtStandardClaims) VerifyIssuer(cmp string, req bool) bool

VerifyIssuer Compares the iss claim against cmp. If required is false, this method will return true if the value matches or is unset 如果required为false,如果值匹配或未设置,此方法将返回true

func (*JwtStandardClaims) VerifyNotBefore added in v0.2.0

func (c *JwtStandardClaims) VerifyNotBefore(cmp int64, req bool) bool

VerifyNotBefore Compares the nbf claim against cmp. If required is false, this method will return true if the value matches or is unset 如果required为false,如果值匹配或未设置,此方法将返回true

type Logger

type Logger interface {
	// Debugf 测试
	Debugf(ctx context.Context, format string, args ...interface{})
	// Debugln 测试
	Debugln(ctx context.Context, args ...interface{})
	// Errorf 错误
	Errorf(ctx context.Context, format string, args ...interface{})
	// Errorln 错误
	Errorln(ctx context.Context, args ...interface{})
}

Logger logger

type ParseAccessTokenFunc added in v0.1.0

type ParseAccessTokenFunc func(ctx context.Context, accessToken string) (claims *JwtClaims, err error)

ParseAccessTokenFunc 解析AccessToken为JwtClaims委托

func NewDefaultParseAccessToken added in v0.1.0

func NewDefaultParseAccessToken(jwtVerifyKey []byte) ParseAccessTokenFunc

NewDefaultParseAccessToken 创建默认解析AccessToken方法

type RefreshAccessTokenFunc added in v0.1.0

type RefreshAccessTokenFunc func(ctx context.Context, clientID, refreshToken string) (token *TokenResponse, err error)

RefreshAccessTokenFunc 刷新AccessToken委托

func NewDefaultRefreshAccessToken added in v0.1.0

func NewDefaultRefreshAccessToken(jwtVerifyKey []byte) RefreshAccessTokenFunc

NewDefaultRefreshAccessToken 创建默认刷新AccessToken方法

type Server

type Server struct {
	VerifyClient                VerifyClientFunc
	VerifyClientID              VerifyClientIDFunc
	VerifyScope                 VerifyScopeFunc
	VerifyGrantType             VerifyGrantTypeFunc
	VerifyPassword              VerifyPasswordFunc
	VerifyRedirectURI           VerifyRedirectURIFunc
	GenerateCode                GenerateCodeFunc
	VerifyCode                  VerifyCodeFunc
	GenerateDeviceAuthorization GenerateDeviceAuthorizationFunc
	VerifyDeviceCode            VerifyDeviceCodeFunc
	VerifyIntrospectionToken    VerifyIntrospectionTokenFunc
	TokenRevocation             TokenRevocationFunc

	AccessToken AccessTokener
	// contains filtered or unexported fields
}

Server OAuth2Server

func NewServer

func NewServer(opts ...ServerOption) *Server

NewServer 创建服务器

func (*Server) HandleAuthorize

func (srv *Server) HandleAuthorize(w http.ResponseWriter, r *http.Request)

HandleAuthorize 处理Authorize

func (*Server) HandleDeviceAuthorization added in v0.2.0

func (srv *Server) HandleDeviceAuthorization(w http.ResponseWriter, r *http.Request)

HandleDeviceAuthorization 处理DeviceAuthorization https://tools.ietf.org/html/rfc8628#section-3.1

func (*Server) HandleToken

func (srv *Server) HandleToken(w http.ResponseWriter, r *http.Request)

HandleToken 处理Token

func (*Server) HandleTokenIntrospection added in v0.2.0

func (srv *Server) HandleTokenIntrospection(w http.ResponseWriter, r *http.Request)

HandleTokenIntrospection 处理内省端点 https://tools.ietf.org/html/rfc7662#section-2.1

func (*Server) HandleTokenRevocation added in v0.2.0

func (srv *Server) HandleTokenRevocation(w http.ResponseWriter, r *http.Request)

HandleTokenRevocation 处理Token销毁 https://tools.ietf.org/html/rfc7009

func (*Server) Init

func (srv *Server) Init(opts ...ServerOption)

Init 初始化

type ServerOption added in v0.2.0

type ServerOption func(*ServerOptions)

ServerOption 为可选参数赋值的函数

func ServerCustomGrantTypeAuthentication added in v0.3.3

func ServerCustomGrantTypeAuthentication(customGrantTypeAuthentication map[string]CustomGrantTypeAuthenticationFunc) ServerOption

ServerCustomGrantTypeAuthentication ...

func ServerCustomGrantTypeEnabled added in v0.3.3

func ServerCustomGrantTypeEnabled(customGrantTypeEnabled bool) ServerOption

ServerCustomGrantTypeEnabled ...

func ServerDeviceAuthorizationEndpointEnabled added in v0.2.0

func ServerDeviceAuthorizationEndpointEnabled(deviceAuthorizationEndpointEnabled bool) ServerOption

ServerDeviceAuthorizationEndpointEnabled ...

func ServerDeviceVerificationURI added in v0.2.0

func ServerDeviceVerificationURI(deviceVerificationURI string) ServerOption

ServerDeviceVerificationURI ...

func ServerIntrospectEndpointEnabled added in v0.2.0

func ServerIntrospectEndpointEnabled(introspectEndpointEnabled bool) ServerOption

ServerIntrospectEndpointEnabled ...

func ServerIssuer added in v0.2.0

func ServerIssuer(issuer string) ServerOption

ServerIssuer ...

func ServerLogger added in v0.2.0

func ServerLogger(log Logger) ServerOption

ServerLogger ...

func ServerTokenRevocationEnabled added in v0.2.0

func ServerTokenRevocationEnabled(tokenRevocationEnabled bool) ServerOption

ServerTokenRevocationEnabled ...

type ServerOptions added in v0.2.0

type ServerOptions struct {
	Log                                Logger
	Issuer                             string
	DeviceAuthorizationEndpointEnabled bool   // https://tools.ietf.org/html/rfc8628
	DeviceVerificationURI              string // https://tools.ietf.org/html/rfc8628#section-3.2
	IntrospectEndpointEnabled          bool   // https://tools.ietf.org/html/rfc7662
	TokenRevocationEnabled             bool   // https://tools.ietf.org/html/rfc7009
	CustomGrantTypeEnabled             bool   // 自定义身份验证
	CustomGrantTypeAuthentication      map[string]CustomGrantTypeAuthenticationFunc
}

ServerOptions server可选参数列表

type TokenResponse

type TokenResponse struct {
	AccessToken  string      `json:"access_token"`
	TokenType    string      `json:"token_type,omitempty"`
	ExpiresIn    int64       `json:"expires_in"`
	RefreshToken string      `json:"refresh_token,omitempty"`
	Data         interface{} `json:"data,omitempty"`
	Scope        string      `json:"scope,omitempty"`
	IDToken      string      `json:"id_token,omitempty"` // https://openid.net/specs/openid-connect-core-1_0.html#IDToken
}

TokenResponse token response.

type TokenRevocationFunc added in v0.2.0

type TokenRevocationFunc func(ctx context.Context, token, clientID string, tokenTypeHint ...string)

TokenRevocationFunc Token撤销委托 https://tools.ietf.org/html/rfc7009#section-2.2

type VerifyClientFunc

type VerifyClientFunc func(ctx context.Context, basic *ClientBasic) (err error)

VerifyClientFunc 验证客户端委托

type VerifyClientIDFunc added in v0.3.0

type VerifyClientIDFunc func(ctx context.Context, clientID string) (err error)

VerifyClientIDFunc 验证客户端ID委托

type VerifyCodeFunc

type VerifyCodeFunc func(ctx context.Context, code, clientID, redirectURI string) (value *CodeValue, err error)

VerifyCodeFunc 验证Code委托

type VerifyDeviceCodeFunc added in v0.2.0

type VerifyDeviceCodeFunc func(ctx context.Context, deviceCode, clientID string) (value *DeviceCodeValue, err error)

VerifyDeviceCodeFunc 验证DeviceCode委托

type VerifyGrantTypeFunc added in v0.4.0

type VerifyGrantTypeFunc func(ctx context.Context, clientID, grantType string) (err error)

VerifyGrantTypeFunc 验证授权类型委托

type VerifyIntrospectionTokenFunc added in v0.2.0

type VerifyIntrospectionTokenFunc func(ctx context.Context, token, clientID string, tokenTypeHint ...string) (resp *IntrospectionResponse, err error)

VerifyIntrospectionTokenFunc 验证IntrospectionToken委托

type VerifyPasswordFunc

type VerifyPasswordFunc func(ctx context.Context, username, password string) (openID string, err error)

VerifyPasswordFunc 验证账号密码委托

type VerifyRedirectURIFunc added in v0.0.3

type VerifyRedirectURIFunc func(ctx context.Context, clientID, redirectURI string) (err error)

VerifyRedirectURIFunc 验证RedirectURI委托

type VerifyScopeFunc added in v0.0.3

type VerifyScopeFunc func(ctx context.Context, scope []string, clientID string) (err error)

VerifyScopeFunc 验证范围委托

Directories

Path Synopsis
examples module

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL