Skip to content

Commit e3ba437

Browse files
committed
Improve code comments
1 parent d7d1679 commit e3ba437

File tree

10 files changed

+179
-145
lines changed

10 files changed

+179
-145
lines changed

README.md

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -84,9 +84,9 @@ func main() {
8484
err = oauth2.ErrInvalidClient
8585
return
8686
}
87-
basic = &oauth2.ClientBasic{
88-
ID: basic.ID,
89-
Secret: pwd,
87+
if basic.Secret != pwd {
88+
err = oauth2.ErrInvalidClient
89+
return
9090
}
9191
return
9292
}
@@ -156,7 +156,9 @@ func main() {
156156
return
157157
}
158158

159-
srv.Init()
159+
if err := srv.InitWithError(); err != nil {
160+
panic(err)
161+
}
160162

161163
// =============Http Default=============
162164
// http.HandleFunc("/authorize", srv.HandleAuthorize)

client.go

Lines changed: 45 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -4,27 +4,29 @@ import (
44
"context"
55
"encoding/json"
66
"io"
7-
"io/ioutil"
87
"net/http"
98
"net/url"
109
"strings"
1110
)
1211

13-
// Client oauth2 client
12+
// Client OAuth2客户端 / OAuth2 client for making authorization requests
1413
type Client struct {
15-
Log Logger
16-
httpClient *http.Client
17-
ServerBaseURL string
18-
AuthorizationEndpoint string
19-
TokenEndpoint string
20-
IntrospectEndpoint string
21-
DeviceAuthorizationEndpoint string
22-
TokenRevocationEndpoint string
23-
ID string
24-
Secret string
14+
Log Logger // 日志记录器 / Logger instance
15+
httpClient *http.Client // HTTP客户端 / HTTP client for requests
16+
ServerBaseURL string // 服务器基础URL / OAuth2 server base URL
17+
AuthorizationEndpoint string // 授权端点 / Authorization endpoint path
18+
TokenEndpoint string // 令牌端点 / Token endpoint path
19+
IntrospectEndpoint string // 内省端点 / Introspection endpoint path
20+
DeviceAuthorizationEndpoint string // 设备授权端点 / Device authorization endpoint path
21+
TokenRevocationEndpoint string // 令牌撤销端点 / Token revocation endpoint path
22+
ID string // 客户端ID / Client identifier
23+
Secret string // 客户端密钥 / Client secret
2524
}
2625

