From 0a49c2d0029b6fcdbdf20ce0cfdbcf1276753db9 Mon Sep 17 00:00:00 2001 From: lyric Date: Thu, 18 Aug 2016 10:29:26 +0800 Subject: [PATCH] optimization of error handling --- LICENSE | 36 +++++++++--------- README.md | 35 +++++++++++++----- errors/response.go | 16 ++++++-- example/server/server.go | 2 +- manage/manage_test.go | 1 - server/server.go | 80 ++++++++++++++++++++-------------------- 6 files changed, 97 insertions(+), 73 deletions(-) diff --git a/LICENSE b/LICENSE index e926b8f..a3f5cc0 100644 --- a/LICENSE +++ b/LICENSE @@ -1,23 +1,21 @@ -Copyright (c) 2016, OAuth 2.0 -All rights reserved. +MIT License -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: +Copyright (c) 2016 Lyric -* Redistributions of source code must retain the above copyright notice, this - list of conditions and the following disclaimer. +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: -* Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md index f30208b..7bb2731 100644 --- a/README.md +++ b/README.md @@ -2,9 +2,11 @@ > An open protocol to allow secure authorization in a simple and standard method from web, mobile and desktop applications. -[![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) -[![Build Status](https://travis-ci.org/go-oauth2/oauth2.svg?branch=master)](https://travis-ci.org/go-oauth2/oauth2) +[![License][License-Image]][License-Url] +[![ReportCard][ReportCard-Image]][ReportCard-Url] +[![Build][Build-Status-Image]][Build-Status-Url] +[![GoDoc][GoDoc-Image]][GoDoc-Url] +[![Release][Release-Image]][Release-Url] ## Protocol Flow @@ -42,6 +44,7 @@ $ go get -u gopkg.in/oauth2.v3/... package main import ( + "fmt" "net/http" "gopkg.in/oauth2.v3/manage" @@ -59,6 +62,10 @@ func main() { srv := server.NewDefaultServer(manager) srv.SetAllowGetAccessRequest(true) + srv.SetInternalErrorHandler(func(err error) { + fmt.Println("OAuth2 Error:",err.Error()) + }) + http.HandleFunc("/authorize", func(w http.ResponseWriter, r *http.Request) { err := srv.HandleAuthorizeRequest(w, r) if err != nil { @@ -69,7 +76,7 @@ func main() { 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) + http.Error(w, err.Error(), http.StatusInternalServerError) } }) @@ -114,15 +121,25 @@ http://localhost:9096/token?grant_type=clientcredentials&client_id=1&client_secr Simulation examples of authorization code model, please check [example](/example) -## Storage implements +## Storage Implements * [BuntDB](https://github.com/tidwall/buntdb)(The default storage) * [Redis](https://github.com/go-oauth2/redis) * [MongoDB](https://github.com/go-oauth2/mongo) -## License +## MIT License ``` -Copyright (c) 2016, OAuth 2.0 -All rights reserved. -``` \ No newline at end of file +Copyright (c) 2016 Lyric +``` + +[License-Url]: http://opensource.org/licenses/MIT +[License-Image]: https://img.shields.io/npm/l/express.svg +[Build-Status-Url]: https://travis-ci.org/go-oauth2/oauth2 +[Build-Status-Image]: https://travis-ci.org/go-oauth2/oauth2.svg?branch=master +[Release-Url]: https://github.com/go-oauth2/oauth2/releases/tag/v3.4.8 +[Release-image]: http://img.shields.io/badge/release-v3.4.8-1eb0fc.svg +[ReportCard-Url]: https://goreportcard.com/report/gopkg.in/oauth2.v3 +[ReportCard-Image]: https://goreportcard.com/badge/gopkg.in/oauth2.v3 +[GoDoc-Url]: https://godoc.org/gopkg.in/oauth2.v3 +[GoDoc-Image]: https://godoc.org/gopkg.in/oauth2.v3?status.svg \ No newline at end of file diff --git a/errors/response.go b/errors/response.go index 6d2a3d8..bcac422 100644 --- a/errors/response.go +++ b/errors/response.go @@ -4,10 +4,11 @@ import "errors" // Response error response type Response struct { - Error error `json:"error"` - Description string `json:"error_description,omitempty"` - URI string `json:"error_uri,omitempty"` - StatusCode int `json:"-"` + Error error + ErrorCode int + Description string + URI string + StatusCode int } // https://tools.ietf.org/html/rfc6749#section-5.2 @@ -37,3 +38,10 @@ var Descriptions = map[error]string{ ErrInvalidGrant: "The provided authorization grant (e.g., authorization code, resource owner credentials) or refresh token is invalid, expired, revoked, does not match the redirection URI used in the authorization request, or was issued to another client", ErrUnsupportedGrantType: "The authorization grant type is not supported by the authorization server", } + +// StatusCodes response error HTTP status code +var StatusCodes = map[error]int{ + ErrInvalidClient: 401, + ErrServerError: 500, + ErrTemporarilyUnavailable: 503, +} diff --git a/example/server/server.go b/example/server/server.go index 53df1ab..50c3964 100644 --- a/example/server/server.go +++ b/example/server/server.go @@ -54,7 +54,7 @@ func main() { 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) + http.Error(w, err.Error(), http.StatusInternalServerError) } }) diff --git a/manage/manage_test.go b/manage/manage_test.go index 85a14f4..36e66e0 100644 --- a/manage/manage_test.go +++ b/manage/manage_test.go @@ -42,7 +42,6 @@ func testManager(manager oauth2.Manager) { } cti, err := manager.GenerateAuthToken(oauth2.Code, reqParams) So(err, ShouldBeNil) - Println(cti.GetCode()) code := cti.GetCode() So(code, ShouldNotBeEmpty) diff --git a/server/server.go b/server/server.go index 7eb68d6..4a3c869 100644 --- a/server/server.go +++ b/server/server.go @@ -55,21 +55,19 @@ type Server struct { AuthorizeScopeHandler AuthorizeScopeHandler } -// response redirect error -func (s *Server) resRedirectError(w http.ResponseWriter, req *AuthorizeRequest, err error) (uerr error) { +func (s *Server) redirectError(w http.ResponseWriter, req *AuthorizeRequest, err error) (uerr error) { if req == nil { uerr = err return } data, _ := s.GetErrorData(err) - err = s.resRedirect(w, req, data) + err = s.redirect(w, req, data) return } -func (s *Server) resRedirect(w http.ResponseWriter, req *AuthorizeRequest, data map[string]interface{}) (err error) { - uri, verr := s.GetRedirectURI(req, data) - if verr != nil { - err = verr +func (s *Server) redirect(w http.ResponseWriter, req *AuthorizeRequest, data map[string]interface{}) (err error) { + uri, err := s.GetRedirectURI(req, data) + if err != nil { return } w.Header().Set("Location", uri) @@ -77,15 +75,13 @@ func (s *Server) resRedirect(w http.ResponseWriter, req *AuthorizeRequest, data return } -// response token error -func (s *Server) resTokenError(w http.ResponseWriter, err error) (uerr error) { +func (s *Server) tokenError(w http.ResponseWriter, err error) (uerr error) { data, statusCode := s.GetErrorData(err) - uerr = s.resToken(w, data, statusCode) + uerr = s.token(w, data, statusCode) return } -// response token -func (s *Server) resToken(w http.ResponseWriter, data map[string]interface{}, statusCode ...int) (err error) { +func (s *Server) token(w http.ResponseWriter, data map[string]interface{}, statusCode ...int) (err error) { w.Header().Set("Content-Type", "application/json;charset=UTF-8") w.Header().Set("Cache-Control", "no-store") w.Header().Set("Pragma", "no-cache") @@ -157,18 +153,19 @@ func (s *Server) CheckResponseType(rt oauth2.ResponseType) bool { // GetAuthorizeToken get authorization token(code) func (s *Server) GetAuthorizeToken(req *AuthorizeRequest) (ti oauth2.TokenInfo, err error) { - if req.RedirectURI == "" || + if req.ResponseType == "" { + err = errors.ErrUnsupportedResponseType + return + } else if req.RedirectURI == "" || req.ClientID == "" { err = errors.ErrInvalidRequest return - } else if req.ResponseType == "" { - err = errors.ErrUnsupportedResponseType - return } if allowed := s.CheckResponseType(req.ResponseType); !allowed { err = errors.ErrUnauthorizedClient return } + // check the client allows the grant type if fn := s.ClientAuthorizedHandler; fn != nil { gt := oauth2.AuthorizationCode if req.ResponseType == oauth2.Token { @@ -183,6 +180,7 @@ func (s *Server) GetAuthorizeToken(req *AuthorizeRequest) (ti oauth2.TokenInfo, return } } + // check the client allows the authorized scope if fn := s.ClientScopeHandler; fn != nil { allowed, verr := fn(req.ClientID, req.Scope) if verr != nil { @@ -194,13 +192,11 @@ func (s *Server) GetAuthorizeToken(req *AuthorizeRequest) (ti oauth2.TokenInfo, } } tgr := &oauth2.TokenGenerateRequest{ - ClientID: req.ClientID, - UserID: req.UserID, - RedirectURI: req.RedirectURI, - Scope: req.Scope, - } - if exp := req.AccessTokenExp; exp > 0 { - tgr.AccessTokenExp = exp + ClientID: req.ClientID, + UserID: req.UserID, + RedirectURI: req.RedirectURI, + Scope: req.Scope, + AccessTokenExp: req.AccessTokenExp, } ti, err = s.Manager.GenerateAuthToken(req.ResponseType, tgr) return @@ -222,13 +218,13 @@ func (s *Server) GetAuthorizeData(rt oauth2.ResponseType, ti oauth2.TokenInfo) ( func (s *Server) HandleAuthorizeRequest(w http.ResponseWriter, r *http.Request) (err error) { req, verr := s.ValidationAuthorizeRequest(r) if verr != nil { - err = s.resRedirectError(w, req, verr) + err = s.redirectError(w, req, verr) return } // user authorization userID, verr := s.UserAuthorizationHandler(w, r) if verr != nil { - err = s.resRedirectError(w, req, verr) + err = s.redirectError(w, req, verr) return } else if userID == "" { return @@ -250,16 +246,15 @@ func (s *Server) HandleAuthorizeRequest(w http.ResponseWriter, r *http.Request) if verr != nil { err = verr return - } else if exp > 0 { - req.AccessTokenExp = exp } + req.AccessTokenExp = exp } ti, verr := s.GetAuthorizeToken(req) if verr != nil { - err = s.resRedirectError(w, req, verr) + err = s.redirectError(w, req, verr) return } - err = s.resRedirect(w, req, s.GetAuthorizeData(req.ResponseType, ti)) + err = s.redirect(w, req, s.GetAuthorizeData(req.ResponseType, ti)) return } @@ -433,15 +428,15 @@ func (s *Server) GetTokenData(ti oauth2.TokenInfo) (data map[string]interface{}) func (s *Server) HandleTokenRequest(w http.ResponseWriter, r *http.Request) (err error) { gt, tgr, verr := s.ValidationTokenRequest(r) if verr != nil { - err = s.resTokenError(w, verr) + err = s.tokenError(w, verr) return } ti, verr := s.GetAccessToken(gt, tgr) if verr != nil { - err = s.resTokenError(w, verr) + err = s.tokenError(w, verr) return } - err = s.resToken(w, s.GetTokenData(ti)) + err = s.token(w, s.GetTokenData(ti)) return } @@ -453,24 +448,31 @@ func (s *Server) GetErrorData(err error) (data map[string]interface{}, statusCod } err = errors.ErrServerError } - var re *errors.Response + re := &errors.Response{ + Error: err, + Description: errors.Descriptions[err], + StatusCode: errors.StatusCodes[err], + } if fn := s.ResponseErrorHandler; fn != nil { - re = fn(err) - } else { - re = &errors.Response{ - Error: err, - Description: errors.Descriptions[err], + if vre := fn(err); vre != nil { + re = vre } } data = map[string]interface{}{ "error": re.Error.Error(), } + if v := re.ErrorCode; v != 0 { + data["error_code"] = v + } if v := re.Description; v != "" { data["error_description"] = v } if v := re.URI; v != "" { data["error_uri"] = v } - statusCode = re.StatusCode + statusCode = 400 + if v := re.StatusCode; v > 0 { + statusCode = v + } return }