本文整理汇总了Golang中github.com/coreos/go-oidc/oauth2.NewError函数的典型用法代码示例。如果您正苦于以下问题:Golang NewError函数的具体用法?Golang NewError怎么用?Golang NewError使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NewError函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。
示例1: ClientCredsToken
func (s *Server) ClientCredsToken(creds oidc.ClientCredentials) (*jose.JWT, error) {
ok, err := s.ClientIdentityRepo.Authenticate(creds)
if err != nil {
log.Errorf("Failed fetching client %s from repo: %v", creds.ID, err)
return nil, oauth2.NewError(oauth2.ErrorServerError)
}
if !ok {
return nil, oauth2.NewError(oauth2.ErrorInvalidClient)
}
signer, err := s.KeyManager.Signer()
if err != nil {
log.Errorf("Failed to generate ID token: %v", err)
return nil, oauth2.NewError(oauth2.ErrorServerError)
}
now := time.Now()
exp := now.Add(s.SessionManager.ValidityWindow)
claims := oidc.NewClaims(s.IssuerURL.String(), creds.ID, creds.ID, now, exp)
claims.Add("name", creds.ID)
jwt, err := jose.NewSignedJWT(claims, signer)
if err != nil {
log.Errorf("Failed to generate ID token: %v", err)
return nil, oauth2.NewError(oauth2.ErrorServerError)
}
log.Infof("Client token sent: clientID=%s", creds.ID)
return jwt, nil
}
开发者ID:derekparker,项目名称:dex,代码行数:31,代码来源:server.go
示例2: addClaimsFromScope
// addClaimsFromScope adds claims that are based on the scopes that the client requested.
// Currently, these include cross-client claims (aud, azp).
func (s *Server) addClaimsFromScope(claims jose.Claims, scopes scope.Scopes, clientID string) error {
crossClientIDs := scopes.CrossClientIDs()
if len(crossClientIDs) > 0 {
var aud []string
for _, id := range crossClientIDs {
if clientID == id {
aud = append(aud, id)
continue
}
allowed, err := s.CrossClientAuthAllowed(clientID, id)
if err != nil {
log.Errorf("Failed to check cross client auth. reqClientID %v; authClient:ID %v; err: %v", clientID, id, err)
return oauth2.NewError(oauth2.ErrorServerError)
}
if !allowed {
err := oauth2.NewError(oauth2.ErrorInvalidRequest)
err.Description = fmt.Sprintf(
"%q is not authorized to perform cross-client requests for %q",
clientID, id)
return err
}
aud = append(aud, id)
}
if len(aud) == 1 {
claims.Add("aud", aud[0])
} else {
claims.Add("aud", aud)
}
claims.Add("azp", clientID)
}
return nil
}
开发者ID:GamerockSA,项目名称:dex,代码行数:34,代码来源:server.go
示例3: Token
func (s *grpcServer) Token(userID, clientID string, iat, exp time.Time) (*jose.JWT, string, error) {
signer, err := s.server.KeyManager.Signer()
if err != nil {
log.Errorf("grpc.go: Failed to generate ID token: %v", err)
return nil, "", oauth2.NewError(oauth2.ErrorServerError)
}
user, err := s.server.UserRepo.Get(nil, userID)
if err != nil {
log.Errorf("grpc.go: Failed to fetch user %q from repo: %v: ", userID, err)
return nil, "", oauth2.NewError(oauth2.ErrorServerError)
}
claims := oidc.NewClaims(s.server.IssuerURL.String(), userID, clientID, iat, exp)
user.AddToClaims(claims)
if user.Admin {
claims.Add(OtsimoUserTypeClaim, "adm")
}
jwt, err := jose.NewSignedJWT(claims, signer)
if err != nil {
log.Errorf("grpc.go: Failed to generate ID token: %v", err)
return nil, "", oauth2.NewError(oauth2.ErrorServerError)
}
refreshToken, err := s.server.RefreshTokenRepo.Create(user.ID, clientID)
if err != nil {
log.Errorf("grpc.go: Failed to generate refresh token: %v", err)
return nil, "", oauth2.NewError(oauth2.ErrorServerError)
}
return jwt, refreshToken, nil
}
开发者ID:otsimo,项目名称:accounts,代码行数:33,代码来源:grpc.go
示例4: TestRedirectAuthError
func TestRedirectAuthError(t *testing.T) {
wantCode := http.StatusFound
tests := []struct {
err error
state string
redirectURL url.URL
wantLoc string
}{
{
err: errors.New("foobar"),
state: "bazinga",
redirectURL: url.URL{Scheme: "http", Host: "server.example.com"},
wantLoc: "http://server.example.com?error=server_error&state=bazinga",
},
{
err: oauth2.NewError(oauth2.ErrorInvalidRequest),
state: "foo",
redirectURL: url.URL{Scheme: "http", Host: "server.example.com"},
wantLoc: "http://server.example.com?error=invalid_request&state=foo",
},
{
err: oauth2.NewError(oauth2.ErrorUnsupportedResponseType),
state: "bar",
redirectURL: url.URL{Scheme: "http", Host: "server.example.com"},
wantLoc: "http://server.example.com?error=unsupported_response_type&state=bar",
},
}
for i, tt := range tests {
w := httptest.NewRecorder()
redirectAuthError(w, tt.err, tt.state, tt.redirectURL)
if wantCode != w.Code {
t.Errorf("case %d: incorrect HTTP status: want=%d got=%d", i, wantCode, w.Code)
}
wantHeader := http.Header{"Location": []string{tt.wantLoc}}
gotHeader := w.Header()
if !reflect.DeepEqual(wantHeader, gotHeader) {
t.Errorf("case %d: incorrect HTTP headers: want=%#v got=%#v", i, wantHeader, gotHeader)
}
gotBody := w.Body.String()
if gotBody != "" {
t.Errorf("case %d: incorrect empty HTTP body, got=%q", i, gotBody)
}
}
}
开发者ID:Tecsisa,项目名称:dex,代码行数:49,代码来源:error_test.go
示例5: writeAuthError
func writeAuthError(w http.ResponseWriter, err error, state string) {
oerr, ok := err.(*oauth2.Error)
if !ok {
oerr = oauth2.NewError(oauth2.ErrorServerError)
}
oerr.State = state
writeResponseWithBody(w, http.StatusBadRequest, oerr)
}
开发者ID:GamerockSA,项目名称:dex,代码行数:8,代码来源:error.go
示例6: TestWriteAuthError
func TestWriteAuthError(t *testing.T) {
wantCode := http.StatusBadRequest
wantHeader := http.Header{"Content-Type": []string{"application/json"}}
tests := []struct {
err error
state string
wantBody string
}{
{
err: errors.New("foobar"),
state: "bazinga",
wantBody: `{"error":"server_error","state":"bazinga"}`,
},
{
err: oauth2.NewError(oauth2.ErrorInvalidRequest),
state: "foo",
wantBody: `{"error":"invalid_request","state":"foo"}`,
},
{
err: oauth2.NewError(oauth2.ErrorUnsupportedResponseType),
state: "bar",
wantBody: `{"error":"unsupported_response_type","state":"bar"}`,
},
}
for i, tt := range tests {
w := httptest.NewRecorder()
writeAuthError(w, tt.err, tt.state)
if wantCode != w.Code {
t.Errorf("case %d: incorrect HTTP status: want=%d got=%d", i, wantCode, w.Code)
}
gotHeader := w.Header()
if !reflect.DeepEqual(wantHeader, gotHeader) {
t.Errorf("case %d: incorrect HTTP headers: want=%#v got=%#v", i, wantHeader, gotHeader)
}
gotBody := w.Body.String()
if tt.wantBody != gotBody {
t.Errorf("case %d: incorrect HTTP body: want=%q got=%q", i, tt.wantBody, gotBody)
}
}
}
开发者ID:Tecsisa,项目名称:dex,代码行数:44,代码来源:error_test.go
示例7: RefreshToken
func (s *Server) RefreshToken(creds oidc.ClientCredentials, token string) (*jose.JWT, error) {
ok, err := s.ClientIdentityRepo.Authenticate(creds)
if err != nil {
log.Errorf("Failed fetching client %s from repo: %v", creds.ID, err)
return nil, oauth2.NewError(oauth2.ErrorServerError)
}
if !ok {
log.Errorf("Failed to Authenticate client %s", creds.ID)
return nil, oauth2.NewError(oauth2.ErrorInvalidClient)
}
userID, err := s.RefreshTokenRepo.Verify(creds.ID, token)
switch err {
case nil:
break
case refresh.ErrorInvalidToken:
return nil, oauth2.NewError(oauth2.ErrorInvalidRequest)
case refresh.ErrorInvalidClientID:
return nil, oauth2.NewError(oauth2.ErrorInvalidClient)
default:
return nil, oauth2.NewError(oauth2.ErrorServerError)
}
user, err := s.UserRepo.Get(nil, userID)
if err != nil {
// The error can be user.ErrorNotFound, but we are not deleting
// user at this moment, so this shouldn't happen.
log.Errorf("Failed to fetch user %q from repo: %v: ", userID, err)
return nil, oauth2.NewError(oauth2.ErrorServerError)
}
signer, err := s.KeyManager.Signer()
if err != nil {
log.Errorf("Failed to refresh ID token: %v", err)
return nil, oauth2.NewError(oauth2.ErrorServerError)
}
now := time.Now()
expireAt := now.Add(session.DefaultSessionValidityWindow)
claims := oidc.NewClaims(s.IssuerURL.String(), user.ID, creds.ID, now, expireAt)
user.AddToClaims(claims)
jwt, err := jose.NewSignedJWT(claims, signer)
if err != nil {
log.Errorf("Failed to generate ID token: %v", err)
return nil, oauth2.NewError(oauth2.ErrorServerError)
}
log.Infof("New token sent: clientID=%s", creds.ID)
return jwt, nil
}
开发者ID:derekparker,项目名称:dex,代码行数:53,代码来源:server.go
示例8: redirectAuthError
func redirectAuthError(w http.ResponseWriter, err error, state string, redirectURL url.URL) {
oerr, ok := err.(*oauth2.Error)
if !ok {
oerr = oauth2.NewError(oauth2.ErrorServerError)
}
q := redirectURL.Query()
q.Set("error", oerr.Type)
q.Set("state", state)
redirectURL.RawQuery = q.Encode()
w.Header().Set("Location", redirectURL.String())
w.WriteHeader(http.StatusFound)
}
开发者ID:GamerockSA,项目名称:dex,代码行数:14,代码来源:error.go
示例9: writeTokenError
func writeTokenError(w http.ResponseWriter, err error, state string) {
oerr, ok := err.(*oauth2.Error)
if !ok {
oerr = oauth2.NewError(oauth2.ErrorServerError)
}
oerr.State = state
var status int
switch oerr.Type {
case oauth2.ErrorInvalidClient:
status = http.StatusUnauthorized
w.Header().Set("WWW-Authenticate", "Basic")
default:
status = http.StatusBadRequest
}
writeResponseWithBody(w, status, oerr)
}
开发者ID:GamerockSA,项目名称:dex,代码行数:18,代码来源:error.go
示例10: Identity
func (c *uaaOAuth2Connector) Identity(cli chttp.Client) (oidc.Identity, error) {
uaaUserInfoURL := *c.uaaBaseURL
uaaUserInfoURL.Path = path.Join(uaaUserInfoURL.Path, "/userinfo")
req, err := http.NewRequest("GET", uaaUserInfoURL.String(), nil)
if err != nil {
return oidc.Identity{}, err
}
resp, err := cli.Do(req)
if err != nil {
return oidc.Identity{}, fmt.Errorf("get: %v", err)
}
defer resp.Body.Close()
switch {
case resp.StatusCode >= 400 && resp.StatusCode < 600:
// attempt to decode error from UAA
var authErr uaaError
if err := json.NewDecoder(resp.Body).Decode(&authErr); err != nil {
return oidc.Identity{}, oauth2.NewError(oauth2.ErrorAccessDenied)
}
return oidc.Identity{}, authErr
case resp.StatusCode == http.StatusOK:
default:
return oidc.Identity{}, fmt.Errorf("unexpected status from providor %s", resp.Status)
}
var user struct {
UserID string `json:"user_id"`
Email string `json:"email"`
Name string `json:"name"`
UserName string `json:"user_name"`
}
if err := json.NewDecoder(resp.Body).Decode(&user); err != nil {
return oidc.Identity{}, fmt.Errorf("getting user info: %v", err)
}
name := user.Name
if name == "" {
name = user.UserName
}
return oidc.Identity{
ID: user.UserID,
Name: name,
Email: user.Email,
}, nil
}
开发者ID:Tecsisa,项目名称:dex,代码行数:43,代码来源:connector_uaa.go
示例11: Identity
func (c *githubOAuth2Connector) Identity(cli chttp.Client) (oidc.Identity, error) {
req, err := http.NewRequest("GET", githubAPIUserURL, nil)
if err != nil {
return oidc.Identity{}, err
}
resp, err := cli.Do(req)
if err != nil {
return oidc.Identity{}, fmt.Errorf("get: %v", err)
}
defer resp.Body.Close()
switch {
case resp.StatusCode >= 400 && resp.StatusCode < 600:
// attempt to decode error from github
var authErr githubError
if err := json.NewDecoder(resp.Body).Decode(&authErr); err != nil {
return oidc.Identity{}, oauth2.NewError(oauth2.ErrorAccessDenied)
}
return oidc.Identity{}, authErr
case resp.StatusCode == http.StatusOK:
default:
return oidc.Identity{}, fmt.Errorf("unexpected status from providor %s", resp.Status)
}
var user struct {
Login string `json:"login"`
ID int64 `json:"id"`
Email string `json:"email"`
Name string `json:"name"`
}
if err := json.NewDecoder(resp.Body).Decode(&user); err != nil {
return oidc.Identity{}, fmt.Errorf("getting user info: %v", err)
}
name := user.Name
if name == "" {
name = user.Login
}
return oidc.Identity{
ID: strconv.FormatInt(user.ID, 10),
Name: name,
Email: user.Email,
}, nil
}
开发者ID:GamerockSA,项目名称:dex,代码行数:41,代码来源:connector_github.go
示例12: getAndDecode
func getAndDecode(cli chttp.Client, url string, v interface{}) error {
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return err
}
resp, err := cli.Do(req)
if err != nil {
return fmt.Errorf("get: %v", err)
}
defer resp.Body.Close()
switch {
case resp.StatusCode >= 400 && resp.StatusCode < 500:
return oauth2.NewError(oauth2.ErrorAccessDenied)
case resp.StatusCode == http.StatusOK:
default:
return fmt.Errorf("unexpected status from providor %s", resp.Status)
}
if err := json.NewDecoder(resp.Body).Decode(v); err != nil {
return fmt.Errorf("decode body: %v", err)
}
return nil
}
开发者ID:Tecsisa,项目名称:dex,代码行数:22,代码来源:connector_bitbucket.go
示例13: Identity
func (c *facebookOAuth2Connector) Identity(cli chttp.Client) (oidc.Identity, error) {
var user struct {
ID string `json:"id"`
Email string `json:"email"`
Name string `json:"name"`
}
req, err := http.NewRequest("GET", facebookGraphAPIURL, nil)
if err != nil {
return oidc.Identity{}, err
}
resp, err := cli.Do(req)
if err != nil {
return oidc.Identity{}, fmt.Errorf("get: %v", err)
}
defer resp.Body.Close()
switch {
case resp.StatusCode >= 400 && resp.StatusCode < 600:
var authErr facebookErr
if err := json.NewDecoder(resp.Body).Decode(&authErr); err != nil {
return oidc.Identity{}, oauth2.NewError(oauth2.ErrorAccessDenied)
}
return oidc.Identity{}, authErr
case resp.StatusCode == http.StatusOK:
default:
return oidc.Identity{}, fmt.Errorf("unexpected status from providor %s", resp.Status)
}
if err := json.NewDecoder(resp.Body).Decode(&user); err != nil {
return oidc.Identity{}, fmt.Errorf("decode body: %v", err)
}
return oidc.Identity{
ID: user.ID,
Name: user.Name,
Email: user.Email,
}, nil
}
开发者ID:Tecsisa,项目名称:dex,代码行数:38,代码来源:connector_facebook.go
示例14: CodeToken
func (s *Server) CodeToken(creds oidc.ClientCredentials, sessionKey string) (*jose.JWT, string, error) {
ok, err := s.ClientManager.Authenticate(creds)
if err != nil {
log.Errorf("Failed fetching client %s from repo: %v", creds.ID, err)
return nil, "", oauth2.NewError(oauth2.ErrorServerError)
}
if !ok {
log.Errorf("Failed to Authenticate client %s", creds.ID)
return nil, "", oauth2.NewError(oauth2.ErrorInvalidClient)
}
sessionID, err := s.SessionManager.ExchangeKey(sessionKey)
if err != nil {
return nil, "", oauth2.NewError(oauth2.ErrorInvalidGrant)
}
ses, err := s.SessionManager.Kill(sessionID)
if err != nil {
return nil, "", oauth2.NewError(oauth2.ErrorInvalidRequest)
}
if ses.ClientID != creds.ID {
return nil, "", oauth2.NewError(oauth2.ErrorInvalidGrant)
}
signer, err := s.KeyManager.Signer()
if err != nil {
log.Errorf("Failed to generate ID token: %v", err)
return nil, "", oauth2.NewError(oauth2.ErrorServerError)
}
user, err := s.UserRepo.Get(nil, ses.UserID)
if err != nil {
log.Errorf("Failed to fetch user %q from repo: %v: ", ses.UserID, err)
return nil, "", oauth2.NewError(oauth2.ErrorServerError)
}
claims := ses.Claims(s.IssuerURL.String())
user.AddToClaims(claims)
s.addClaimsFromScope(claims, ses.Scope, ses.ClientID)
jwt, err := jose.NewSignedJWT(claims, signer)
if err != nil {
log.Errorf("Failed to generate ID token: %v", err)
return nil, "", oauth2.NewError(oauth2.ErrorServerError)
}
// Generate refresh token when 'scope' contains 'offline_access'.
var refreshToken string
for _, scope := range ses.Scope {
if scope == "offline_access" {
log.Infof("Session %s requests offline access, will generate refresh token", sessionID)
refreshToken, err = s.RefreshTokenRepo.Create(ses.UserID, creds.ID, ses.Scope)
switch err {
case nil:
break
default:
log.Errorf("Failed to generate refresh token: %v", err)
return nil, "", oauth2.NewError(oauth2.ErrorServerError)
}
break
}
}
log.Infof("Session %s token sent: clientID=%s", sessionID, creds.ID)
return jwt, refreshToken, nil
}
开发者ID:GamerockSA,项目名称:dex,代码行数:70,代码来源:server.go
示例15: TestServerRefreshToken
func TestServerRefreshToken(t *testing.T) {
issuerURL := url.URL{Scheme: "http", Host: "server.example.com"}
credXXX := oidc.ClientCredentials{
ID: "XXX",
Secret: "secret",
}
credYYY := oidc.ClientCredentials{
ID: "YYY",
Secret: "secret",
}
signerFixture := &StaticSigner{sig: []byte("beer"), err: nil}
tests := []struct {
token string
clientID string // The client that associates with the token.
creds oidc.ClientCredentials
signer jose.Signer
err error
}{
// Everything is good.
{
fmt.Sprintf("0/%s", base64.URLEncoding.EncodeToString([]byte("refresh-1"))),
"XXX",
credXXX,
signerFixture,
nil,
},
// Invalid refresh token(malformatted).
{
"invalid-token",
"XXX",
credXXX,
signerFixture,
oauth2.NewError(oauth2.ErrorInvalidRequest),
},
// Invalid refresh token(invalid payload content).
{
fmt.Sprintf("0/%s", base64.URLEncoding.EncodeToString([]byte("refresh-2"))),
"XXX",
credXXX,
signerFixture,
oauth2.NewError(oauth2.ErrorInvalidRequest),
},
// Invalid refresh token(invalid ID content).
{
fmt.Sprintf("1/%s", base64.URLEncoding.EncodeToString([]byte("refresh-1"))),
"XXX",
credXXX,
signerFixture,
oauth2.NewError(oauth2.ErrorInvalidRequest),
},
// Invalid client(client is not associated with the token).
{
fmt.Sprintf("0/%s", base64.URLEncoding.EncodeToString([]byte("refresh-1"))),
"XXX",
credYYY,
signerFixture,
oauth2.NewError(oauth2.ErrorInvalidClient),
},
// Invalid client(no client ID).
{
fmt.Sprintf("0/%s", base64.URLEncoding.EncodeToString([]byte("refresh-1"))),
"XXX",
oidc.ClientCredentials{ID: "", Secret: "aaa"},
signerFixture,
oauth2.NewError(oauth2.ErrorInvalidClient),
},
// Invalid client(no such client).
{
fmt.Sprintf("0/%s", base64.URLEncoding.EncodeToString([]byte("refresh-1"))),
"XXX",
oidc.ClientCredentials{ID: "AAA", Secret: "aaa"},
signerFixture,
oauth2.NewError(oauth2.ErrorInvalidClient),
},
// Invalid client(no secrets).
{
fmt.Sprintf("0/%s", base64.URLEncoding.EncodeToString([]byte("refresh-1"))),
"XXX",
oidc.ClientCredentials{ID: "XXX"},
signerFixture,
oauth2.NewError(oauth2.ErrorInvalidClient),
},
// Invalid client(invalid secret).
{
fmt.Sprintf("0/%s", base64.URLEncoding.EncodeToString([]byte("refresh-1"))),
"XXX",
oidc.ClientCredentials{ID: "XXX", Secret: "bad-secret"},
signerFixture,
oauth2.NewError(oauth2.ErrorInvalidClient),
},
// Signing operation fails.
{
fmt.Sprintf("0/%s", base64.URLEncoding.EncodeToString([]byte("refresh-1"))),
"XXX",
credXXX,
&StaticSigner{sig: nil, err: errors.New("fail")},
oauth2.NewError(oauth2.ErrorServerError),
//.........这里部分代码省略.........
开发者ID:adrianlop,项目名称:dex,代码行数:101,代码来源:server_test.go
示例16: TestServerTokenFail
func TestServerTokenFail(t *testing.T) {
issuerURL := url.URL{Scheme: "http", Host: "server.example.com"}
keyFixture := "goodkey"
ccFixture := oidc.ClientCredentials{
ID: "XXX",
Secret: "secrete",
}
signerFixture := &StaticSigner{sig: []byte("beer"), err: nil}
tests := []struct {
signer jose.Signer
argCC oidc.ClientCredentials
argKey string
err error
scope []string
refreshToken string
}{
// control test case to make sure fixtures check out
{
signer: signerFixture,
argCC: ccFixture,
argKey: keyFixture,
scope: []string{"openid", "offline_access"},
refreshToken: fmt.Sprintf("0/%s", base64.URLEncoding.EncodeToString([]byte("refresh-1"))),
},
// no 'offline_access' in 'scope', should get empty refresh token
{
signer: signerFixture,
argCC: ccFixture,
argKey: keyFixture,
scope: []string{"openid"},
},
// unrecognized key
{
signer: signerFixture,
argCC: ccFixture,
argKey: "foo",
err: oauth2.NewError(oauth2.ErrorInvalidGrant),
scope: []string{"openid", "offline_access"},
},
// unrecognized client
{
signer: signerFixture,
argCC: oidc.ClientCredentials{ID: "YYY"},
argKey: keyFixture,
err: oauth2.NewError(oauth2.ErrorInvalidClient),
scope: []string{"openid", "offline_access"},
},
// signing operation fails
{
signer: &StaticSigner{sig: nil, err: errors.New("fail")},
argCC: ccFixture,
argKey: keyFixture,
err: oauth2.NewError(oauth2.ErrorServerError),
scope: []string{"openid", "offline_access"},
},
}
for i, tt := range tests {
sm := session.NewSessionManager(session.NewSessionRepo(), session.NewSessionKeyRepo())
sm.GenerateCode = func() (string, error) { return keyFixture, nil }
sessionID, err := sm.NewSession("connector_id", ccFixture.ID, "bogus", url.URL{}, "", false, tt.scope)
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
_, err = sm.AttachRemoteIdentity(sessionID, oidc.Identity{})
if err != nil {
t.Errorf("case %d: unexpected error: %v", i, err)
continue
}
km := &StaticKeyManager{
signer: tt.signer,
}
ciRepo := client.NewClientIdentityRepo([]oidc.ClientIdentity{
oidc.ClientIdentity{Credentials: ccFixture},
})
_, err = sm.AttachUser(sessionID, "testid-1")
if err != nil {
t.Fatalf("case %d: unexpected error: %v", i, err)
}
userRepo, err := makeNewUserRepo()
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
refreshTokenRepo, err := refreshtest.NewTestRefreshTokenRepo()
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
srv := &Server{
IssuerURL: issuerURL,
//.........这里部分代码省略.........
开发者ID:adrianlop,项目名称:dex,代码行数:101,代码来源:server_test.go
示例17: TestServerRefreshToken
func TestServerRefreshToken(t *testing.T) {
clientB := client.Client{
Credentials: oidc.ClientCredentials{
ID: "example2.com",
Secret: clientTestSecret,
},
Metadata: oidc.ClientMetadata{
RedirectURIs: []url.URL{
url.URL{Scheme: "https", Host: "example2.com", Path: "one/two/three"},
},
},
}
signerFixture := &StaticSigner{sig: []byte("beer"), err: nil}
// NOTE(ericchiang): These tests assume that the database ID of the first
// refresh token will be "1".
tests := []struct {
token string
expectedRefreshToken string
clientID string // The client that associates with the token.
creds oidc.ClientCredentials
signer jose.Signer
createScopes []string
refreshScopes []string
expectedAud []string
err error
}{
// Everything is good.
{
token: getRefreshTokenEncoded("1", "refresh-1"),
expectedRefreshToken: getRefreshTokenEncoded("1", "refresh-2"),
clientID: testClientID,
creds: testClientCredentials,
signer: signerFixture,
createScopes: []string{"openid", "profile"},
refreshScopes: []string{"openid", "profile"},
},
// Asking for a scope not originally granted to you.
{
token: getRefreshTokenEncoded("1", "refresh-1"),
clientID: testClientID,
creds: testClientCredentials,
signer: signerFixture,
createScopes: []string{"openid", "profile"},
refreshScopes: []string{"openid", "profile", "extra_scope"},
err: oauth2.NewError(oauth2.ErrorInvalidRequest),
},
// Invalid refresh token(malformatted).
{
token: "invalid-token",
clientID: testClientID,
creds: testClientCredentials,
signer: signerFixture,
createScopes: []string{"openid", "profile"},
refreshScopes: []string{"openid", "profile"},
err: oauth2.NewError(oauth2.ErrorInvalidRequest),
},
// Invalid refresh token(invalid payload content).
{
token: getRefreshTokenEncoded("1", "refresh-2"),
clientID: testClientID,
creds: testClientCredentials,
signer: signerFixture,
createScopes: []string{"openid", "profile"},
refreshScopes: []string{"openid", "profile"},
err: oauth2.NewError(oauth2.ErrorInvalidRequest),
},
// Invalid refresh token(invalid ID content).
{
token: getRefreshTokenEncoded("0", "refresh-1"),
clientID: testClientID,
creds: testClientCredentials,
signer: signerFixture,
createScopes: []string{"openid", "profile"},
refreshScopes: []string{"openid", "profile"},
err: oauth2.NewError(oauth2.ErrorInvalidRequest),
},
// Invalid client(client is not associated with the token).
{
token: getRefreshTokenEncoded("1", "refresh-1"),
clientID: testClientID,
creds: clientB.Credentials,
signer: signerFixture,
createScopes: []string{"openid", "profile"},
refreshScopes: []string{"openid", "profile"},
err: oauth2.NewError(oauth2.ErrorInvalidClient),
},
// Invalid client(no client ID).
{
token: getRefreshTokenEncoded("1", "refresh-1"),
clientID: testClientID,
creds: oidc.ClientCredentials{ID: "", Secret: "aaa"},
signer: signerFixture,
createScopes: []string{"openid", "profile"},
refreshScopes: []string{"openid", "profile"},
err: oauth2.NewError(oauth2.ErrorInvalidClient),
},
// Invalid client(no such client).
{
//.........这里部分代码省略.........
开发者ID:Tecsisa,项目名称:dex,代码行数:101,代码来源:server_test.go
示例18: TestServerTokenFail
func TestServerTokenFail(t *testing.T) {
keyFixture := "goodkey"
signerFixture := &StaticSigner{sig: []byte("beer"), err: nil}
tests := []struct {
signer jose.Signer
argCC oidc.ClientCredentials
argKey string
err error
scope []string
refreshToken string
}{
// control test case to make sure fixtures check out
{
// NOTE(ericchiang): This test assumes that the database ID of the first
// refresh token will be "1".
signer: signerFixture,
argCC: testClientCredentials,
argKey: keyFixture,
scope: []string{"openid", "offline_access"},
refreshToken: fmt.Sprintf("1/%s", base64.URLEncoding.EncodeToString([]byte("refresh-1"))),
},
// no 'offline_access' in 'scope', should get empty refresh token
{
signer: signerFixture,
argCC: testClientCredentials,
argKey: keyFixture,
scope: []string{"openid"},
},
// unrecognized key
{
signer: signerFixture,
argCC: testClientCredentials,
argKey: "foo",
err: oauth2.NewError(oauth2.ErrorInvalidGrant),
scope: []string{"openid", "offline_access"},
},
// unrecognized client
{
signer: signerFixture,
argCC: oidc.ClientCredentials{ID: "YYY"},
argKey: keyFixture,
err: oauth2.NewError(oauth2.ErrorInvalidClient),
scope: []string{"openid", "offline_access"},
},
// signing operation fails
{
signer: &StaticSigner{sig: nil, err: errors.New("fail")},
argCC: testClientCredentials,
argKey: keyFixture,
err: oauth2.NewError(oauth2.ErrorServerError),
scope: []string{"openid", "offline_access"},
},
}
for i, tt := range tests {
f, err := makeTestFixtures()
if err != nil {
t.Fatalf("error making test fixtures: %v", err)
}
sm := f.sessionManager
sm.GenerateCode = func() (string, error) { return keyFixture, nil }
f.srv.RefreshTokenRepo = refreshtest.NewTestRefreshTokenRepo()
f.srv.KeyManager = &StaticKeyManager{
signer: tt.signer,
}
sessionID, err := sm.NewSession(testConnectorID1, testClientID, "bogus", url.URL{}, "", false, tt.scope)
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
_, err = sm.AttachRemoteIdentity(sessionID, oidc.Identity{})
if err != nil {
t.Errorf("case %d: unexpected error: %v", i, err)
continue
}
_, err = sm.AttachUser(sessionID, testUserID1)
if err != nil {
t.Fatalf("case %d: unexpected error: %v", i, err)
}
_, err = sm.NewSessionKey(sessionID)
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
jwt, token, expiresAt, err := f.srv.CodeToken(tt.argCC, tt.argKey)
if token != tt.refreshToken {
fmt.Printf("case %d: expect refresh token %q, got %q\n", i, tt.refreshToken, token)
t.Fatalf("case %d: expect refresh token %q, got %q", i, tt.refreshToken, token)
panic("")
}
if !reflect.DeepEqual(err, tt.err) {
//.........这里部分代码省略.........
开发者ID:Tecsisa,项目名称:dex,代码行数:101,代码来源:server_test.go
示例19: validateScopes
func validateScopes(srv OIDCServer, clientID string, scopes []string) error {
foundOpenIDScope := false
for i, curScope := range scopes {
if i > 0 && curScope == scopes[i-1] {
err := oauth2.NewError(oauth2.ErrorInvalidRequest)
err.Description = fmt.Sprintf(
"Duplicate scopes are not allowed: %q",
curScope)
return err
}
switch {
case strings.HasPrefix(curScope, scope.ScopeGoogleCrossClient):
otherClient := curScope[len(scope.ScopeGoogleCrossClient):]
var allowed bool
var err error
if otherClient == clientID {
allowed = true
} else {
allowed, err = srv.CrossClientAuthAllowed(clientID, otherClient)
if err != nil {
return err
}
}
if !allowed {
err := oauth2.NewError(oauth2.ErrorInvalidRequest)
err.Description = fmt.Sprintf(
"%q is not authorized to perform cross-client requests for %q",
clientID, otherClient)
return err
}
case curScope == "openid":
foundOpenIDScope = true
case curScope == "profile":
case curScope == "email":
case curScope == scope.ScopeGroups:
case curScope == "offline_access":
// According to the spec, for offline_access scope, the client must
// use a response_type value that would result in an Authorization
// Code. Currently oauth2.ResponseTypeCode is the only supported
// response type, and it's been checked above, so we don't need to
// check it again here.
//
// TODO(yifan): Verify that 'consent' should be in 'prompt'.
default:
// Reject all other scopes.
err := oauth2.NewError(oauth2.ErrorInvalidRequest)
err.Description = fmt.Sprintf("%q is not a recognized scope", curScope)
return err
}
}
if !foundOpenIDScope {
log.Errorf("Invalid auth request: missing 'openid' in 'scope'")
err := oauth2.NewError(oauth2.ErrorInvalidRequest)
err.Description = "Invalid auth request: missing 'openid' in 'scope'"
return err
}
return nil
}
开发者ID:Tecsisa,项目名称:dex,代码行数:61,代码来源:http.go
示例20: handleTokenFunc
func handleTokenFunc(srv OIDCServer) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
w.Header().Set("Allow", "POST")
phttp.WriteError(w, http.StatusMethodNotAllowed, fmt.Sprintf("POST only acceptable method"))
return
}
err := r.ParseForm()
if err != nil {
log.Errorf("error parsing request: %v", err)
writeTokenError(w, oauth2.NewError(oauth2.ErrorInvalidRequest), "")
return
}
state := r.PostForm.Get("state")
user, password, ok := r.BasicAuth()
if !ok {
log.Errorf("error parsing basic auth")
writeTokenError(w, oauth2.NewError(oauth2.ErrorInvalidClient), state)
return
}
creds := oidc.ClientCredentials{ID: user, Secret: password}
var jwt *jose.JWT
var refreshToken string
grantType := r.PostForm.Get("grant_type")
switch grantType {
case oauth2.GrantTypeAuthCode:
code := r.PostForm.Get("code")
if code == "" {
log.Errorf("missing code param")
writeTokenError(w, oauth2.NewError(oauth2.ErrorInvalidRequest), state)
return
}
jwt, refreshToken, err = srv.CodeToken(creds, code)
if err != nil {
log.Errorf("couldn't exchange code for token: %v", err)
writeTokenError(w, err, state)
return
}
case oauth2.GrantTypeClientCreds:
jwt, err = srv.ClientCredsToken(creds)
if err != nil {
log.Errorf("couldn't creds for token: %v", err)
writeTokenError(w, err, state)
return
}
case oauth2.GrantTypeRefreshToken:
token := r.PostForm.Get("refresh_token")
if token == "" {
writeTokenError(w, oauth2.NewError(oauth2.ErrorInvalidRequest), state)
return
}
jwt, err = srv.RefreshToken(creds, token)
if err != nil {
writeTokenError(w, err, state)
return
}
default:
log.Errorf("unsupported grant: %v", grantType)
writeTokenError(w, oauth2.NewError(oauth2.ErrorUnsupportedGrantType), state)
return
}
t := oAuth2Token{
AccessToken: jwt.Encode(),
IDToken: jwt.Encode(),
TokenType: "bearer",
RefreshToken: refreshToken,
}
b, err := json.Marshal(t)
if err != nil {
log.Errorf("Failed marshaling %#v to JSON: %v", t, err)
writeTokenError(w, oauth2.NewError(oauth2.ErrorServerError), state)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write(b)
}
}
开发者ID:set321go,项目名称:dex,代码行数:87,代码来源:http.go
注:本文中的github.com/coreos/go-oidc/oauth2.NewError函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论