27-
// NewClient new oauth2 client
26+
// NewClient 创建OAuth2客户端 / Create a new OAuth2 client
27+
// serverBaseURL: 服务器基础URL / OAuth2 server base URL
28+
// id: 客户端ID / Client identifier
29+
// secret: 客户端密钥 / Client secret
2830
func NewClient(serverBaseURL, id, secret string) *Client {
2931
httpclient := &http.Client{}
3032
httpclient.CheckRedirect = func(req *http.Request, via []*http.Request) error {
@@ -73,13 +75,18 @@ func (c *Client) authorize(ctx context.Context, w http.ResponseWriter, responseT
7375
return
7476
}
7577

76-
// AuthorizeAuthorizationCode ...
78+
// AuthorizeAuthorizationCode 授权码模式授权请求 / Authorization code grant authorization request
79+
// redirectURI: 重定向URI / Redirect URI after authorization
80+
// scope: 授权范围 / Requested scope
81+
// state: 状态码,用于防止CSRF攻击 / State parameter for CSRF protection
7782
func (c *Client) AuthorizeAuthorizationCode(ctx context.Context, w http.ResponseWriter, redirectURI, scope, state string) (err error) {
7883
return c.authorize(ctx, w, CodeKey, redirectURI, scope, state)
7984
}
8085

81-
// TokenAuthorizationCode ...
82-
// TokenAuthorizationCode(code, redirectURI, state string)
86+
// TokenAuthorizationCode 授权码模式获取令牌 / Exchange authorization code for access token
87+
// code: 授权码 / Authorization code received from authorization server
88+
// redirectURI: 重定向URI / Redirect URI used in authorization request
89+
// clientID: 客户端ID / Client identifier
8390
func (c *Client) TokenAuthorizationCode(ctx context.Context, code, redirectURI, clientID string) (token *TokenResponse, err error) {
8491
values := url.Values{
8592
CodeKey: []string{code},
@@ -89,12 +96,16 @@ func (c *Client) TokenAuthorizationCode(ctx context.Context, code, redirectURI,
8996
return c.token(ctx, AuthorizationCodeKey, values)
9097
}
9198

92-
// AuthorizeImplicit ...
99+
// AuthorizeImplicit 隐式授权模式授权请求 / Implicit grant authorization request
100+
// redirectURI: 重定向URI / Redirect URI after authorization
101+
// scope: 授权范围 / Requested scope
102+
// state: 状态码,用于防止CSRF攻击 / State parameter for CSRF protection
93103
func (c *Client) AuthorizeImplicit(ctx context.Context, w http.ResponseWriter, redirectURI, scope, state string) (err error) {
94104
return c.authorize(ctx, w, TokenKey, redirectURI, scope, state)
95105
}
96106

97-
// DeviceAuthorization ...
107+
// DeviceAuthorization 设备授权请求 / Device authorization request (RFC 8628)
108+
// scope: 授权范围 / Requested scope
98109
func (c *Client) DeviceAuthorization(ctx context.Context, w http.ResponseWriter, scope string) (err error) {
99110
var uri *url.URL
100111
uri, err = url.Parse(c.ServerBaseURL + c.DeviceAuthorizationEndpoint)
@@ -175,7 +186,9 @@ func (c *Client) token(ctx context.Context, grantType string, values url.Values)
175186
return
176187
}
177188

178-
// TokenResourceOwnerPasswordCredentials ...
189+
// TokenResourceOwnerPasswordCredentials 密码模式获取令牌 / Resource owner password credentials grant
190+
// username: 用户名 / Resource owner username
191+
// password: 密码 / Resource owner password
179192
func (c *Client) TokenResourceOwnerPasswordCredentials(ctx context.Context, username, password string) (model *TokenResponse, err error) {
180193
values := url.Values{
181194
UsernameKey: []string{username},
@@ -184,7 +197,8 @@ func (c *Client) TokenResourceOwnerPasswordCredentials(ctx context.Context, user
184197
return c.token(ctx, PasswordKey, values)
185198
}
186199

187-
// TokenClientCredentials ...
200+
// TokenClientCredentials 客户端凭证模式获取令牌 / Client credentials grant
201+
// scope: 授权范围(可选) / Requested scope (optional)
188202
func (c *Client) TokenClientCredentials(ctx context.Context, scope ...string) (model *TokenResponse, err error) {
189203
values := url.Values{}
190204
if len(scope) > 0 {
@@ -193,15 +207,17 @@ func (c *Client) TokenClientCredentials(ctx context.Context, scope ...string) (m
193207
return c.token(ctx, ClientCredentialsKey, values)
194208
}
195209

196-
// RefreshToken ...
210+
// RefreshToken 刷新访问令牌 / Refresh access token using refresh token
211+
// refreshToken: 刷新令牌 / Refresh token
197212
func (c *Client) RefreshToken(ctx context.Context, refreshToken string) (model *TokenResponse, err error) {
198213
values := url.Values{
199214
RefreshTokenKey: []string{refreshToken},
200215
}
201216
return c.token(ctx, RefreshTokenKey, values)
202217
}
203218

204-
// TokenDeviceCode ...
219+
// TokenDeviceCode 设备码模式获取令牌 / Exchange device code for access token (RFC 8628)
220+
// deviceCode: 设备码 / Device code received from device authorization
205221
func (c *Client) TokenDeviceCode(ctx context.Context, deviceCode string) (model *TokenResponse, err error) {
206222
values := url.Values{
207223
ClientIDKey: []string{c.ID},
@@ -210,7 +226,9 @@ func (c *Client) TokenDeviceCode(ctx context.Context, deviceCode string) (model
210226
return c.token(ctx, DeviceCodeKey, values)
211227
}
212228

213-
// TokenIntrospect ...
229+
// TokenIntrospect 令牌内省 / Token introspection (RFC 7662)
230+
// token: 要检查的令牌 / Token to introspect
231+
// tokenTypeHint: 令牌类型提示(可选) / Token type hint (optional): access_token or refresh_token
214232
func (c *Client) TokenIntrospect(ctx context.Context, token string, tokenTypeHint ...string) (introspection *IntrospectionResponse, err error) {
215233
values := url.Values{
216234
TokenKey: []string{token},
@@ -227,7 +245,9 @@ func (c *Client) TokenIntrospect(ctx context.Context, token string, tokenTypeHin
227245
return
228246
}
229247

230-
// TokenRevocation token撤销
248+
// TokenRevocation 令牌撤销 / Token revocation (RFC 7009)
249+
// token: 要撤销的令牌 / Token to revoke
250+
// tokenTypeHint: 令牌类型提示(可选) / Token type hint (optional): access_token or refresh_token
231251
func (c *Client) TokenRevocation(ctx context.Context, token string, tokenTypeHint ...string) (introspection *IntrospectionResponse, err error) {
232252
values := url.Values{
233253
TokenKey: []string{token},
@@ -263,7 +283,7 @@ func (c *Client) do(ctx context.Context, path string, values url.Values, v inter
263283
}
264284
defer resp.Body.Close()
265285
var body []byte
266-
body, err = ioutil.ReadAll(resp.Body)
286+
body, err = io.ReadAll(resp.Body)
267287
if err != nil {
268288
return
269289
}

constant.go

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,15 +3,16 @@ package oauth2
33
import "time"
44

55
const (
6+
// contentTypeJSON JSON内容类型 / JSON content type for HTTP responses
67
contentTypeJSON = "application/json"
7-
// AccessTokenExpire ...
8+
// AccessTokenExpire 访问令牌过期时间(1小时) / Access token expiration time (1 hour)
89
AccessTokenExpire = time.Second * 3600
9-
// RefreshTokenExpire ...
10+
// RefreshTokenExpire 刷新令牌过期时间(30分钟) / Refresh token expiration time (30 minutes)
1011
RefreshTokenExpire = AccessTokenExpire / 2
11-
// TokenTypeBearer ...
12+
// TokenTypeBearer Bearer令牌类型 / Bearer token type
1213
TokenTypeBearer = "Bearer"
13-
// ScopeRefreshToken ...
14+
// ScopeRefreshToken 刷新令牌的scope / Scope for refresh token
1415
ScopeRefreshToken = "refresh_token"
15-
// DefaultJwtIssuer ...
16+
// DefaultJwtIssuer 默认JWT颁发者 / Default JWT issuer
1617
DefaultJwtIssuer = "github.com/nilorg/oauth2"
1718
)

context.go

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,14 +5,15 @@ import (
55
"errors"
66
)
77

8+
// openIDKey OpenID上下文键类型 / Context key type for OpenID
89
type openIDKey struct{}
910

1011
var (
11-
// ErrContextNotFoundOpenID 上下文不存在OpenID
12-
ErrContextNotFoundOpenID = errors.New("OAuth2上下文不存在OpenID")
12+
// ErrContextNotFoundOpenID 上下文不存在OpenID / OpenID not found in context
13+
ErrContextNotFoundOpenID = errors.New("openid not found in context")
1314
)
1415

15-
// OpenIDFromContext ...
16+
// OpenIDFromContext 从上下文中获取OpenID / Get OpenID from context
1617
func OpenIDFromContext(ctx context.Context) (string, error) {
1718
openID, ok := ctx.Value(openIDKey{}).(string)
1819
if !ok {
@@ -21,7 +22,7 @@ func OpenIDFromContext(ctx context.Context) (string, error) {
2122
return openID, nil
2223
}
2324

24-
// NewOpenIDContext 创建OpenID上下文
25+
// NewOpenIDContext 创建包含OpenID的上下文 / Create context with OpenID
2526
func NewOpenIDContext(ctx context.Context, openID string) context.Context {
2627
return context.WithValue(ctx, openIDKey{}, openID)
2728
}

errors.go

Lines changed: 20 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -40,50 +40,50 @@ var (
4040
)
4141

4242
var (
43-
// ErrVerifyClientFuncNil ...
43+
// ErrVerifyClientFuncNil VerifyClient函数未设置 / VerifyClient function is not set
4444
ErrVerifyClientFuncNil = errors.New("OAuth2 Server VerifyClient Is Nil")
45-
// ErrVerifyClientIDFuncNil ...
45+
// ErrVerifyClientIDFuncNil VerifyClientID函数未设置 / VerifyClientID function is not set
4646
ErrVerifyClientIDFuncNil = errors.New("OAuth2 Server VerifyClientID Is Nil")
47-
// ErrVerifyPasswordFuncNil ...
47+
// ErrVerifyPasswordFuncNil VerifyPassword函数未设置 / VerifyPassword function is not set
4848
ErrVerifyPasswordFuncNil = errors.New("OAuth2 Server VerifyPassword Is Nil")
49-
// ErrVerifyRedirectURIFuncNil ...
49+
// ErrVerifyRedirectURIFuncNil VerifyRedirectURI函数未设置 / VerifyRedirectURI function is not set
5050
ErrVerifyRedirectURIFuncNil = errors.New("OAuth2 Server VerifyRedirectURI Is Nil")
51-
// ErrGenerateCodeFuncNil ...
51+
// ErrGenerateCodeFuncNil GenerateCode函数未设置 / GenerateCode function is not set
5252
ErrGenerateCodeFuncNil = errors.New("OAuth2 Server GenerateCode Is Nil")
53-
// ErrVerifyCodeFuncNil ...
53+
// ErrVerifyCodeFuncNil VerifyCode函数未设置 / VerifyCode function is not set
5454
ErrVerifyCodeFuncNil = errors.New("OAuth2 Server VerifyCode Is Nil")
55-
// ErrVerifyScopeFuncNil ...
55+
// ErrVerifyScopeFuncNil VerifyScope函数未设置 / VerifyScope function is not set
5656
ErrVerifyScopeFuncNil = errors.New("OAuth2 Server VerifyScope Is Nil")
57-
// ErrGenerateAccessTokenFuncNil ...
57+
// ErrGenerateAccessTokenFuncNil GenerateAccessToken函数未设置 / GenerateAccessToken function is not set
5858
ErrGenerateAccessTokenFuncNil = errors.New("OAuth2 Server GenerateAccessTokenFunc Is Nil")
59-
// ErrGenerateDeviceAuthorizationFuncNil ...
59+
// ErrGenerateDeviceAuthorizationFuncNil GenerateDeviceAuthorization函数未设置 / GenerateDeviceAuthorization function is not set
6060
ErrGenerateDeviceAuthorizationFuncNil = errors.New("OAuth2 Server GenerateDeviceAuthorizationFunc Is Nil")
61-
// ErrVerifyDeviceCodeFuncNil ...
61+
// ErrVerifyDeviceCodeFuncNil VerifyDeviceCode函数未设置 / VerifyDeviceCode function is not set
6262
ErrVerifyDeviceCodeFuncNil = errors.New("OAuth2 Server ErrVerifyDeviceCodeFunc Is Nil")
63-
// ErrRefreshAccessTokenFuncNil ...
63+
// ErrRefreshAccessTokenFuncNil RefreshAccessToken函数未设置 / RefreshAccessToken function is not set
6464
ErrRefreshAccessTokenFuncNil = errors.New("OAuth2 Server ErrRefreshAccessTokenFuncNil Is Nil")
65-
// ErrParseAccessTokenFuncNil ...
65+
// ErrParseAccessTokenFuncNil ParseAccessToken函数未设置 / ParseAccessToken function is not set
6666
ErrParseAccessTokenFuncNil = errors.New("OAuth2 Server ParseAccessTokenFunc Is Nil")
67-
// ErrVerifyIntrospectionTokenFuncNil ...
67+
// ErrVerifyIntrospectionTokenFuncNil VerifyIntrospectionToken函数未设置 / VerifyIntrospectionToken function is not set
6868
ErrVerifyIntrospectionTokenFuncNil = errors.New("OAuth2 Server VerifyIntrospectionToken Is Nil")
69-
// ErrTokenRevocationFuncNil ...
69+
// ErrTokenRevocationFuncNil TokenRevocation函数未设置 / TokenRevocation function is not set
7070
ErrTokenRevocationFuncNil = errors.New("OAuth2 Server TokenRevocation Is Nil")
71-
// ErrVerifyGrantTypeFuncNil ...
71+
// ErrVerifyGrantTypeFuncNil VerifyGrantType函数未设置 / VerifyGrantType function is not set
7272
ErrVerifyGrantTypeFuncNil = errors.New("OAuth2 Server VerifyGrantType Is Nil")
7373
// ErrInvalidAccessToken 无效的访问令牌
7474
ErrInvalidAccessToken = errors.New("invalid_access_token")
7575
// ErrInvalidRedirectURI 无效的RedirectURI
7676
ErrInvalidRedirectURI = errors.New("invalid_redirect_uri")
77-
// ErrStateValueDidNotMatch ...
77+
// ErrStateValueDidNotMatch state值不匹配 / State value did not match
7878
ErrStateValueDidNotMatch = errors.New("state value did not match")
79-
// ErrMissingAccessToken ...
79+
// ErrMissingAccessToken 缺少访问令牌 / Missing access token in request
8080
ErrMissingAccessToken = errors.New("missing access token")
81-
// ErrAccessToken ...
81+
// ErrAccessToken AccessToken接口未设置 / AccessToken interface is not set
8282
ErrAccessToken = errors.New("OAuth2 Server AccessToken Is Nil")
8383
)
8484

8585
var (
86-
// Errors ...
86+
// Errors 错误映射表,用于从错误字符串查找错误对象 / Error map for looking up error objects from error strings
8787
Errors = map[string]error{
8888
ErrVerifyClientFuncNil.Error(): ErrVerifyClientFuncNil,
8989
ErrInvalidAccessToken.Error(): ErrInvalidAccessToken,
@@ -105,7 +105,7 @@ var (
105105
ErrSlowDown.Error(): ErrSlowDown,
106106
ErrUnsupportedTokenType.Error(): ErrUnsupportedTokenType,
107107
}
108-
// ErrStatusCodes ...
108+
// ErrStatusCodes 错误对应的HTTP状态码映射表 / HTTP status codes mapping for errors
109109
ErrStatusCodes = map[error]int{
110110
ErrInvalidRequest: http.StatusBadRequest, // 400
111111
ErrUnauthorizedClient: http.StatusUnauthorized, // 401

examples/server/main.go

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -95,7 +95,9 @@ func main() {
9595
return
9696
}
9797

98-
srv.Init()
98+
if err := srv.InitWithError(); err != nil {
99+
panic(err)
100+
}
99101

100102
// =============Http Default=============
101103
// http.HandleFunc("/authorize", srv.HandleAuthorize)

keys.go

Lines changed: 21 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,46 +1,46 @@
11
package oauth2
22

33
const (
4-
// ResponseTypeKey ...
4+
// ResponseTypeKey 响应类型 / Response type parameter key
55
ResponseTypeKey = "response_type"
6-
// ClientIDKey ...
6+
// ClientIDKey 客户端ID / Client identifier parameter key
77
ClientIDKey = "client_id"
8-
// ClientSecretKey ...
8+
// ClientSecretKey 客户端密钥 / Client secret parameter key
99
ClientSecretKey = "client_secret"
10-
// RedirectURIKey ...
10+
// RedirectURIKey 重定向URI / Redirect URI parameter key
1111
RedirectURIKey = "redirect_uri"
12-
// ScopeKey ...
12+
// ScopeKey 授权范围 / Scope parameter key
1313
ScopeKey = "scope"
14-
// StateKey ...
14+
// StateKey 状态码,用于防止CSRF攻击 / State parameter key for CSRF protection
1515
StateKey = "state"
16-
// GrantTypeKey ...
16+
// GrantTypeKey 授权类型 / Grant type parameter key
1717
GrantTypeKey = "grant_type"
18-
// CodeKey ...
18+
// CodeKey 授权码 / Authorization code parameter key
1919
CodeKey = "code"
20-
// TokenKey ...
20+
// TokenKey 令牌 / Token parameter key
2121
TokenKey = "token"
22-
// ErrorKey ...
22+
// ErrorKey 错误信息 / Error parameter key
2323
ErrorKey = "error"
24-
// AccessTokenKey ...
24+
// AccessTokenKey 访问令牌 / Access token parameter key
2525
AccessTokenKey = "access_token"
26-
// TokenTypeKey ...
26+
// TokenTypeKey 令牌类型 / Token type parameter key
2727
TokenTypeKey = "token_type"
28-
// ClientCredentialsKey ...
28+
// ClientCredentialsKey 客户端凭证模式 / Client credentials grant type
2929
ClientCredentialsKey = "client_credentials"
30-
// PasswordKey ...
30+
// PasswordKey 密码模式 / Resource owner password credentials grant type
3131
PasswordKey = "password"
32-
// UsernameKey ...
32+
// UsernameKey 用户名 / Username parameter key
3333
UsernameKey = "username"
34-
// RefreshTokenKey ...
34+
// RefreshTokenKey 刷新令牌 / Refresh token parameter key
3535
RefreshTokenKey = "refresh_token"
36-
// AuthorizationCodeKey ...
36+
// AuthorizationCodeKey 授权码模式 / Authorization code grant type
3737
AuthorizationCodeKey = "authorization_code"
38-
// DeviceCodeKey ...
38+
// DeviceCodeKey 设备码模式 / Device code grant type
3939
DeviceCodeKey = "device_code"
40-
// UrnIetfParamsOAuthGrantTypeDeviceCodeKey ...
40+
// UrnIetfParamsOAuthGrantTypeDeviceCodeKey 设备码模式URN格式 / Device code grant type in URN format (RFC 8628)
4141
UrnIetfParamsOAuthGrantTypeDeviceCodeKey = "urn:ietf:params:oauth:grant-type:device_code"
42-
// TokenTypeHintKey ...
42+
// TokenTypeHintKey 令牌类型提示 / Token type hint parameter key
4343
TokenTypeHintKey = "token_type_hint"
44-
// ImplicitKey ...
44+
// ImplicitKey 隐式授权模式 / Implicit grant type
4545
ImplicitKey = "implicit"
4646
)

0 commit comments

Comments
 (0)