From a002e30577d3fe2c9df2089b3e4332b183f38fc2 Mon Sep 17 00:00:00 2001 From: arekkas Date: Tue, 1 May 2018 23:22:03 +0200 Subject: [PATCH] oauth2: Improves the consent flow design This patch makes significant changes to the consent flow. First, the consent flow is being renamed to "User Login and Consent Flow" and is split into two redirection flows, the "User Login Redirection Flow" and the "User Consent Flow". Conceptually, not a lot has changed but the APIs have been cleaned up and the new flow is a huge step towards OpenID Connect Certification. Besides easier implementation on the (previously known as) consent app, this patch introduces a new set of features which lets ORY Hydra detect previous logins and previously accepted consent requests. In turn, the user does not need to login or consent on every OAuth2 Authorize Code Flow. This patch additionally lays the foundation for revoking tokens per user or per user and client. Awesome. Closes #771 Closes #772 --- Gopkg.lock | 30 +- Gopkg.toml | 4 +- UPGRADE.md | 59 +- client/manager_sql.go | 10 +- cmd/cli/handler_migrate.go | 3 +- cmd/clients_create.go | 2 +- cmd/host.go | 20 +- cmd/root.go | 16 +- cmd/root_test.go | 2 +- cmd/server/handler.go | 15 +- cmd/server/handler_consent_factory.go | 20 +- cmd/server/handler_oauth2_factory.go | 64 +- cmd/server/helper_client.go | 66 - cmd/token_client.go | 7 +- cmd/token_user.go | 14 +- config/backend_plugin.go | 12 +- config/config.go | 14 +- config/context.go | 4 +- consent/doc.go | 58 + consent/handler.go | 379 ++++ consent/helper.go | 84 + consent/helper_test.go | 96 + consent/manager.go | 40 + consent/manager_memory.go | 186 ++ consent/manager_sql.go | 283 +++ consent/manager_test.go | 348 +++ consent/sql_helper.go | 348 +++ pkg/split_string.go => consent/strategy.go | 18 +- consent/strategy_default.go | 359 ++++ consent/strategy_default_test.go | 460 ++++ consent/strategy_test_helper.go | 66 + consent/types.go | 257 +++ docs/api.swagger.json | 1869 ++++------------- integration/sql_schema_test.go | 10 +- metrics/middleware.go | 2 +- oauth2/consent.go | 31 - oauth2/consent_handler.go | 169 -- oauth2/consent_manager.go | 89 - oauth2/consent_manager_memory.go | 80 - oauth2/consent_manager_sql.go | 253 --- oauth2/consent_manager_sql_test.go | 65 - oauth2/consent_manager_test.go | 132 -- oauth2/consent_sdk_test.go | 98 - oauth2/consent_strategy.go | 148 -- oauth2/consent_strategy_test.go | 150 -- oauth2/doc.go | 52 - oauth2/fosite_store_test.go | 2 - oauth2/handler.go | 110 +- ...point.go => handler_fallback_endpoints.go} | 35 +- ....go => handler_fallback_endpoints_test.go} | 0 oauth2/handler_struct.go | 24 +- oauth2/handler_test.go | 69 - oauth2/oauth2_auth_code_test.go | 55 +- oauth2/oauth2_test.go | 57 +- oauth2/session.go | 4 +- pkg/joinURL.go | 46 - pkg/joinURL_test.go | 53 - pkg/url.go | 38 - sdk/go/hydra/sdk_api.go | 10 +- sdk/go/hydra/swagger/README.md | 24 +- .../hydra/swagger/accept_consent_request.go | 25 + sdk/go/hydra/swagger/accept_login_request.go | 26 + ...t_payload.go => authentication_session.go} | 12 +- ...uest_rejection.go => completed_request.go} | 6 +- sdk/go/hydra/swagger/consent_request.go | 28 +- .../swagger/consent_request_acceptance.go | 26 - .../hydra/swagger/consent_request_manager.go | 14 - .../hydra/swagger/consent_request_session.go | 20 + .../swagger/docs/AcceptConsentRequest.md | 13 + .../hydra/swagger/docs/AcceptLoginRequest.md | 13 + ...estPayload.md => AuthenticationSession.md} | 6 +- ...tConsentRequest.md => CompletedRequest.md} | 5 +- sdk/go/hydra/swagger/docs/ConsentRequest.md | 12 +- .../swagger/docs/ConsentRequestAcceptance.md | 13 - .../swagger/docs/ConsentRequestManager.md | 9 - .../swagger/docs/ConsentRequestSession.md | 11 + sdk/go/hydra/swagger/docs/Handler.md | 1 + sdk/go/hydra/swagger/docs/LoginRequest.md | 16 + sdk/go/hydra/swagger/docs/OAuth2Api.md | 150 +- .../swagger/docs/OAuth2consentRequest.md | 14 - .../swagger/docs/OpenIdConnectContext.md | 12 + sdk/go/hydra/swagger/docs/RejectRequest.md | 14 + sdk/go/hydra/swagger/handler.go | 2 + sdk/go/hydra/swagger/login_request.go | 33 + sdk/go/hydra/swagger/o_auth2_api.go | 272 ++- .../hydra/swagger/o_auth2_consent_request.go | 29 - .../hydra/swagger/open_id_connect_context.go | 23 + ...t_consent_request.go => reject_request.go} | 13 +- .../swagger/swagger_reject_consent_request.go | 18 - sdk/js/swagger/README.md | 24 +- sdk/js/swagger/docs/AcceptConsentRequest.md | 11 + sdk/js/swagger/docs/AcceptLoginRequest.md | 11 + sdk/js/swagger/docs/AuthenticationSession.md | 10 + sdk/js/swagger/docs/CompletedRequest.md | 8 + sdk/js/swagger/docs/ConsentRequest.md | 12 +- .../swagger/docs/ConsentRequestAcceptance.md | 11 - sdk/js/swagger/docs/ConsentRequestManager.md | 7 - .../swagger/docs/ConsentRequestRejection.md | 8 - sdk/js/swagger/docs/ConsentRequestSession.md | 9 + sdk/js/swagger/docs/Handler.md | 1 + sdk/js/swagger/docs/LoginRequest.md | 14 + sdk/js/swagger/docs/OAuth2Api.md | 241 ++- sdk/js/swagger/docs/OAuth2consentRequest.md | 12 - sdk/js/swagger/docs/OpenIDConnectContext.md | 10 + sdk/js/swagger/docs/RejectRequest.md | 12 + .../docs/SwaggerAcceptConsentRequest.md | 9 - .../docs/SwaggerOAuthConsentRequestPayload.md | 8 - .../docs/SwaggerRejectConsentRequest.md | 9 - sdk/js/swagger/src/api/OAuth2Api.js | 329 ++- sdk/js/swagger/src/index.js | 110 +- .../swagger/src/model/AcceptConsentRequest.js | 111 + ...estAcceptance.js => AcceptLoginRequest.js} | 58 +- ...estManager.js => AuthenticationSession.js} | 42 +- ...equestRejection.js => CompletedRequest.js} | 29 +- sdk/js/swagger/src/model/ConsentRequest.js | 87 +- .../src/model/ConsentRequestSession.js | 88 + sdk/js/swagger/src/model/Handler.js | 24 +- sdk/js/swagger/src/model/LoginRequest.js | 139 ++ .../swagger/src/model/OAuth2ConsentRequest.js | 114 - .../swagger/src/model/OpenIDConnectContext.js | 96 + sdk/js/swagger/src/model/RejectRequest.js | 115 + .../src/model/SwaggerAcceptConsentRequest.js | 93 - .../SwaggerOAuthConsentRequestPayload.js | 79 - .../src/model/SwaggerRejectConsentRequest.js | 93 - sdk/php/swagger/README.md | 24 +- sdk/php/swagger/docs/Api/OAuth2Api.md | 230 +- .../docs/Model/AcceptConsentRequest.md | 13 + .../swagger/docs/Model/AcceptLoginRequest.md | 13 + .../docs/Model/AuthenticationSession.md} | 7 +- ...tRequestManager.md => CompletedRequest.md} | 3 +- sdk/php/swagger/docs/Model/ConsentRequest.md | 12 +- .../docs/Model/ConsentRequestAcceptance.md | 13 - .../docs/Model/ConsentRequestRejection.md | 10 - .../docs/Model/ConsentRequestSession.md | 11 + sdk/php/swagger/docs/Model/Handler.md | 1 + sdk/php/swagger/docs/Model/LoginRequest.md | 16 + .../docs/Model/OAuth2ConsentRequest.md | 14 - .../docs/Model/OpenIDConnectContext.md | 12 + .../swagger/docs/Model/RejectRequest.md} | 8 +- .../docs/Model/SwaggerAcceptConsentRequest.md | 11 - .../SwaggerOAuthConsentRequestPayload.md | 10 - .../docs/Model/SwaggerRejectConsentRequest.md | 11 - sdk/php/swagger/lib/Api/OAuth2Api.php | 484 ++++- .../lib/Model/AcceptConsentRequest.php | 323 +++ ...tAcceptance.php => AcceptLoginRequest.php} | 94 +- ...tRequest.php => AuthenticationSession.php} | 87 +- ...uestRejection.php => CompletedRequest.php} | 34 +- sdk/php/swagger/lib/Model/ConsentRequest.php | 190 +- .../lib/Model/ConsentRequestManager.php | 220 -- ...tRequest.php => ConsentRequestSession.php} | 76 +- sdk/php/swagger/lib/Model/Handler.php | 27 + sdk/php/swagger/lib/Model/LoginRequest.php | 404 ++++ .../lib/Model/OpenIDConnectContext.php | 296 +++ ...h2ConsentRequest.php => RejectRequest.php} | 140 +- .../SwaggerOAuthConsentRequestPayload.php | 248 --- 155 files changed, 7711 insertions(+), 5220 deletions(-) create mode 100644 consent/doc.go create mode 100644 consent/handler.go create mode 100644 consent/helper.go create mode 100644 consent/helper_test.go create mode 100644 consent/manager.go create mode 100644 consent/manager_memory.go create mode 100644 consent/manager_sql.go create mode 100644 consent/manager_test.go create mode 100644 consent/sql_helper.go rename pkg/split_string.go => consent/strategy.go (69%) create mode 100644 consent/strategy_default.go create mode 100644 consent/strategy_default_test.go create mode 100644 consent/strategy_test_helper.go create mode 100644 consent/types.go delete mode 100644 oauth2/consent.go delete mode 100644 oauth2/consent_handler.go delete mode 100644 oauth2/consent_manager.go delete mode 100644 oauth2/consent_manager_memory.go delete mode 100644 oauth2/consent_manager_sql.go delete mode 100644 oauth2/consent_manager_sql_test.go delete mode 100644 oauth2/consent_manager_test.go delete mode 100644 oauth2/consent_sdk_test.go delete mode 100644 oauth2/consent_strategy.go delete mode 100644 oauth2/consent_strategy_test.go rename oauth2/{handler_default_consent_endpoint.go => handler_fallback_endpoints.go} (50%) rename oauth2/{handler_default_consent_endpoint_test.go => handler_fallback_endpoints_test.go} (100%) delete mode 100644 pkg/joinURL.go delete mode 100644 pkg/joinURL_test.go delete mode 100644 pkg/url.go create mode 100644 sdk/go/hydra/swagger/accept_consent_request.go create mode 100644 sdk/go/hydra/swagger/accept_login_request.go rename sdk/go/hydra/swagger/{swagger_o_auth_consent_request_payload.go => authentication_session.go} (69%) rename sdk/go/hydra/swagger/{consent_request_rejection.go => completed_request.go} (70%) delete mode 100644 sdk/go/hydra/swagger/consent_request_acceptance.go delete mode 100644 sdk/go/hydra/swagger/consent_request_manager.go create mode 100644 sdk/go/hydra/swagger/consent_request_session.go create mode 100644 sdk/go/hydra/swagger/docs/AcceptConsentRequest.md create mode 100644 sdk/go/hydra/swagger/docs/AcceptLoginRequest.md rename sdk/go/hydra/swagger/docs/{SwaggerOAuthConsentRequestPayload.md => AuthenticationSession.md} (55%) rename sdk/go/hydra/swagger/docs/{SwaggerAcceptConsentRequest.md => CompletedRequest.md} (59%) delete mode 100644 sdk/go/hydra/swagger/docs/ConsentRequestAcceptance.md delete mode 100644 sdk/go/hydra/swagger/docs/ConsentRequestManager.md create mode 100644 sdk/go/hydra/swagger/docs/ConsentRequestSession.md create mode 100644 sdk/go/hydra/swagger/docs/LoginRequest.md delete mode 100644 sdk/go/hydra/swagger/docs/OAuth2consentRequest.md create mode 100644 sdk/go/hydra/swagger/docs/OpenIdConnectContext.md create mode 100644 sdk/go/hydra/swagger/docs/RejectRequest.md create mode 100644 sdk/go/hydra/swagger/login_request.go delete mode 100644 sdk/go/hydra/swagger/o_auth2_consent_request.go create mode 100644 sdk/go/hydra/swagger/open_id_connect_context.go rename sdk/go/hydra/swagger/{swagger_accept_consent_request.go => reject_request.go} (61%) delete mode 100644 sdk/go/hydra/swagger/swagger_reject_consent_request.go create mode 100644 sdk/js/swagger/docs/AcceptConsentRequest.md create mode 100644 sdk/js/swagger/docs/AcceptLoginRequest.md create mode 100644 sdk/js/swagger/docs/AuthenticationSession.md create mode 100644 sdk/js/swagger/docs/CompletedRequest.md delete mode 100644 sdk/js/swagger/docs/ConsentRequestAcceptance.md delete mode 100644 sdk/js/swagger/docs/ConsentRequestManager.md delete mode 100644 sdk/js/swagger/docs/ConsentRequestRejection.md create mode 100644 sdk/js/swagger/docs/ConsentRequestSession.md create mode 100644 sdk/js/swagger/docs/LoginRequest.md delete mode 100644 sdk/js/swagger/docs/OAuth2consentRequest.md create mode 100644 sdk/js/swagger/docs/OpenIDConnectContext.md create mode 100644 sdk/js/swagger/docs/RejectRequest.md delete mode 100644 sdk/js/swagger/docs/SwaggerAcceptConsentRequest.md delete mode 100644 sdk/js/swagger/docs/SwaggerOAuthConsentRequestPayload.md delete mode 100644 sdk/js/swagger/docs/SwaggerRejectConsentRequest.md create mode 100644 sdk/js/swagger/src/model/AcceptConsentRequest.js rename sdk/js/swagger/src/model/{ConsentRequestAcceptance.js => AcceptLoginRequest.js} (50%) rename sdk/js/swagger/src/model/{ConsentRequestManager.js => AuthenticationSession.js} (59%) rename sdk/js/swagger/src/model/{ConsentRequestRejection.js => CompletedRequest.js} (65%) create mode 100644 sdk/js/swagger/src/model/ConsentRequestSession.js create mode 100644 sdk/js/swagger/src/model/LoginRequest.js delete mode 100644 sdk/js/swagger/src/model/OAuth2ConsentRequest.js create mode 100644 sdk/js/swagger/src/model/OpenIDConnectContext.js create mode 100644 sdk/js/swagger/src/model/RejectRequest.js delete mode 100644 sdk/js/swagger/src/model/SwaggerAcceptConsentRequest.js delete mode 100644 sdk/js/swagger/src/model/SwaggerOAuthConsentRequestPayload.js delete mode 100644 sdk/js/swagger/src/model/SwaggerRejectConsentRequest.js create mode 100644 sdk/php/swagger/docs/Model/AcceptConsentRequest.md create mode 100644 sdk/php/swagger/docs/Model/AcceptLoginRequest.md rename sdk/{go/hydra/swagger/docs/SwaggerRejectConsentRequest.md => php/swagger/docs/Model/AuthenticationSession.md} (61%) rename sdk/php/swagger/docs/Model/{ConsentRequestManager.md => CompletedRequest.md} (61%) delete mode 100644 sdk/php/swagger/docs/Model/ConsentRequestAcceptance.md delete mode 100644 sdk/php/swagger/docs/Model/ConsentRequestRejection.md create mode 100644 sdk/php/swagger/docs/Model/ConsentRequestSession.md create mode 100644 sdk/php/swagger/docs/Model/LoginRequest.md delete mode 100644 sdk/php/swagger/docs/Model/OAuth2ConsentRequest.md create mode 100644 sdk/php/swagger/docs/Model/OpenIDConnectContext.md rename sdk/{go/hydra/swagger/docs/ConsentRequestRejection.md => php/swagger/docs/Model/RejectRequest.md} (53%) delete mode 100644 sdk/php/swagger/docs/Model/SwaggerAcceptConsentRequest.md delete mode 100644 sdk/php/swagger/docs/Model/SwaggerOAuthConsentRequestPayload.md delete mode 100644 sdk/php/swagger/docs/Model/SwaggerRejectConsentRequest.md create mode 100644 sdk/php/swagger/lib/Model/AcceptConsentRequest.php rename sdk/php/swagger/lib/Model/{ConsentRequestAcceptance.php => AcceptLoginRequest.php} (66%) rename sdk/php/swagger/lib/Model/{SwaggerRejectConsentRequest.php => AuthenticationSession.php} (75%) rename sdk/php/swagger/lib/Model/{ConsentRequestRejection.php => CompletedRequest.php} (85%) delete mode 100644 sdk/php/swagger/lib/Model/ConsentRequestManager.php rename sdk/php/swagger/lib/Model/{SwaggerAcceptConsentRequest.php => ConsentRequestSession.php} (70%) create mode 100644 sdk/php/swagger/lib/Model/LoginRequest.php create mode 100644 sdk/php/swagger/lib/Model/OpenIDConnectContext.php rename sdk/php/swagger/lib/Model/{OAuth2ConsentRequest.php => RejectRequest.php} (61%) delete mode 100644 sdk/php/swagger/lib/Model/SwaggerOAuthConsentRequestPayload.php diff --git a/Gopkg.lock b/Gopkg.lock index ca8a3f63682..a700c2dc6f5 100644 --- a/Gopkg.lock +++ b/Gopkg.lock @@ -82,6 +82,15 @@ revision = "a0583e0143b1624142adab07e0e97fe106d99561" version = "v1.3" +[[projects]] + branch = "master" + name = "github.com/golang/gddo" + packages = [ + "httputil", + "httputil/header" + ] + revision = "416d5fc8c9c85e9ec9252a70d01e069f4b287ff0" + [[projects]] branch = "master" name = "github.com/golang/protobuf" @@ -271,8 +280,19 @@ "token/hmac", "token/jwt" ] - revision = "2bf9b6c4177be3050ff9ba3b82c6474e4c324c39" - version = "v0.18.0" + revision = "91c9d194a88e6b395668211df60cb512eab08541" + version = "v0.18.1" + +[[projects]] + branch = "master" + name = "github.com/ory/go-convenience" + packages = [ + "mapx", + "stringslice", + "stringsx", + "urlx" + ] + revision = "cf3c3570c7b941a7180cdc036c8b06eebd95dcb1" [[projects]] name = "github.com/ory/graceful" @@ -283,8 +303,8 @@ [[projects]] name = "github.com/ory/herodot" packages = ["."] - revision = "e16e86900c6c08ed085117308701a823b3da77fc" - version = "v0.1.3" + revision = "809d81bb89b684063f794913e1fe3635f0b20222" + version = "v0.2.2" [[projects]] name = "github.com/ory/ladon" @@ -545,6 +565,6 @@ [solve-meta] analyzer-name = "dep" analyzer-version = 1 - inputs-digest = "33ad6060ba98ec0df48b987abfb552bace7263bf08d56a91deac2f8a31b75553" + inputs-digest = "ed156fb22c2ead58aea442975fec6c0e30ab3bc8deb7fd0c0e821ec2c6648b76" solver-name = "gps-cdcl" solver-version = 1 diff --git a/Gopkg.toml b/Gopkg.toml index d560ac7c60d..d4c94c524b4 100644 --- a/Gopkg.toml +++ b/Gopkg.toml @@ -75,7 +75,7 @@ [[constraint]] name = "github.com/ory/fosite" - version = "0.18.0" + version = "0.18.1" [[constraint]] name = "github.com/ory/graceful" @@ -83,7 +83,7 @@ [[constraint]] name = "github.com/ory/herodot" - version = "0.1.3" + version = "0.2.2" [[constraint]] name = "github.com/ory/ladon" diff --git a/UPGRADE.md b/UPGRADE.md index 7f4ab5796c5..6433671fc85 100644 --- a/UPGRADE.md +++ b/UPGRADE.md @@ -59,6 +59,60 @@ This section summarizes important changes introduced in 1.0.0. ### Major breaking changes +#### Changes to the CLI + +The CLI has changed in order to improve developer experience and adopt to the changes made with this release. + +##### `hydra host` + +The command `hydra host` has been renamed to `hydra serve` as projects ORY Oathkeeper and ORY Keto use the `serve` terminology +as well. + +Because this patch removes the internal access control, no root client and root policy will be created upon start up. Thus, +environment variable `FORCE_ROOT_CLIENT_CREDENTIALS` has been removed without replacement. + +To better reflect what environment variables touch which system, ISSUER has been renamed to `OAUTH2_ISSUER_URL` and +`CONSENT_URL` has been renamed to `OAUTH2_CONSENT_URL`. + +Additionally, flag `--dangerous-force-auto-logon` has been removed it has no effect any more. + +##### Access Control & `hydra connect` + +WHAT HAPPENED TO THIS COMMAND? TBD + +As access control has been removed, most commands (except `token user`, `token client`, `token revoke`, `token introspect`) +work without supplying any credentials at all. The listed exceptions support setting an OAuth 2.0 Client ID and Client Secret +using flags `--client-id` and `--client-secret` or environment variables `OAUTH2_CLIENT_ID` and `OAUTH2_CLIENT_SECRET`. + +All other commands, such as `hydra clients create`, still support scenarios where you would need an OAuth2 Access Token. +In those cases, you can supply the access token using flag `--access-token` or environment variable `OAUTH2_ACCESS_TOKEN`. + +#### `hydra token validate` + +This command has been renamed to `hydra token introspect` to properly reflect that you are performing OAuth 2.0 +Token Introspection. + +#### `hydra clients create` + +As OAuth 2.0 specifies that terminology `scope` does not have a plural `scopes`, we updated the places where the +incorrect `scopes` was used in order to provide a more consistent developer experience. + +This command renamed flag `--allowed-scopes` to `--scope`. + +#### `hydra migrate ladon` + +This command is a relict of an old version of ORY Hydra which is, according to our metrics, not being used any more. + +### sdk + + AcceptConsentRequest(challenge string, body swagger.AcceptConsentRequest) (*swagger.CompletedRequest, *swagger.APIResponse, error) + AcceptLoginRequest(challenge string, body swagger.AcceptLoginRequest) (*swagger.CompletedRequest, *swagger.APIResponse, error) + RejectConsentRequest(challenge string, body swagger.RejectRequest) (*swagger.CompletedRequest, *swagger.APIResponse, error) + RejectLoginRequest(challenge string, body swagger.RejectRequest) (*swagger.CompletedRequest, *swagger.APIResponse, error) + GetLoginRequest(challenge string) (*swagger.LoginRequest, *swagger.APIResponse, error) + GetConsentRequest(challenge string) (*swagger.ConsentRequest, *swagger.APIResponse, error) + + #### Access Control Policies and Warden moved to ORY Keto #### camelCase JSON is now under_score @@ -90,11 +144,6 @@ Minor breaking changes do not require any special upgrade paths, unless you expl Previously, we disabled the introspection of refresh tokens. This has now changed to comply with the OAuth 2.0 specification. To distinguish tokens, use the `token_type` in the introspection response. It can either be `access_token` or `refresh_token`. -#### FORCE_ROOT_CLIENT_CREDENTIALS - -The variable `FORCE_ROOT_CLIENT_CREDENTIALS` has caused some pain due to url-encoding conventions. It has been replaced -by `FORCE_ROOT_CLIENT_ID` and `FORCE_ROOT_CLIENT_SECRET` which do not need to be encoded. - #### jwk: Forces JWK to have a unique ID Previously, JSON Web Keys did not have to specify a unique id. JWKs diff --git a/client/manager_sql.go b/client/manager_sql.go index 8dc93da4940..78dd1d523bc 100644 --- a/client/manager_sql.go +++ b/client/manager_sql.go @@ -28,7 +28,7 @@ import ( "github.com/jmoiron/sqlx" "github.com/ory/fosite" - "github.com/ory/hydra/pkg" + "github.com/ory/go-convenience/stringsx" "github.com/ory/sqlcon" "github.com/pborman/uuid" "github.com/pkg/errors" @@ -125,16 +125,16 @@ func (d *sqlData) ToClient() *Client { ID: d.ID, Name: d.Name, Secret: d.Secret, - RedirectURIs: pkg.SplitNonEmpty(d.RedirectURIs, "|"), - GrantTypes: pkg.SplitNonEmpty(d.GrantTypes, "|"), - ResponseTypes: pkg.SplitNonEmpty(d.ResponseTypes, "|"), + RedirectURIs: stringsx.Splitx(d.RedirectURIs, "|"), + GrantTypes: stringsx.Splitx(d.GrantTypes, "|"), + ResponseTypes: stringsx.Splitx(d.ResponseTypes, "|"), Scope: d.Scope, Owner: d.Owner, PolicyURI: d.PolicyURI, TermsOfServiceURI: d.TermsOfServiceURI, ClientURI: d.ClientURI, LogoURI: d.LogoURI, - Contacts: pkg.SplitNonEmpty(d.Contacts, "|"), + Contacts: stringsx.Splitx(d.Contacts, "|"), Public: d.Public, } } diff --git a/cmd/cli/handler_migrate.go b/cmd/cli/handler_migrate.go index 6c08606432e..11443d17c13 100644 --- a/cmd/cli/handler_migrate.go +++ b/cmd/cli/handler_migrate.go @@ -30,6 +30,7 @@ import ( "github.com/jmoiron/sqlx" "github.com/ory/hydra/client" "github.com/ory/hydra/config" + "github.com/ory/hydra/consent" "github.com/ory/hydra/jwk" "github.com/ory/hydra/oauth2" "github.com/ory/hydra/pkg" @@ -103,7 +104,7 @@ func (h *MigrateHandler) runMigrateSQL(db *sqlx.DB) error { "client": &client.SQLManager{DB: db}, "oauth2": &oauth2.FositeSQLStore{DB: db}, "jwk": &jwk.SQLManager{DB: db}, - "consent": oauth2.NewConsentRequestSQLManager(db), + "consent": consent.NewSQLManager(db, nil), } { fmt.Printf("Applying `%s` SQL migrations...\n", k) if num, err := m.CreateSchemas(); err != nil { diff --git a/cmd/clients_create.go b/cmd/clients_create.go index 25478e1cf75..2761bae0b61 100644 --- a/cmd/clients_create.go +++ b/cmd/clients_create.go @@ -42,7 +42,7 @@ func init() { clientsCreateCmd.Flags().StringSliceP("callbacks", "c", []string{}, "REQUIRED list of allowed callback URLs") clientsCreateCmd.Flags().StringSliceP("grant-types", "g", []string{"authorization_code"}, "A list of allowed grant types") clientsCreateCmd.Flags().StringSliceP("response-types", "r", []string{"code"}, "A list of allowed response types") - clientsCreateCmd.Flags().StringSliceP("allowed-scopes", "a", []string{""}, "A list of allowed scopes") + clientsCreateCmd.Flags().StringSliceP("scope", "a", []string{""}, "The scope the client is allowed to request") clientsCreateCmd.Flags().Bool("is-public", false, "Use this flag to create a public client") clientsCreateCmd.Flags().String("secret", "", "Provide the client's secret") clientsCreateCmd.Flags().StringP("name", "n", "", "The client's name") diff --git a/cmd/host.go b/cmd/host.go index 9d95d11b39a..f3b248cda35 100644 --- a/cmd/host.go +++ b/cmd/host.go @@ -65,12 +65,6 @@ CORE CONTROLS a separate secret in production. Example: COOKIE_SECRET=fjah8uFhgjSiuf-AS -- FORCE_ROOT_CLIENT_CREDENTIALS: On first start up, Hydra generates a root client with random id and secret. Use - this environment variable in the form of "FORCE_ROOT_CLIENT_CREDENTIALS=id:secret" to set - the client id and secret yourself. Please www-url-encode the id - and the secret: "FORCE_ROOT_CLIENT_CREDENTIALS=urlencode(id):urlencode(secret)". - Example: FORCE_ROOT_CLIENT_CREDENTIALS=admin:h6hy92tK4dQcZ2EaFsGNRtqg - - PORT: The port hydra should listen on. Defaults to PORT=4444 @@ -99,12 +93,18 @@ CORE CONTROLS OAUTH2 CONTROLS =============== -- CONSENT_URL: The uri of the consent endpoint. - Example: CONSENT_URL=https://id.myapp.com/consent +- OAUTH2_ERROR_URL: A dedicated endpoint that shows critical errors in a user-friendly way. + Example: OAUTH2_ERROR_URL=https://id.myapp.com/error + +- OAUTH2_CONSENT_URL: The consent provider's URL. + Example: OAUTH2_CONSENT_URL=https://id.myapp.com/consent + +- OAUTH2_LOGIN_URL: The login provider's URL. + Example: OAUTH2_LOGIN_URL=https://id.myapp.com/login -- ISSUER: Issuer is the public URL of your Hydra installation. It is used for OAuth2 and OpenID Connect and must be +- OAUTH2_ISSUER_URL: Issuer is the public URL of your Hydra installation. It is used for OAuth2 and OpenID Connect and must be specified and using HTTPS protocol, unless --dangerous-force-http is set. - Example: ISSUER=https://hydra.myapp.com/ + Example: OAUTH2_ISSUER_URL=https://hydra.myapp.com/ - AUTH_CODE_LIFESPAN: Lifespan of OAuth2 authorize codes. Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h". Defaults to AUTH_CODE_LIFESPAN=10m diff --git a/cmd/root.go b/cmd/root.go index fb46e1720b1..fa7d69ba71d 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -107,8 +107,14 @@ func initConfig() { viper.BindEnv("CLIENT_ID") viper.SetDefault("CLIENT_ID", "") - viper.BindEnv("CONSENT_URL") - viper.SetDefault("CONSENT_URL", oauth2.DefaultConsentPath) + viper.BindEnv("OAUTH2_CONSENT_URL") + viper.SetDefault("OAUTH2_CONSENT_URL", oauth2.DefaultConsentPath) + + viper.BindEnv("OAUTH2_LOGIN_URL") + viper.SetDefault("OAUTH2_LOGIN_URL", oauth2.DefaultConsentPath) + + viper.BindEnv("OAUTH2_ERROR_URL") + viper.SetDefault("OAUTH2_ERROR_URL", oauth2.DefaultErrorPath) viper.BindEnv("DATABASE_PLUGIN") viper.SetDefault("DATABASE_PLUGIN", "") @@ -131,8 +137,8 @@ func initConfig() { viper.BindEnv("PORT") viper.SetDefault("PORT", 4444) - viper.BindEnv("ISSUER") - viper.SetDefault("ISSUER", "http://localhost:4444") + viper.BindEnv("OAUTH2_ISSUER_URL") + viper.SetDefault("OAUTH2_ISSUER_URL", "http://localhost:4444") viper.BindEnv("BCRYPT_COST") viper.SetDefault("BCRYPT_COST", 10) @@ -176,7 +182,7 @@ func initConfig() { fmt.Println("") } - iss := viper.Get("ISSUER") + iss := viper.Get("OAUTH2_ISSUER_URL") viper.Set("ISSUER", strings.TrimSuffix(iss.(string), "/")) if err := viper.Unmarshal(c); err != nil { diff --git a/cmd/root_test.go b/cmd/root_test.go index 5b061da7f10..52ac331067f 100644 --- a/cmd/root_test.go +++ b/cmd/root_test.go @@ -41,7 +41,7 @@ func TestExecute(t *testing.T) { os.Setenv("DATABASE_URL", "memory") os.Setenv("FORCE_ROOT_CLIENT_ID", "admin") os.Setenv("FORCE_ROOT_CLIENT_SECRET", "pw") - os.Setenv("ISSUER", "https://localhost:4444/") + os.Setenv("OAUTH2_ISSUER_URL", "https://localhost:4444/") copy(osArgs, os.Args) for _, c := range []struct { diff --git a/cmd/server/handler.go b/cmd/server/handler.go index 63950eef06a..e243f04124f 100644 --- a/cmd/server/handler.go +++ b/cmd/server/handler.go @@ -37,6 +37,7 @@ import ( "github.com/ory/herodot" "github.com/ory/hydra/client" "github.com/ory/hydra/config" + "github.com/ory/hydra/consent" "github.com/ory/hydra/jwk" "github.com/ory/hydra/oauth2" "github.com/ory/hydra/pkg" @@ -47,6 +48,8 @@ import ( "github.com/urfave/negroni" ) +var _ = &consent.Handler{} + func parseCorsOptions() cors.Options { allowCredentials, _ := strconv.ParseBool(viper.GetString("CORS_ALLOWED_CREDENTIALS")) debug, _ := strconv.ParseBool(viper.GetString("CORS_DEBUG")) @@ -120,12 +123,6 @@ func RunHost(c *config.Config) func(cmd *cobra.Command, args []string) { }, }) - if ok, _ := cmd.Flags().GetBool("dangerous-auto-logon"); ok { - logger.Warnln("Do not use flag --dangerous-auto-logon in production.") - err := c.Persist() - pkg.Must(err, "Could not write configuration file: %s", err) - } - err := graceful.Graceful(func() error { var err error logger.Infof("Setting up http server on %s", c.GetAddress()) @@ -149,7 +146,7 @@ type Handler struct { Clients *client.Handler Keys *jwk.Handler OAuth2 *oauth2.Handler - Consent *oauth2.ConsentSessionHandler + Consent *consent.Handler Config *config.Config H herodot.Writer } @@ -168,11 +165,9 @@ func (h *Handler) registerRoutes(router *httprouter.Router) { // Set up handlers h.Clients = newClientHandler(c, router, clientsManager) h.Keys = newJWKHandler(c, router) - h.Consent = newConsentHanlder(c, router) + h.Consent = newConsentHandler(c, router) h.OAuth2 = newOAuth2Handler(c, router, ctx.ConsentManager, oauth2Provider, idTokenKeyID) _ = newHealthHandler(c, router) - - h.createRootIfNewInstall(c) } func (h *Handler) rejectInsecureRequests(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) { diff --git a/cmd/server/handler_consent_factory.go b/cmd/server/handler_consent_factory.go index ff6260329fc..81aebf4155b 100644 --- a/cmd/server/handler_consent_factory.go +++ b/cmd/server/handler_consent_factory.go @@ -24,23 +24,23 @@ import ( "github.com/julienschmidt/httprouter" "github.com/ory/herodot" "github.com/ory/hydra/config" - "github.com/ory/hydra/oauth2" + "github.com/ory/hydra/consent" ) func injectConsentManager(c *config.Config) { var ctx = c.Context() - var manager oauth2.ConsentRequestManager + var manager consent.Manager switch con := ctx.Connection.(type) { case *config.MemoryConnection: - manager = oauth2.NewConsentRequestMemoryManager() + manager = consent.NewMemoryManager() break case *config.SQLConnection: - manager = oauth2.NewConsentRequestSQLManager(con.GetDatabase()) + panic("not implemented yet") break case *config.PluginConnection: var err error - if manager, err = con.NewConsentRequestManager(); err != nil { + if manager, err = con.NewConsentManager(); err != nil { c.GetLogger().Fatalf("Could not load client manager plugin %s", err) } break @@ -49,13 +49,13 @@ func injectConsentManager(c *config.Config) { } ctx.ConsentManager = manager - } -func newConsentHanlder(c *config.Config, router *httprouter.Router) *oauth2.ConsentSessionHandler { - h := &oauth2.ConsentSessionHandler{ - H: herodot.NewJSONWriter(c.GetLogger()), - ResourcePrefix: c.AccessControlResourcePrefix, +func newConsentHandler(c *config.Config, router *httprouter.Router) *consent.Handler { + var ctx = c.Context() + h := &consent.Handler{ + H: herodot.NewJSONWriter(c.GetLogger()), + M: ctx.ConsentManager, } h.SetRoutes(router) diff --git a/cmd/server/handler_oauth2_factory.go b/cmd/server/handler_oauth2_factory.go index 2103bf23832..9d9b3479f60 100644 --- a/cmd/server/handler_oauth2_factory.go +++ b/cmd/server/handler_oauth2_factory.go @@ -23,6 +23,7 @@ package server import ( "fmt" "net/url" + "time" "github.com/gorilla/sessions" "github.com/julienschmidt/httprouter" @@ -31,6 +32,7 @@ import ( "github.com/ory/herodot" "github.com/ory/hydra/client" "github.com/ory/hydra/config" + "github.com/ory/hydra/consent" "github.com/ory/hydra/jwk" "github.com/ory/hydra/oauth2" "github.com/ory/hydra/pkg" @@ -107,21 +109,29 @@ func newOAuth2Provider(c *config.Config) (fosite.OAuth2Provider, string) { ), publicKey.KeyID } -func newOAuth2Handler(c *config.Config, router *httprouter.Router, cm oauth2.ConsentRequestManager, o fosite.OAuth2Provider, idTokenKeyID string) *oauth2.Handler { - if c.ConsentURL == "" { - proto := "https" - if c.ForceHTTP { - proto = "http" - } - host := "localhost" - if c.BindHost != "" { - host = c.BindHost - } - c.ConsentURL = fmt.Sprintf("%s://%s:%d/oauth2/consent", proto, host, c.BindPort) +func setDefaultConsentURL(s string, c *config.Config, path string) string { + if s != "" { + return s + } + proto := "https" + if c.ForceHTTP { + proto = "http" } + host := "localhost" + if c.BindHost != "" { + host = c.BindHost + } + return fmt.Sprintf("%s://%s:%d/%s", proto, host, c.BindPort, path) +} + +//func newOAuth2Handler(c *config.Config, router *httprouter.Router, cm oauth2.ConsentRequestManager, o fosite.OAuth2Provider, idTokenKeyID string) *oauth2.Handler { +func newOAuth2Handler(c *config.Config, router *httprouter.Router, cm consent.Manager, o fosite.OAuth2Provider, idTokenKeyID string) *oauth2.Handler { + c.ConsentURL = setDefaultConsentURL(c.ConsentURL, c, "oauth2/fallbacks/consent") + c.LoginURL = setDefaultConsentURL(c.LoginURL, c, "oauth2/fallbacks/consent") + c.ErrorURL = setDefaultConsentURL(c.ErrorURL, c, "oauth2/fallbacks/error") - consentURL, err := url.Parse(c.ConsentURL) - pkg.Must(err, "Could not parse consent url %s.", c.ConsentURL) + errorURL, err := url.Parse(c.ErrorURL) + pkg.Must(err, "Could not parse error url %s.", errorURL) handler := &oauth2.Handler{ ScopesSupported: c.OpenIDDiscoveryScopesSupported, @@ -130,21 +140,33 @@ func newOAuth2Handler(c *config.Config, router *httprouter.Router, cm oauth2.Con ForcedHTTP: c.ForceHTTP, OAuth2: o, ScopeStrategy: c.GetScopeStrategy(), - Consent: &oauth2.DefaultConsentStrategy{ - Issuer: c.Issuer, - ConsentManager: c.Context().ConsentManager, - DefaultChallengeLifespan: c.GetChallengeTokenLifespan(), - DefaultIDTokenLifespan: c.GetIDTokenLifespan(), - KeyID: idTokenKeyID, + Consent: &consent.DefaultStrategy{ + RequestMaxAge: time.Minute * 15, + AuthenticationURL: c.LoginURL, + ConsentURL: c.ConsentURL, + IssuerURL: c.Issuer, + OAuth2AuthURL: "/oauth2/auth", + M: cm, + CookieStore: sessions.NewCookieStore(c.GetCookieSecret()), + ScopeStrategy: c.GetScopeStrategy(), + RunsHTTPS: !c.ForceHTTP, }, + //Consent: &oauth2.DefaultConsentStrategy{ + // Issuer: c.Issuer, + // ConsentManager: c.Context().ConsentManager, + // DefaultChallengeLifespan: c.GetChallengeTokenLifespan(), + // DefaultIDTokenLifespan: c.GetIDTokenLifespan(), + // KeyID: idTokenKeyID, + //}, Storage: c.Context().FositeStore, - ConsentURL: *consentURL, + ErrorURL: *errorURL, H: herodot.NewJSONWriter(c.GetLogger()), AccessTokenLifespan: c.GetAccessTokenLifespan(), CookieStore: sessions.NewCookieStore(c.GetCookieSecret()), Issuer: c.Issuer, L: c.GetLogger(), - ResourcePrefix: c.AccessControlResourcePrefix, + IDTokenPublicKeyID: idTokenKeyID, + IDTokenLifespan: c.GetIDTokenLifespan(), } handler.SetRoutes(router) diff --git a/cmd/server/helper_client.go b/cmd/server/helper_client.go index 6837979c2ca..bdb68eae1a9 100644 --- a/cmd/server/helper_client.go +++ b/cmd/server/helper_client.go @@ -19,69 +19,3 @@ */ package server - -import ( - "os" - - "github.com/ory/hydra/client" - "github.com/ory/hydra/config" - "github.com/ory/hydra/pkg" -) - -func (h *Handler) createRootIfNewInstall(c *config.Config) { - clients, err := h.Clients.Manager.GetClients(100, 0) - pkg.Must(err, "Could not fetch client list: %s", err) - if len(clients) != 0 { - return - } - - rs, err := pkg.GenerateSecret(16) - pkg.Must(err, "Could notgenerate secret because %s", err) - var providedSecrets bool - secret := string(rs) - - id := "" - forceRootClientID := os.Getenv("FORCE_ROOT_CLIENT_ID") - forceRootClientSecret := os.Getenv("FORCE_ROOT_CLIENT_SECRET") - if forceRootClientID != "" && forceRootClientSecret != "" { - id = forceRootClientID - secret = forceRootClientSecret - providedSecrets = true - } - - c.GetLogger().Warn("No clients were found. Creating a temporary root client...") - root := &client.Client{ - ID: id, - Name: "This temporary client is generated by hydra and is granted all of hydra's administrative privileges. It must be removed when everything is set up.", - ResponseTypes: []string{"id_token", "code", "token"}, - GrantTypes: []string{"implicit", "refresh_token", "authorization_code", "password", "client_credentials"}, - Scope: "hydra.* openid offline hydra", - RedirectURIs: []string{"http://localhost:4445/callback"}, - Secret: secret, - } - - err = h.Clients.Manager.CreateClient(root) - pkg.Must(err, "Could not create temporary root because %s", err) - - c.ClientID = root.ID - c.ClientSecret = string(secret) - - c.GetLogger().Infoln("Temporary root client created.") - if !providedSecrets { - c.GetLogger().Infof("client_id: %s", root.GetID()) - c.GetLogger().Infof("client_secret: %s", string(secret)) - c.GetLogger().Warn("WARNING: YOU MUST delete this client once in production, as credentials may have been leaked in your logfiles.") - } -} - -func prefixResource(prefix, resource string) string { - if prefix == "" { - prefix = "rn:hydra" - } - - if prefix[len(prefix)-1] == ':' { - prefix = prefix[:len(prefix)-1] - } - - return prefix + ":" + resource -} diff --git a/cmd/token_client.go b/cmd/token_client.go index 682a3de08f6..65e92041c33 100644 --- a/cmd/token_client.go +++ b/cmd/token_client.go @@ -25,7 +25,9 @@ import ( "crypto/tls" "fmt" "net/http" + "net/url" + "github.com/ory/go-convenience/urlx" "github.com/ory/hydra/pkg" "github.com/spf13/cobra" "golang.org/x/oauth2" @@ -73,10 +75,13 @@ var tokenClientCmd = &cobra.Command{ scopes, _ := cmd.Flags().GetStringSlice("scopes") + cu, err := url.Parse(c.ClusterURL) + pkg.Must(err, `Unable to parse cluster url ("%s"): %s`, c.ClusterURL, err) + oauthConfig := clientcredentials.Config{ ClientID: c.ClientID, ClientSecret: c.ClientSecret, - TokenURL: pkg.JoinURLStrings(c.ClusterURL, "/oauth2/token"), + TokenURL: urlx.AppendPaths(cu, "/oauth2/token").String(), Scopes: scopes, } diff --git a/cmd/token_user.go b/cmd/token_user.go index 4291065f6d2..f2f78ff8240 100644 --- a/cmd/token_user.go +++ b/cmd/token_user.go @@ -25,9 +25,11 @@ import ( "crypto/tls" "fmt" "net/http" + "net/url" "time" "github.com/julienschmidt/httprouter" + "github.com/ory/go-convenience/urlx" "github.com/ory/hydra/pkg" "github.com/ory/hydra/rand/sequence" "github.com/spf13/cobra" @@ -48,7 +50,7 @@ var tokenUserCmd = &cobra.Command{ }}) } - scopes, _ := cmd.Flags().GetStringSlice("scopes") + scopes, _ := cmd.Flags().GetStringSlice("scope") clientId, _ := cmd.Flags().GetString("id") clientSecret, _ := cmd.Flags().GetString("secret") redirectUrl, _ := cmd.Flags().GetString("redirect") @@ -62,10 +64,14 @@ var tokenUserCmd = &cobra.Command{ clientSecret = c.ClientSecret } if backend == "" { - backend = pkg.JoinURLStrings(c.ClusterURL, "/oauth2/token") + bu, err := url.Parse(c.ClusterURL) + pkg.Must(err, `Unable to parse cluster url ("%s"): %s`, c.ClusterURL, err) + backend = urlx.AppendPaths(bu, "/oauth2/token").String() } if frontend == "" { - frontend = pkg.JoinURLStrings(c.ClusterURL, "/oauth2/auth") + fu, err := url.Parse(c.ClusterURL) + pkg.Must(err, `Unable to parse cluster url ("%s"): %s`, c.ClusterURL, err) + frontend = urlx.AppendPaths(fu, "/oauth2/auth").String() } conf := oauth2.Config{ @@ -152,7 +158,7 @@ var tokenUserCmd = &cobra.Command{ func init() { tokenCmd.AddCommand(tokenUserCmd) tokenUserCmd.Flags().Bool("no-open", false, "Do not open the browser window automatically") - tokenUserCmd.Flags().StringSlice("scopes", []string{"hydra", "offline", "openid"}, "Force scopes") + tokenUserCmd.Flags().StringSlice("scope", []string{"hydra", "offline", "openid"}, "Force scopes") tokenUserCmd.Flags().String("id", "", "Force a client id, defaults to value from config file") tokenUserCmd.Flags().String("secret", "", "Force a client secret, defaults to value from config file") tokenUserCmd.Flags().String("redirect", "http://localhost:4445/callback", "Force a redirect url") diff --git a/config/backend_plugin.go b/config/backend_plugin.go index 7737f70bd05..742dfccace5 100644 --- a/config/backend_plugin.go +++ b/config/backend_plugin.go @@ -26,8 +26,8 @@ import ( "github.com/jmoiron/sqlx" "github.com/ory/fosite" "github.com/ory/hydra/client" + "github.com/ory/hydra/consent" "github.com/ory/hydra/jwk" - "github.com/ory/hydra/oauth2" "github.com/ory/hydra/pkg" "github.com/pkg/errors" "github.com/sirupsen/logrus" @@ -130,15 +130,15 @@ func (c *PluginConnection) NewOAuth2Manager(clientManager client.Manager) (pkg.F } } -func (c *PluginConnection) NewConsentRequestManager() (oauth2.ConsentRequestManager, error) { +func (c *PluginConnection) NewConsentManager() (consent.Manager, error) { if err := c.load(); err != nil { return nil, errors.WithStack(err) } - if l, err := c.plugin.Lookup("NewConsentRequestManager"); err != nil { - return nil, errors.Wrap(err, "Unable to look up `NewConsentRequestManager`") - } else if m, ok := l.(func(*sqlx.DB) oauth2.ConsentRequestManager); !ok { - return nil, errors.Errorf("Unable to type assert `NewConsentRequestManager`, got %v", l) + if l, err := c.plugin.Lookup("NewConsentManager"); err != nil { + return nil, errors.Wrap(err, "Unable to look up `NewConsentManager`") + } else if m, ok := l.(func(*sqlx.DB) consent.Manager); !ok { + return nil, errors.Errorf("Unable to type assert `NewConsentManager`, got %v", l) } else { return m(c.db), nil } diff --git a/config/config.go b/config/config.go index d6e34d72d35..0f2e21aff86 100644 --- a/config/config.go +++ b/config/config.go @@ -36,6 +36,7 @@ import ( "github.com/ory/fosite" foauth2 "github.com/ory/fosite/handler/oauth2" "github.com/ory/fosite/token/hmac" + "github.com/ory/go-convenience/urlx" "github.com/ory/hydra/health" "github.com/ory/hydra/metrics" "github.com/ory/hydra/pkg" @@ -58,11 +59,13 @@ type Config struct { // These are used by the host command BindPort int `mapstructure:"PORT" yaml:"-"` BindHost string `mapstructure:"HOST" yaml:"-"` - Issuer string `mapstructure:"ISSUER" yaml:"-"` + Issuer string `mapstructure:"OAUTH2_ISSUER_URL" yaml:"-"` SystemSecret string `mapstructure:"SYSTEM_SECRET" yaml:"-"` DatabaseURL string `mapstructure:"DATABASE_URL" yaml:"-"` DatabasePlugin string `mapstructure:"DATABASE_PLUGIN" yaml:"-"` - ConsentURL string `mapstructure:"CONSENT_URL" yaml:"-"` + ConsentURL string `mapstructure:"OAUTH2_CONSENT_URL" yaml:"-"` + LoginURL string `mapstructure:"OAUTH2_LOGIN_URL" yaml:"-"` + ErrorURL string `mapstructure:"OAUTH2_ERROR_URL" yaml:"-"` AllowTLSTermination string `mapstructure:"HTTPS_ALLOW_TERMINATION_FROM" yaml:"-"` BCryptWorkFactor int `mapstructure:"BCRYPT_COST" yaml:"-"` AccessTokenLifespan string `mapstructure:"ACCESS_TOKEN_LIFESPAN" yaml:"-"` @@ -281,7 +284,7 @@ func (c *Config) Resolve(join ...string) *url.URL { return c.cluster } - return pkg.JoinURL(c.cluster, join...) + return urlx.AppendPaths(c.cluster, join...) } type transporter struct { @@ -302,10 +305,13 @@ func (c *Config) OAuth2Client(cmd *cobra.Command) *http.Client { return c.oauth2Client } + cu, err := url.Parse(c.ClusterURL) + pkg.Must(err, `Unable to parse cluster url ("%s"): %s`, c.ClusterURL, err) + oauthConfig := clientcredentials.Config{ ClientID: c.ClientID, ClientSecret: c.ClientSecret, - TokenURL: pkg.JoinURLStrings(c.ClusterURL, "/oauth2/token"), + TokenURL: urlx.AppendPaths(cu, "/oauth2/token").String(), Scopes: []string{"hydra", "hydra.*"}, } diff --git a/config/context.go b/config/context.go index b4342cfcac5..20eba0d9090 100644 --- a/config/context.go +++ b/config/context.go @@ -23,8 +23,8 @@ package config import ( "github.com/ory/fosite" "github.com/ory/fosite/handler/oauth2" + "github.com/ory/hydra/consent" "github.com/ory/hydra/jwk" - hoa2 "github.com/ory/hydra/oauth2" "github.com/ory/hydra/pkg" ) @@ -35,5 +35,5 @@ type Context struct { FositeStrategy oauth2.CoreStrategy FositeStore pkg.FositeStorer KeyManager jwk.Manager - ConsentManager hoa2.ConsentRequestManager + ConsentManager consent.Manager } diff --git a/consent/doc.go b/consent/doc.go new file mode 100644 index 00000000000..af7df1a2f45 --- /dev/null +++ b/consent/doc.go @@ -0,0 +1,58 @@ +/* + * Copyright © 2015-2018 Aeneas Rekkas + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * @author Aeneas Rekkas + * @Copyright 2017-2018 Aeneas Rekkas + * @license Apache-2.0 + */ + +package consent + +// swagger:parameters getLoginRequest getConsentRequest +type swaggerGetRequestByChallenge struct { + // in: path + // required: true + Challenge string `json:"challenge"` +} + +// swagger:parameters acceptLoginRequest +type swaggerAcceptAuthenticationRequest struct { + // in: path + // required: true + Challenge string `json:"challenge"` + + // in: body + Body HandledAuthenticationRequest +} + +// swagger:parameters acceptConsentRequest +type swaggerAcceptConsentRequest struct { + // in: path + // required: true + Challenge string `json:"challenge"` + + // in: body + Body HandledConsentRequest +} + +// swagger:parameters rejectLoginRequest rejectConsentRequest +type swaggerRejectRequest struct { + // in: path + // required: true + Challenge string `json:"challenge"` + + // in: body + Body RequestDeniedError +} diff --git a/consent/handler.go b/consent/handler.go new file mode 100644 index 00000000000..41d9785d075 --- /dev/null +++ b/consent/handler.go @@ -0,0 +1,379 @@ +/* + * Copyright © 2015-2018 Aeneas Rekkas + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * @author Aeneas Rekkas + * @Copyright 2017-2018 Aeneas Rekkas + * @license Apache-2.0 + */ + +package consent + +import ( + "encoding/json" + "net/http" + "net/url" + "time" + + "github.com/julienschmidt/httprouter" + "github.com/ory/go-convenience/urlx" + "github.com/ory/herodot" + "github.com/pkg/errors" +) + +type Handler struct { + H herodot.Writer + M Manager +} + +func NewHandler( + h herodot.Writer, + m Manager, +) *Handler { + return &Handler{ + H: h, + M: m, + } +} + +func (h *Handler) SetRoutes(r *httprouter.Router) { + r.GET("/oauth2/auth/requests/login/:challenge", h.GetLoginRequest) + r.PUT("/oauth2/auth/requests/login/:challenge/accept", h.AcceptLoginRequest) + r.PUT("/oauth2/auth/requests/login/:challenge/reject", h.RejectLoginRequest) + + r.GET("/oauth2/auth/requests/consent/:challenge", h.GetConsentRequest) + r.PUT("/oauth2/auth/requests/consent/:challenge/accept", h.AcceptConsentRequest) + r.PUT("/oauth2/auth/requests/consent/:challenge/reject", h.RejectConsentRequest) +} + +// swagger:route GET /oauth2/auth/requests/login/{challenge} oAuth2 getLoginRequest +// +// Get an login request +// +// When an authorization code, hybrid, or implicit OAuth 2.0 Flow is initiated, ORY Hydra asks the login provider +// (sometimes called "identity provider") to authenticate the user and then tell ORY Hydra now about it. The login +// provider is an web-app you write and host, and it must be able to authenticate ("show the user a login screen") +// a user (in OAuth2 the proper name for user is "resource owner"). +// +// The authentication challenge is appended to the login provider URL to which the user's user-agent (browser) is redirected to. The login +// provider uses that challenge to fetch information on the OAuth2 request and then accept or reject the requested authentication process. +// +// +// Consumes: +// - application/json +// +// Produces: +// - application/json +// +// Schemes: http, https +// +// Responses: +// 200: loginRequest +// 401: genericError +// 500: genericError +func (h *Handler) GetLoginRequest(w http.ResponseWriter, r *http.Request, ps httprouter.Params) { + request, err := h.M.GetAuthenticationRequest(ps.ByName("challenge")) + if err != nil { + h.H.WriteError(w, r, err) + return + } + + h.H.Write(w, r, request) +} + +// swagger:route PUT /oauth2/auth/requests/login/{challenge}/accept oAuth2 acceptLoginRequest +// +// Accept an login request +// +// When an authorization code, hybrid, or implicit OAuth 2.0 Flow is initiated, ORY Hydra asks the login provider +// (sometimes called "identity provider") to authenticate the user and then tell ORY Hydra now about it. The login +// provider is an web-app you write and host, and it must be able to authenticate ("show the user a login screen") +// a user (in OAuth2 the proper name for user is "resource owner"). +// +// The authentication challenge is appended to the login provider URL to which the user's user-agent (browser) is redirected to. The login +// provider uses that challenge to fetch information on the OAuth2 request and then accept or reject the requested authentication process. +// +// This endpoint tells ORY Hydra that the user has successfully authenticated and includes additional information such as +// the user's ID and if ORY Hydra should remember the user's user agent for future authentication attempts by setting +// a cookie. +// +// The response contains a redirect URL which the login provider should redirect the user-agent to. +// +// Consumes: +// - application/json +// +// Produces: +// - application/json +// +// Schemes: http, https +// +// Responses: +// 200: completedRequest +// 401: genericError +// 500: genericError +func (h *Handler) AcceptLoginRequest(w http.ResponseWriter, r *http.Request, ps httprouter.Params) { + var p HandledAuthenticationRequest + d := json.NewDecoder(r.Body) + d.DisallowUnknownFields() + if err := d.Decode(&p); err != nil { + h.H.WriteErrorCode(w, r, http.StatusBadRequest, errors.WithStack(err)) + return + } + + p.Challenge = ps.ByName("challenge") + p.RequestedAt = time.Now().UTC() + + if ar, err := h.M.GetAuthenticationRequest(ps.ByName("challenge")); err != nil { + h.H.WriteError(w, r, err) + return + } else if ar.Subject != "" && p.Subject != ar.Subject { + h.H.WriteErrorCode(w, r, http.StatusBadRequest, errors.New("Subject from payload does not match subject from previous authentication")) + return + } + + request, err := h.M.HandleAuthenticationRequest(ps.ByName("challenge"), &p) + if err != nil { + h.H.WriteError(w, r, errors.WithStack(err)) + return + } + + ru, err := url.Parse(request.RequestURL) + if err != nil { + h.H.WriteError(w, r, err) + return + } + + h.H.Write(w, r, &RequestHandlerResponse{ + RedirectTo: urlx.SetQuery(ru, url.Values{"login_verifier": {request.Verifier}}).String(), + }) +} + +// swagger:route PUT /oauth2/auth/requests/login/{challenge}/reject oAuth2 rejectLoginRequest +// +// Reject an logout request +// +// When an authorization code, hybrid, or implicit OAuth 2.0 Flow is initiated, ORY Hydra asks the login provider +// (sometimes called "identity provider") to authenticate the user and then tell ORY Hydra now about it. The login +// provider is an web-app you write and host, and it must be able to authenticate ("show the user a login screen") +// a user (in OAuth2 the proper name for user is "resource owner"). +// +// The authentication challenge is appended to the login provider URL to which the user's user-agent (browser) is redirected to. The login +// provider uses that challenge to fetch information on the OAuth2 request and then accept or reject the requested authentication process. +// +// This endpoint tells ORY Hydra that the user has not authenticated and includes a reason why the authentication +// was be denied. +// +// The response contains a redirect URL which the login provider should redirect the user-agent to. +// +// Consumes: +// - application/json +// +// Produces: +// - application/json +// +// Schemes: http, https +// +// Responses: +// 200: completedRequest +// 401: genericError +// 500: genericError +func (h *Handler) RejectLoginRequest(w http.ResponseWriter, r *http.Request, ps httprouter.Params) { + var p RequestDeniedError + d := json.NewDecoder(r.Body) + d.DisallowUnknownFields() + if err := d.Decode(&p); err != nil { + h.H.WriteErrorCode(w, r, http.StatusBadRequest, errors.WithStack(err)) + return + } + + request, err := h.M.HandleAuthenticationRequest(ps.ByName("challenge"), &HandledAuthenticationRequest{ + Error: &p, + Challenge: ps.ByName("challenge"), + RequestedAt: time.Now().UTC(), + }) + if err != nil { + h.H.WriteError(w, r, errors.WithStack(err)) + return + } + + ru, err := url.Parse(request.RequestURL) + if err != nil { + h.H.WriteError(w, r, err) + return + } + + h.H.Write(w, r, &RequestHandlerResponse{ + RedirectTo: urlx.SetQuery(ru, url.Values{"login_verifier": {request.Verifier}}).String(), + }) +} + +// swagger:route GET /oauth2/auth/requests/consent/{challenge} oAuth2 getConsentRequest +// +// Get consent request information +// +// When an authorization code, hybrid, or implicit OAuth 2.0 Flow is initiated, ORY Hydra asks the login provider +// to authenticate the user and then tell ORY Hydra now about it. If the user authenticated, he/she must now be asked if +// the OAuth 2.0 Client which initiated the flow should be allowed to access the resources on the user's behalf. +// +// The consent provider which handles this request and is a web app implemented and hosted by you. It shows a user interface which asks the user to +// grant or deny the client access to the requested scope ("Application my-dropbox-app wants write access to all your private files"). +// +// The consent challenge is appended to the consent provider's URL to which the user's user-agent (browser) is redirected to. The consent +// provider uses that challenge to fetch information on the OAuth2 request and then tells ORY Hydra if the user accepted +// or rejected the request. +// +// Consumes: +// - application/json +// +// Produces: +// - application/json +// +// Schemes: http, https +// +// Responses: +// 200: consentRequest +// 401: genericError +// 500: genericError +func (h *Handler) GetConsentRequest(w http.ResponseWriter, r *http.Request, ps httprouter.Params) { + request, err := h.M.GetConsentRequest(ps.ByName("challenge")) + if err != nil { + h.H.WriteError(w, r, err) + return + } + + h.H.Write(w, r, request) +} + +// swagger:route PUT /oauth2/auth/requests/consent/{challenge}/accept oAuth2 acceptConsentRequest +// +// Accept an consent request +// +// When an authorization code, hybrid, or implicit OAuth 2.0 Flow is initiated, ORY Hydra asks the login provider +// to authenticate the user and then tell ORY Hydra now about it. If the user authenticated, he/she must now be asked if +// the OAuth 2.0 Client which initiated the flow should be allowed to access the resources on the user's behalf. +// +// The consent provider which handles this request and is a web app implemented and hosted by you. It shows a user interface which asks the user to +// grant or deny the client access to the requested scope ("Application my-dropbox-app wants write access to all your private files"). +// +// The consent challenge is appended to the consent provider's URL to which the user's user-agent (browser) is redirected to. The consent +// provider uses that challenge to fetch information on the OAuth2 request and then tells ORY Hydra if the user accepted +// or rejected the request. +// +// This endpoint tells ORY Hydra that the user has authorized the OAuth 2.0 client to access resources on his/her behalf. +// The consent provider includes additional information, such as session data for access and ID tokens, and if the +// consent request should be used as basis for future requests. +// +// The response contains a redirect URL which the consent provider should redirect the user-agent to. +// +// Consumes: +// - application/json +// +// Produces: +// - application/json +// +// Schemes: http, https +// +// Responses: +// 200: completedRequest +// 401: genericError +// 500: genericError +func (h *Handler) AcceptConsentRequest(w http.ResponseWriter, r *http.Request, ps httprouter.Params) { + var p HandledConsentRequest + d := json.NewDecoder(r.Body) + d.DisallowUnknownFields() + if err := d.Decode(&p); err != nil { + h.H.WriteErrorCode(w, r, http.StatusBadRequest, errors.WithStack(err)) + return + } + + p.Challenge = ps.ByName("challenge") + p.RequestedAt = time.Now().UTC() + hr, err := h.M.HandleConsentRequest(ps.ByName("challenge"), &p) + if err != nil { + h.H.WriteError(w, r, errors.WithStack(err)) + return + } + + ru, err := url.Parse(hr.RequestURL) + if err != nil { + h.H.WriteError(w, r, err) + return + } + + h.H.Write(w, r, &RequestHandlerResponse{ + RedirectTo: urlx.SetQuery(ru, url.Values{"consent_verifier": {hr.Verifier}}).String(), + }) +} + +// swagger:route PUT /oauth2/auth/requests/consent/{challenge}/reject oAuth2 rejectConsentRequest +// +// Reject an consent request +// +// When an authorization code, hybrid, or implicit OAuth 2.0 Flow is initiated, ORY Hydra asks the login provider +// to authenticate the user and then tell ORY Hydra now about it. If the user authenticated, he/she must now be asked if +// the OAuth 2.0 Client which initiated the flow should be allowed to access the resources on the user's behalf. +// +// The consent provider which handles this request and is a web app implemented and hosted by you. It shows a user interface which asks the user to +// grant or deny the client access to the requested scope ("Application my-dropbox-app wants write access to all your private files"). +// +// The consent challenge is appended to the consent provider's URL to which the user's user-agent (browser) is redirected to. The consent +// provider uses that challenge to fetch information on the OAuth2 request and then tells ORY Hydra if the user accepted +// or rejected the request. +// +// This endpoint tells ORY Hydra that the user has not authorized the OAuth 2.0 client to access resources on his/her behalf. +// The consent provider must include a reason why the consent was not granted. +// +// The response contains a redirect URL which the consent provider should redirect the user-agent to. +// +// Consumes: +// - application/json +// +// Produces: +// - application/json +// +// Schemes: http, https +// +// Responses: +// 200: completedRequest +// 401: genericError +// 500: genericError +func (h *Handler) RejectConsentRequest(w http.ResponseWriter, r *http.Request, ps httprouter.Params) { + var p RequestDeniedError + d := json.NewDecoder(r.Body) + d.DisallowUnknownFields() + if err := d.Decode(&p); err != nil { + h.H.WriteErrorCode(w, r, http.StatusBadRequest, errors.WithStack(err)) + return + } + + request, err := h.M.HandleConsentRequest(ps.ByName("challenge"), &HandledConsentRequest{ + Error: &p, + Challenge: ps.ByName("challenge"), + RequestedAt: time.Now().UTC(), + }) + if err != nil { + h.H.WriteError(w, r, errors.WithStack(err)) + return + } + + ru, err := url.Parse(request.RequestURL) + if err != nil { + h.H.WriteError(w, r, err) + return + } + + h.H.Write(w, r, &RequestHandlerResponse{ + RedirectTo: urlx.SetQuery(ru, url.Values{"consent_verifier": {request.Verifier}}).String(), + }) +} diff --git a/consent/helper.go b/consent/helper.go new file mode 100644 index 00000000000..45b856090c2 --- /dev/null +++ b/consent/helper.go @@ -0,0 +1,84 @@ +/* + * Copyright © 2015-2018 Aeneas Rekkas + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * @author Aeneas Rekkas + * @Copyright 2017-2018 Aeneas Rekkas + * @license Apache-2.0 + */ + +package consent + +import ( + "net/http" + + "github.com/gorilla/sessions" + "github.com/ory/fosite" + "github.com/ory/go-convenience/mapx" + "github.com/ory/hydra/client" + "github.com/pkg/errors" +) + +func sanitizeClient(ar fosite.AuthorizeRequester) *client.Client { + c := new(client.Client) + // Remove the hashed secret here + *c = *ar.GetClient().(*client.Client) + c.Secret = "" + return c +} + +func matchScopes(scopeStrategy fosite.ScopeStrategy, previousConsent []HandledConsentRequest, requestedScope []string) *HandledConsentRequest { + for _, cs := range previousConsent { + var found = true + for _, scope := range requestedScope { + if !scopeStrategy(cs.GrantedScope, scope) { + found = false + break + } + } + + if found { + return &cs + } + } + + return nil +} + +func createCsrfSession(w http.ResponseWriter, r *http.Request, store sessions.Store, name, csrf string, secure bool) error { + // Errors can be ignored here, because we always get a session session back. Error typically means that the + // session doesn't exist yet. + session, _ := store.Get(r, name) + session.Values["csrf"] = csrf + session.Options.HttpOnly = true + session.Options.Secure = secure + + if err := session.Save(r, w); err != nil { + return errors.WithStack(err) + } + + return nil +} + +func validateCsrfSession(r *http.Request, store sessions.Store, name, expectedCSRF string) error { + if cookie, err := store.Get(r, name); err != nil { + return errors.WithStack(fosite.ErrRequestForbidden.WithDebug("CSRF session cookie could not be decoded")) + } else if csrf, err := mapx.GetString(cookie.Values, "csrf"); err != nil { + return errors.WithStack(fosite.ErrRequestForbidden.WithDebug("No CSRF value available in the session cookie")) + } else if csrf != expectedCSRF { + return errors.WithStack(fosite.ErrRequestForbidden.WithDebug("The CSRF value from the token does not match the CSRF value from the data store")) + } + + return nil +} diff --git a/consent/helper_test.go b/consent/helper_test.go new file mode 100644 index 00000000000..b8a387a81dc --- /dev/null +++ b/consent/helper_test.go @@ -0,0 +1,96 @@ +/* + * Copyright © 2015-2018 Aeneas Rekkas + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * @author Aeneas Rekkas + * @Copyright 2017-2018 Aeneas Rekkas + * @license Apache-2.0 + */ + +package consent + +import ( + "fmt" + "testing" + + "github.com/ory/fosite" + "github.com/ory/hydra/client" + "github.com/stretchr/testify/assert" +) + +func TestSanitizeClient(t *testing.T) { + c := &client.Client{ + Secret: "some-secret", + } + ar := &fosite.AuthorizeRequest{ + Request: fosite.Request{ + Client: c, + }, + } + got := sanitizeClient(ar) + assert.Empty(t, got.Secret) + assert.NotEmpty(t, c.Secret) +} + +func TestMatchScopes(t *testing.T) { + for k, tc := range []struct { + granted []HandledConsentRequest + requested []string + expectChallenge string + }{ + { + granted: []HandledConsentRequest{{Challenge: "1", GrantedScope: []string{"foo", "bar"}}}, + requested: []string{"foo", "bar"}, + expectChallenge: "1", + }, + { + granted: []HandledConsentRequest{{Challenge: "1", GrantedScope: []string{"foo", "bar"}}}, + requested: []string{"foo", "bar", "baz"}, + expectChallenge: "", + }, + { + granted: []HandledConsentRequest{ + {Challenge: "1", GrantedScope: []string{"foo", "bar"}}, + {Challenge: "2", GrantedScope: []string{"foo", "bar"}}, + }, + requested: []string{"foo", "bar"}, + expectChallenge: "1", + }, + { + granted: []HandledConsentRequest{ + {Challenge: "1", GrantedScope: []string{"foo", "bar"}}, + {Challenge: "2", GrantedScope: []string{"foo", "bar", "baz"}}, + }, + requested: []string{"foo", "bar", "baz"}, + expectChallenge: "2", + }, + { + granted: []HandledConsentRequest{ + {Challenge: "1", GrantedScope: []string{"foo", "bar"}}, + {Challenge: "2", GrantedScope: []string{"foo", "bar", "baz"}}, + }, + requested: []string{"zab"}, + expectChallenge: "", + }, + } { + t.Run(fmt.Sprintf("case=%d", k), func(t *testing.T) { + got := matchScopes(fosite.ExactScopeStrategy, tc.granted, tc.requested) + if tc.expectChallenge == "" { + assert.Nil(t, got) + return + } + assert.Equal(t, tc.expectChallenge, got.Challenge) + }) + } +} diff --git a/consent/manager.go b/consent/manager.go new file mode 100644 index 00000000000..72293538336 --- /dev/null +++ b/consent/manager.go @@ -0,0 +1,40 @@ +/* + * Copyright © 2015-2018 Aeneas Rekkas + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * @author Aeneas Rekkas + * @Copyright 2017-2018 Aeneas Rekkas + * @license Apache-2.0 + */ + +package consent + +type Manager interface { + CreateConsentRequest(*ConsentRequest) error + GetConsentRequest(challenge string) (*ConsentRequest, error) + HandleConsentRequest(challenge string, r *HandledConsentRequest) (*ConsentRequest, error) + + VerifyAndInvalidateConsentRequest(verifier string) (*HandledConsentRequest, error) + FindPreviouslyGrantedConsentRequests(client string, user string) ([]HandledConsentRequest, error) + + // Cookie management + GetAuthenticationSession(id string) (*AuthenticationSession, error) + CreateAuthenticationSession(*AuthenticationSession) error + DeleteAuthenticationSession(id string) error + + CreateAuthenticationRequest(*AuthenticationRequest) error + GetAuthenticationRequest(challenge string) (*AuthenticationRequest, error) + HandleAuthenticationRequest(challenge string, r *HandledAuthenticationRequest) (*AuthenticationRequest, error) + VerifyAndInvalidateAuthenticationRequest(verifier string) (*HandledAuthenticationRequest, error) +} diff --git a/consent/manager_memory.go b/consent/manager_memory.go new file mode 100644 index 00000000000..3cbc88d5e29 --- /dev/null +++ b/consent/manager_memory.go @@ -0,0 +1,186 @@ +/* + * Copyright © 2015-2018 Aeneas Rekkas + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * @author Aeneas Rekkas + * @Copyright 2017-2018 Aeneas Rekkas + * @license Apache-2.0 + */ + +package consent + +import ( + "time" + + "github.com/ory/fosite" + "github.com/ory/hydra/pkg" + "github.com/pkg/errors" +) + +type MemoryManager struct { + consentRequests map[string]ConsentRequest + handledConsentRequests map[string]HandledConsentRequest + authRequests map[string]AuthenticationRequest + handledAuthRequests map[string]HandledAuthenticationRequest + authSessions map[string]AuthenticationSession +} + +func NewMemoryManager() *MemoryManager { + return &MemoryManager{ + consentRequests: map[string]ConsentRequest{}, + handledConsentRequests: map[string]HandledConsentRequest{}, + authRequests: map[string]AuthenticationRequest{}, + handledAuthRequests: map[string]HandledAuthenticationRequest{}, + authSessions: map[string]AuthenticationSession{}, + } +} + +func (m *MemoryManager) CreateConsentRequest(c *ConsentRequest) error { + m.consentRequests[c.Challenge] = *c + return nil +} + +func (m *MemoryManager) GetConsentRequest(challenge string) (*ConsentRequest, error) { + if c, ok := m.consentRequests[challenge]; ok { + return &c, nil + } + return nil, errors.WithStack(pkg.ErrNotFound) +} + +func (m *MemoryManager) HandleConsentRequest(challenge string, r *HandledConsentRequest) (*ConsentRequest, error) { + m.handledConsentRequests[r.Challenge] = *r + return m.GetConsentRequest(challenge) +} + +func (m *MemoryManager) VerifyAndInvalidateConsentRequest(verifier string) (*HandledConsentRequest, error) { + for _, c := range m.consentRequests { + if c.Verifier == verifier { + for _, h := range m.handledConsentRequests { + if h.Challenge == c.Challenge { + if h.WasUsed { + return nil, errors.WithStack(fosite.ErrInvalidRequest.WithDebug("Consent verifier has been used already")) + } + + h.WasUsed = true + if _, err := m.HandleConsentRequest(h.Challenge, &h); err != nil { + return nil, err + } + + h.ConsentRequest = &c + return &h, nil + } + } + } + } + return nil, errors.WithStack(pkg.ErrNotFound) +} + +func (m *MemoryManager) FindPreviouslyGrantedConsentRequests(client string, subject string) ([]HandledConsentRequest, error) { + var rs []HandledConsentRequest + for _, c := range m.handledConsentRequests { + cr, err := m.GetConsentRequest(c.Challenge) + if err != nil { + return nil, err + } + + if client != cr.Client.GetID() { + continue + } + + if subject != cr.Subject { + continue + } + + if c.Error != nil { + continue + } + + if !c.Remember { + continue + } + + if cr.Skip { + continue + } + + if c.RememberFor > 0 && c.RequestedAt.Add(time.Duration(c.RememberFor)*time.Second).Before(time.Now().UTC()) { + continue + } + + c.ConsentRequest = cr + rs = append(rs, c) + } + if len(rs) == 0 { + return []HandledConsentRequest{}, nil + } + + return rs, nil +} + +func (m *MemoryManager) GetAuthenticationSession(id string) (*AuthenticationSession, error) { + if c, ok := m.authSessions[id]; ok { + return &c, nil + } + return nil, errors.WithStack(pkg.ErrNotFound) +} + +func (m *MemoryManager) CreateAuthenticationSession(a *AuthenticationSession) error { + m.authSessions[a.ID] = *a + return nil +} + +func (m *MemoryManager) DeleteAuthenticationSession(id string) error { + delete(m.authSessions, id) + return nil +} + +func (m *MemoryManager) CreateAuthenticationRequest(a *AuthenticationRequest) error { + m.authRequests[a.Challenge] = *a + return nil +} + +func (m *MemoryManager) GetAuthenticationRequest(challenge string) (*AuthenticationRequest, error) { + if c, ok := m.authRequests[challenge]; ok { + return &c, nil + } + return nil, errors.WithStack(pkg.ErrNotFound) +} + +func (m *MemoryManager) HandleAuthenticationRequest(challenge string, r *HandledAuthenticationRequest) (*AuthenticationRequest, error) { + m.handledAuthRequests[r.Challenge] = *r + return m.GetAuthenticationRequest(challenge) +} + +func (m *MemoryManager) VerifyAndInvalidateAuthenticationRequest(verifier string) (*HandledAuthenticationRequest, error) { + for _, c := range m.authRequests { + if c.Verifier == verifier { + for _, h := range m.handledAuthRequests { + if h.Challenge == c.Challenge { + if h.WasUsed { + return nil, errors.WithStack(fosite.ErrInvalidRequest.WithDebug("Authentication verifier has been used already")) + } + + h.WasUsed = true + if _, err := m.HandleAuthenticationRequest(h.Challenge, &h); err != nil { + return nil, err + } + + h.AuthenticationRequest = &c + return &h, nil + } + } + } + } + return nil, errors.WithStack(pkg.ErrNotFound) +} diff --git a/consent/manager_sql.go b/consent/manager_sql.go new file mode 100644 index 00000000000..619baf3c6ee --- /dev/null +++ b/consent/manager_sql.go @@ -0,0 +1,283 @@ +/* + * Copyright © 2015-2018 Aeneas Rekkas + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * @author Aeneas Rekkas + * @Copyright 2017-2018 Aeneas Rekkas + * @license Apache-2.0 + */ + +package consent + +import ( + "fmt" + "strings" + "time" + + "github.com/jmoiron/sqlx" + "github.com/ory/fosite" + "github.com/ory/hydra/client" + "github.com/ory/sqlcon" + "github.com/pkg/errors" + "github.com/rubenv/sql-migrate" +) + +type SQLManager struct { + db *sqlx.DB + c client.Manager +} + +func NewSQLManager(db *sqlx.DB, c client.Manager) *SQLManager { + return &SQLManager{ + db: db, + c: c, + } +} + +func (m *SQLManager) CreateSchemas() (int, error) { + migrate.SetTable("hydra_oauth2_authentication_consent_migration") + n, err := migrate.Exec(m.db.DB, m.db.DriverName(), migrations, migrate.Up) + if err != nil { + return 0, errors.Wrapf(err, "Could not migrate sql schema, applied %d migrations", n) + } + return n, nil +} + +func (m *SQLManager) CreateConsentRequest(c *ConsentRequest) error { + d, err := newSQLConsentRequest(c) + if err != nil { + return err + } + + if _, err := m.db.NamedExec(fmt.Sprintf( + "INSERT INTO hydra_oauth2_consent_request (%s) VALUES (%s)", + strings.Join(sqlParamsRequest, ", "), + ":"+strings.Join(sqlParamsRequest, ", :"), + ), d); err != nil { + return sqlcon.HandleError(err) + } + + return nil +} + +func (m *SQLManager) GetConsentRequest(challenge string) (*ConsentRequest, error) { + var d sqlRequest + + if err := m.db.Get(&d, m.db.Rebind("SELECT * FROM hydra_oauth2_consent_request WHERE challenge=?"), challenge); err != nil { + return nil, sqlcon.HandleError(err) + } + + c, err := m.c.GetConcreteClient(d.Client) + if err != nil { + return nil, err + } + + return d.toConsentRequest(c) +} + +func (m *SQLManager) CreateAuthenticationRequest(c *AuthenticationRequest) error { + d, err := newSQLAuthenticationRequest(c) + if err != nil { + return err + } + + if _, err := m.db.NamedExec(fmt.Sprintf( + "INSERT INTO hydra_oauth2_authentication_request (%s) VALUES (%s)", + strings.Join(sqlParamsRequest, ", "), + ":"+strings.Join(sqlParamsRequest, ", :"), + ), d); err != nil { + return sqlcon.HandleError(err) + } + + return nil +} + +func (m *SQLManager) GetAuthenticationRequest(challenge string) (*AuthenticationRequest, error) { + var d sqlRequest + + if err := m.db.Get(&d, m.db.Rebind("SELECT * FROM hydra_oauth2_authentication_request WHERE challenge=?"), challenge); err != nil { + return nil, sqlcon.HandleError(err) + } + + c, err := m.c.GetConcreteClient(d.Client) + if err != nil { + return nil, err + } + + return d.toAuthenticationRequest(c) +} + +func (m *SQLManager) HandleConsentRequest(challenge string, r *HandledConsentRequest) (*ConsentRequest, error) { + d, err := newSQLHandledConsentRequest(r) + if err != nil { + return nil, err + } + + if _, err := m.db.NamedExec(fmt.Sprintf( + "INSERT INTO hydra_oauth2_consent_request_handled (%s) VALUES (%s)", + strings.Join(sqlParamsConsentRequestHandled, ", "), + ":"+strings.Join(sqlParamsConsentRequestHandled, ", :"), + ), d); err != nil { + return nil, sqlcon.HandleError(err) + } + + return m.GetConsentRequest(challenge) +} + +func (m *SQLManager) VerifyAndInvalidateConsentRequest(verifier string) (*HandledConsentRequest, error) { + var d sqlHandledConsentRequest + var challenge string + + // This can be solved more elegantly with a join statement, but it works for now + + if err := m.db.Get(&challenge, m.db.Rebind("SELECT challenge FROM hydra_oauth2_consent_request WHERE verifier=?"), verifier); err != nil { + return nil, sqlcon.HandleError(err) + } + + if err := m.db.Get(&d, m.db.Rebind("SELECT * FROM hydra_oauth2_consent_request_handled WHERE challenge=?"), challenge); err != nil { + return nil, sqlcon.HandleError(err) + } + + if d.WasUsed { + return nil, errors.WithStack(fosite.ErrInvalidRequest.WithDebug("Consent verifier has been used already")) + } + + r, err := m.GetConsentRequest(challenge) + if err != nil { + return nil, err + } + + if _, err := m.db.Exec(m.db.Rebind("UPDATE hydra_oauth2_consent_request_handled SET was_used=true WHERE challenge=?"), challenge); err != nil { + return nil, sqlcon.HandleError(err) + } + + return d.toHandledConsentRequest(r) +} + +func (m *SQLManager) HandleAuthenticationRequest(challenge string, r *HandledAuthenticationRequest) (*AuthenticationRequest, error) { + d, err := newSQLHandledAuthenticationRequest(r) + if err != nil { + return nil, err + } + + if _, err := m.db.NamedExec(fmt.Sprintf( + "INSERT INTO hydra_oauth2_authentication_request_handled (%s) VALUES (%s)", + strings.Join(sqlParamsAuthenticationRequestHandled, ", "), + ":"+strings.Join(sqlParamsAuthenticationRequestHandled, ", :"), + ), d); err != nil { + return nil, sqlcon.HandleError(err) + } + + return m.GetAuthenticationRequest(challenge) +} + +func (m *SQLManager) VerifyAndInvalidateAuthenticationRequest(verifier string) (*HandledAuthenticationRequest, error) { + var d sqlHandledAuthenticationRequest + var challenge string + + // This can be solved more elegantly with a join statement, but it works for now + + if err := m.db.Get(&challenge, m.db.Rebind("SELECT challenge FROM hydra_oauth2_authentication_request WHERE verifier=?"), verifier); err != nil { + return nil, sqlcon.HandleError(err) + } + + if err := m.db.Get(&d, m.db.Rebind("SELECT * FROM hydra_oauth2_authentication_request_handled WHERE challenge=?"), challenge); err != nil { + return nil, sqlcon.HandleError(err) + } + + if d.WasUsed { + return nil, errors.WithStack(fosite.ErrInvalidRequest.WithDebug("Consent verifier has been used already")) + } + + if _, err := m.db.Exec(m.db.Rebind("UPDATE hydra_oauth2_authentication_request_handled SET was_used=true WHERE challenge=?"), challenge); err != nil { + return nil, sqlcon.HandleError(err) + } + + r, err := m.GetAuthenticationRequest(challenge) + if err != nil { + return nil, err + } + + return d.toHandledAuthenticationRequest(r) +} + +func (m *SQLManager) GetAuthenticationSession(id string) (*AuthenticationSession, error) { + var a AuthenticationSession + if err := m.db.Get(&a, m.db.Rebind("SELECT * FROM hydra_oauth2_authentication_session WHERE id=?"), id); err != nil { + return nil, sqlcon.HandleError(err) + } + + return &a, nil +} + +func (m *SQLManager) CreateAuthenticationSession(a *AuthenticationSession) error { + if _, err := m.db.NamedExec(fmt.Sprintf( + "INSERT INTO hydra_oauth2_authentication_session (%s) VALUES (%s)", + strings.Join(sqlParamsAuthSession, ", "), + ":"+strings.Join(sqlParamsAuthSession, ", :"), + ), a); err != nil { + return sqlcon.HandleError(err) + } + + return nil +} + +func (m *SQLManager) DeleteAuthenticationSession(id string) error { + if _, err := m.db.Exec(m.db.Rebind("DELETE FROM hydra_oauth2_authentication_session WHERE id=?"), id); err != nil { + return sqlcon.HandleError(err) + } + + return nil +} + +func (m *SQLManager) FindPreviouslyGrantedConsentRequests(client string, subject string) ([]HandledConsentRequest, error) { + var a []sqlHandledConsentRequest + + if err := m.db.Select(&a, m.db.Rebind(`SELECT h.* FROM + hydra_oauth2_consent_request_handled as h +JOIN + hydra_oauth2_consent_request as r ON (h.challenge = r.challenge) +WHERE + r.subject=? AND r.client_id=? AND r.skip=FALSE + AND + (h.error='{}' AND h.remember=TRUE) +`), subject, client); err != nil { + return nil, sqlcon.HandleError(err) + } + + var aa []HandledConsentRequest + for _, v := range a { + r, err := m.GetConsentRequest(v.Challenge) + if err != nil { + return nil, err + } + + if v.RememberFor > 0 && v.RequestedAt.Add(time.Duration(v.RememberFor)*time.Second).Before(time.Now().UTC()) { + continue + } + + va, err := v.toHandledConsentRequest(r) + if err != nil { + return nil, err + } + + aa = append(aa, *va) + } + + if len(aa) == 0 { + return []HandledConsentRequest{}, nil + } + + return aa, nil +} diff --git a/consent/manager_test.go b/consent/manager_test.go new file mode 100644 index 00000000000..2746fbc914b --- /dev/null +++ b/consent/manager_test.go @@ -0,0 +1,348 @@ +/* + * Copyright © 2015-2018 Aeneas Rekkas + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * @author Aeneas Rekkas + * @Copyright 2017-2018 Aeneas Rekkas + * @license Apache-2.0 + */ + +package consent + +import ( + "testing" + "time" + + "github.com/ory/fosite" + "github.com/ory/hydra/client" + "github.com/ory/sqlcon/dockertest" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func mockConsentRequest(key string, remember bool, rememberFor int, hasError bool, skip bool) (c *ConsentRequest, h *HandledConsentRequest) { + c = &ConsentRequest{ + OpenIDConnectContext: &OpenIDConnectContext{ + ACRValues: []string{"1" + key, "2" + key}, + UILocales: []string{"fr" + key, "de" + key}, + Display: "popup" + key, + }, + Client: &client.Client{ID: "client" + key}, + Subject: "subject" + key, + RequestURL: "https://request-url/path" + key, + Skip: skip, + Challenge: "challenge" + key, + RequestedScope: []string{"scopea" + key, "scopeb" + key}, + Verifier: "verifier" + key, + CSRF: "csrf" + key, + } + + var err *RequestDeniedError + if hasError { + err = &RequestDeniedError{ + Name: "error_name" + key, + Description: "error_description" + key, + Hint: "error_hint,omitempty" + key, + Code: 100, + Debug: "error_debug,omitempty" + key, + } + } + + h = &HandledConsentRequest{ + ConsentRequest: c, + RememberFor: rememberFor, + Remember: remember, + Challenge: "challenge" + key, + RequestedAt: time.Now().UTC().Add(-time.Minute), + Error: err, + } + + return c, h +} + +func mockAuthRequest(key string) (c *AuthenticationRequest, h *HandledAuthenticationRequest) { + c = &AuthenticationRequest{ + OpenIDConnectContext: &OpenIDConnectContext{ + ACRValues: []string{"1" + key, "2" + key}, + UILocales: []string{"fr" + key, "de" + key}, + Display: "popup" + key, + }, + Client: &client.Client{ID: "client" + key}, + Subject: "subject" + key, + RequestURL: "https://request-url/path" + key, + Skip: true, + Challenge: "challenge" + key, + RequestedScope: []string{"scopea" + key, "scopeb" + key}, + Verifier: "verifier" + key, + CSRF: "csrf" + key, + } + + var err = &RequestDeniedError{ + Name: "error_name" + key, + Description: "error_description" + key, + Hint: "error_hint,omitempty" + key, + Code: 100, + Debug: "error_debug,omitempty" + key, + } + + h = &HandledAuthenticationRequest{ + AuthenticationRequest: c, + RememberFor: 120, + Remember: true, + Challenge: "challenge" + key, + RequestedAt: time.Now().UTC().Add(-time.Minute), + Error: err, + } + + return c, h +} + +func connectToPostgres(t *testing.T, managers map[string]Manager, c client.Manager) { + db, err := dockertest.ConnectToTestPostgreSQL() + if err != nil { + t.Logf("Could not connect to database: %v", err) + t.FailNow() + return + } + + s := NewSQLManager(db, c) + if _, err := s.CreateSchemas(); err != nil { + t.Logf("Could not create postgres schema: %v", err) + t.FailNow() + return + } + + managers["postgres"] = s +} + +func connectToMySQL(t *testing.T, managers map[string]Manager, c client.Manager) { + db, err := dockertest.ConnectToTestMySQL() + if err != nil { + t.Logf("Could not connect to database: %v", err) + t.FailNow() + return + } + + s := NewSQLManager(db, c) + if _, err := s.CreateSchemas(); err != nil { + t.Logf("Could not create mysql schema: %v", err) + t.FailNow() + return + } + + managers["mysql"] = s +} + +func TestManagers(t *testing.T) { + clientManager := client.NewMemoryManager(&fosite.BCrypt{WorkFactor: 8}) + var managers = map[string]Manager{ + "memory": NewMemoryManager(), + } + + if !testing.Short() { + connectToPostgres(t, managers, clientManager) + connectToMySQL(t, managers, clientManager) + } + + t.Run("case=auth-session", func(t *testing.T) { + for k, m := range managers { + t.Run("manager="+k, func(t *testing.T) { + for _, tc := range []struct { + s AuthenticationSession + }{ + { + s: AuthenticationSession{ + ID: "session1", + AuthenticatedAt: time.Now().Round(time.Second).UTC(), + Subject: "subject1", + }, + }, + { + s: AuthenticationSession{ + ID: "session2", + AuthenticatedAt: time.Now().Round(time.Minute).UTC(), + Subject: "subject2", + }, + }, + } { + t.Run("case=create-get-"+tc.s.ID, func(t *testing.T) { + _, err := m.GetAuthenticationSession(tc.s.ID) + require.Error(t, err) + + err = m.CreateAuthenticationSession(&tc.s) + require.NoError(t, err) + + got, err := m.GetAuthenticationSession(tc.s.ID) + require.NoError(t, err) + assert.EqualValues(t, tc.s.ID, got.ID) + assert.EqualValues(t, tc.s.AuthenticatedAt.Unix(), got.AuthenticatedAt.Unix()) + assert.EqualValues(t, tc.s.Subject, got.Subject) + }) + } + for _, tc := range []struct { + id string + }{ + { + id: "session1", + }, + { + id: "session2", + }, + } { + t.Run("case=delete-get-"+tc.id, func(t *testing.T) { + err := m.DeleteAuthenticationSession(tc.id) + require.NoError(t, err) + + _, err = m.GetAuthenticationSession(tc.id) + require.Error(t, err) + }) + } + }) + } + }) + + t.Run("case=consent-request", func(t *testing.T) { + for k, m := range managers { + t.Run("manager="+k, func(t *testing.T) { + for _, tc := range []struct { + key string + remember bool + rememberFor int + hasError bool + skip bool + }{ + {"1", true, 0, false, false}, + {"2", true, 0, true, false}, + {"3", true, 1, false, false}, + {"4", false, 0, false, false}, + {"5", true, 120, false, false}, + {"6", true, 120, false, true}, + } { + t.Run("key="+tc.key, func(t *testing.T) { + c, h := mockConsentRequest(tc.key, tc.remember, tc.rememberFor, tc.hasError, tc.skip) + clientManager.CreateClient(c.Client) // Ignore errors that are caused by duplication + + _, err := m.GetConsentRequest("challenge" + tc.key) + require.Error(t, err) + + require.NoError(t, m.CreateConsentRequest(c)) + + got1, err := m.GetConsentRequest("challenge" + tc.key) + require.NoError(t, err) + compareConsentRequest(t, c, got1) + + got1, err = m.HandleConsentRequest("challenge"+tc.key, h) + require.NoError(t, err) + compareConsentRequest(t, c, got1) + + got2, err := m.VerifyAndInvalidateConsentRequest("verifier" + tc.key) + require.NoError(t, err) + compareConsentRequest(t, c, got2.ConsentRequest) + assert.Equal(t, c.Challenge, got2.Challenge) + + _, err = m.VerifyAndInvalidateConsentRequest("verifier" + tc.key) + require.Error(t, err) + }) + } + + for _, tc := range []struct { + keyC string + keyS string + expectedLength int + }{ + {"1", "1", 1}, + {"2", "2", 0}, + {"3", "3", 0}, + {"4", "4", 0}, + {"1", "2", 0}, + {"2", "1", 0}, + {"5", "5", 1}, + {"6", "6", 0}, + } { + t.Run("key="+tc.keyC+"-"+tc.keyS, func(t *testing.T) { + rs, err := m.FindPreviouslyGrantedConsentRequests("client"+tc.keyC, "subject"+tc.keyS) + require.NoError(t, err) + assert.Len(t, rs, tc.expectedLength) + }) + } + }) + } + }) + + t.Run("case=auth-request", func(t *testing.T) { + for k, m := range managers { + t.Run("manager="+k, func(t *testing.T) { + for _, tc := range []struct { + key string + }{ + {"1"}, + {"2"}, + {"3"}, + {"4"}, + {"5"}, + } { + t.Run("key="+tc.key, func(t *testing.T) { + c, h := mockAuthRequest(tc.key) + clientManager.CreateClient(c.Client) // Ignore errors that are caused by duplication + + _, err := m.GetAuthenticationRequest("challenge" + tc.key) + require.Error(t, err) + + require.NoError(t, m.CreateAuthenticationRequest(c)) + + got1, err := m.GetAuthenticationRequest("challenge" + tc.key) + require.NoError(t, err) + compareAuthenticationRequest(t, c, got1) + + got1, err = m.HandleAuthenticationRequest("challenge"+tc.key, h) + require.NoError(t, err) + compareAuthenticationRequest(t, c, got1) + + got2, err := m.VerifyAndInvalidateAuthenticationRequest("verifier" + tc.key) + require.NoError(t, err) + compareAuthenticationRequest(t, c, got2.AuthenticationRequest) + assert.Equal(t, c.Challenge, got2.Challenge) + + _, err = m.VerifyAndInvalidateAuthenticationRequest("verifier" + tc.key) + require.Error(t, err) + }) + } + }) + } + }) +} + +func compareAuthenticationRequest(t *testing.T, a, b *AuthenticationRequest) { + assert.EqualValues(t, a.Client.ID, b.Client.ID) + assert.EqualValues(t, a.Challenge, b.Challenge) + assert.EqualValues(t, *a.OpenIDConnectContext, *b.OpenIDConnectContext) + assert.EqualValues(t, a.Subject, b.Subject) + assert.EqualValues(t, a.RequestedScope, b.RequestedScope) + assert.EqualValues(t, a.Verifier, b.Verifier) + assert.EqualValues(t, a.RequestURL, b.RequestURL) + assert.EqualValues(t, a.CSRF, b.CSRF) + assert.EqualValues(t, a.Skip, b.Skip) +} + +func compareConsentRequest(t *testing.T, a, b *ConsentRequest) { + assert.EqualValues(t, a.Client.ID, b.Client.ID) + assert.EqualValues(t, a.Challenge, b.Challenge) + assert.EqualValues(t, *a.OpenIDConnectContext, *b.OpenIDConnectContext) + assert.EqualValues(t, a.Subject, b.Subject) + assert.EqualValues(t, a.RequestedScope, b.RequestedScope) + assert.EqualValues(t, a.Verifier, b.Verifier) + assert.EqualValues(t, a.RequestURL, b.RequestURL) + assert.EqualValues(t, a.CSRF, b.CSRF) + assert.EqualValues(t, a.Skip, b.Skip) +} diff --git a/consent/sql_helper.go b/consent/sql_helper.go new file mode 100644 index 00000000000..2614f5bb3f7 --- /dev/null +++ b/consent/sql_helper.go @@ -0,0 +1,348 @@ +/* + * Copyright © 2015-2018 Aeneas Rekkas + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * @author Aeneas Rekkas + * @Copyright 2017-2018 Aeneas Rekkas + * @license Apache-2.0 + */ + +package consent + +import ( + "encoding/json" + "strings" + "time" + + "github.com/ory/go-convenience/stringsx" + "github.com/ory/hydra/client" + "github.com/pkg/errors" + "github.com/rubenv/sql-migrate" +) + +var migrations = &migrate.MemoryMigrationSource{ + Migrations: []*migrate.Migration{ + { + Id: "1", + Up: []string{ + `CREATE TABLE hydra_oauth2_consent_request ( + challenge varchar(40) NOT NULL PRIMARY KEY, + verifier varchar(40) NOT NULL, + client_id varchar(255) NOT NULL, + subject varchar(255) NOT NULL, + request_url text NOT NULL, + skip bool NOT NULL, + requested_scope text NOT NULL, + csrf varchar(40) NOT NULL, + oidc_context text NOT NULL +)`, + // It would probably make sense here to have a FK relation to clients, but it increases testing complexity and might also + // purge important audit data when a client is deleted. Also, stale data does not have a negative impact here + // FOREIGN KEY (client_id) REFERENCES hydra_client (id) ON DELETE CASCADE + `CREATE TABLE hydra_oauth2_authentication_request ( + challenge varchar(40) NOT NULL PRIMARY KEY, + requested_scope text NOT NULL, + verifier varchar(40) NOT NULL, + csrf varchar(40) NOT NULL, + subject varchar(255) NOT NULL, + request_url text NOT NULL, + skip bool NOT NULL, + client_id varchar(255) NOT NULL, + oidc_context text NOT NULL +)`, + // It would probably make sense here to have a FK relation to clients, but it increases testing complexity and might also + // purge important audit data when a client is deleted. Also, stale data does not have a negative impact here + // FOREIGN KEY (client_id) REFERENCES hydra_client (id) ON DELETE CASCADE + `CREATE TABLE hydra_oauth2_authentication_session ( + id varchar(40) NOT NULL PRIMARY KEY, + authenticated_at timestamp NOT NULL DEFAULT NOW(), + subject varchar(255) NOT NULL +)`, + `CREATE TABLE hydra_oauth2_consent_request_handled ( + challenge varchar(40) NOT NULL PRIMARY KEY, + granted_scope text NOT NULL, + remember bool NOT NULL, + remember_for int NOT NULL, + error text NOT NULL, + requested_at timestamp NOT NULL DEFAULT now(), + session_access_token text NOT NULL, + session_id_token text NOT NULL, + was_used bool NOT NULL +)`, + `CREATE TABLE hydra_oauth2_authentication_request_handled ( + challenge varchar(40) NOT NULL PRIMARY KEY, + subject varchar(255) NOT NULL, + remember bool NOT NULL, + remember_for int NOT NULL, + error text NOT NULL, + acr text NOT NULL, + requested_at timestamp NOT NULL DEFAULT now(), + was_used bool NOT NULL +)`, + }, + Down: []string{ + "DROP TABLE hydra_oauth2_consent_request", + "DROP TABLE hydra_oauth2_authentication_request", + "DROP TABLE hydra_oauth2_authentication_session", + "DROP TABLE hydra_oauth2_consent_request_handled", + "DROP TABLE hydra_oauth2_authentication_request_handled", + }, + }, + }, +} + +var sqlParamsAuthenticationRequestHandled = []string{ + "challenge", + "subject", + "remember", + "remember_for", + "error", + "requested_at", + "acr", + "was_used", +} + +var sqlParamsRequest = []string{ + "challenge", + "verifier", + "client_id", + "subject", + "request_url", + "skip", + "requested_scope", + "csrf", + "oidc_context", +} +var sqlParamsConsentRequestHandled = []string{ + "challenge", + "granted_scope", + "remember", + "remember_for", + "error", + "requested_at", + "session_access_token", + "session_id_token", + "was_used", +} +var sqlParamsAuthSession = []string{ + "id", + "authenticated_at", + "subject", +} + +type sqlRequest struct { + OpenIDConnectContext string `db:"oidc_context"` + Client string `db:"client_id"` + Subject string `db:"subject"` + RequestURL string `db:"request_url"` + Skip bool `db:"skip"` + Challenge string `db:"challenge"` + RequestedScope string `db:"requested_scope"` + Verifier string `db:"verifier"` + CSRF string `db:"csrf"` +} + +func newSQLConsentRequest(c *ConsentRequest) (*sqlRequest, error) { + oidc, err := json.Marshal(c.OpenIDConnectContext) + if err != nil { + return nil, errors.WithStack(err) + } + + return &sqlRequest{ + OpenIDConnectContext: string(oidc), + Client: c.Client.GetID(), + Subject: c.Subject, + RequestURL: c.RequestURL, + Skip: c.Skip, + Challenge: c.Challenge, + RequestedScope: strings.Join(c.RequestedScope, "|"), + Verifier: c.Verifier, + CSRF: c.CSRF, + }, nil +} + +func newSQLAuthenticationRequest(c *AuthenticationRequest) (*sqlRequest, error) { + var cc ConsentRequest + cc = ConsentRequest(*c) + return newSQLConsentRequest(&cc) +} + +func (s *sqlRequest) toAuthenticationRequest(client *client.Client) (*AuthenticationRequest, error) { + cr, err := s.toConsentRequest(client) + if err != nil { + return nil, err + } + + var ar AuthenticationRequest + ar = AuthenticationRequest(*cr) + return &ar, nil +} + +func (s *sqlRequest) toConsentRequest(client *client.Client) (*ConsentRequest, error) { + var oidc OpenIDConnectContext + if err := json.Unmarshal([]byte(s.OpenIDConnectContext), &oidc); err != nil { + return nil, errors.WithStack(err) + } + + return &ConsentRequest{ + OpenIDConnectContext: &oidc, + Client: client, + Subject: s.Subject, + RequestURL: s.RequestURL, + Skip: s.Skip, + Challenge: s.Challenge, + RequestedScope: stringsx.Splitx(s.RequestedScope, "|"), + Verifier: s.Verifier, + CSRF: s.CSRF, + }, nil +} + +type sqlHandledConsentRequest struct { + GrantedScope string `db:"granted_scope"` + SessionIDToken string `db:"session_id_token"` + SessionAccessToken string `db:"session_access_token"` + Remember bool `db:"remember"` + RememberFor int `db:"remember_for"` + Error string `db:"error"` + Challenge string `db:"challenge"` + RequestedAt time.Time `db:"requested_at"` + WasUsed bool `db:"was_used"` +} + +func newSQLHandledConsentRequest(c *HandledConsentRequest) (*sqlHandledConsentRequest, error) { + sidt := "{}" + sat := "{}" + e := "{}" + + if c.Session != nil { + if len(c.Session.IDToken) > 0 { + if out, err := json.Marshal(c.Session.IDToken); err != nil { + return nil, errors.WithStack(err) + } else { + sidt = string(out) + } + } + + if len(c.Session.AccessToken) > 0 { + if out, err := json.Marshal(c.Session.AccessToken); err != nil { + return nil, errors.WithStack(err) + } else { + sat = string(out) + } + } + } + + if c.Error != nil { + if out, err := json.Marshal(c.Error); err != nil { + return nil, errors.WithStack(err) + } else { + e = string(out) + } + } + + return &sqlHandledConsentRequest{ + GrantedScope: strings.Join(c.GrantedScope, "|"), + SessionIDToken: sidt, + SessionAccessToken: sat, + Remember: c.Remember, + RememberFor: c.RememberFor, + Error: e, + Challenge: c.Challenge, + RequestedAt: c.RequestedAt, + WasUsed: c.WasUsed, + }, nil +} + +func (s *sqlHandledConsentRequest) toHandledConsentRequest(r *ConsentRequest) (*HandledConsentRequest, error) { + var idt map[string]interface{} + var at map[string]interface{} + var e RequestDeniedError + + if err := json.Unmarshal([]byte(s.SessionIDToken), &idt); err != nil { + return nil, errors.WithStack(err) + } + if err := json.Unmarshal([]byte(s.SessionAccessToken), &at); err != nil { + return nil, errors.WithStack(err) + } + if err := json.Unmarshal([]byte(s.Error), &e); err != nil { + return nil, errors.WithStack(err) + } + + return &HandledConsentRequest{ + GrantedScope: stringsx.Splitx(s.GrantedScope, "|"), + RememberFor: s.RememberFor, + Remember: s.Remember, + Challenge: s.Challenge, + RequestedAt: s.RequestedAt, + WasUsed: s.WasUsed, + Session: &ConsentRequestSessionData{ + IDToken: idt, + AccessToken: at, + }, + Error: &e, + ConsentRequest: r, + }, nil +} + +type sqlHandledAuthenticationRequest struct { + Remember bool `db:"remember"` + RememberFor int `db:"remember_for"` + ACR string `db:"acr"` + Subject string `db:"subject"` + Error string `db:"error"` + Challenge string `db:"challenge"` + RequestedAt time.Time `db:"requested_at"` + WasUsed bool `db:"was_used"` +} + +func newSQLHandledAuthenticationRequest(c *HandledAuthenticationRequest) (*sqlHandledAuthenticationRequest, error) { + e := "{}" + + if c.Error != nil { + if out, err := json.Marshal(c.Error); err != nil { + return nil, errors.WithStack(err) + } else { + e = string(out) + } + } + + return &sqlHandledAuthenticationRequest{ + ACR: c.ACR, + Remember: c.Remember, + RememberFor: c.RememberFor, + Error: e, + Challenge: c.Challenge, + RequestedAt: c.RequestedAt, + WasUsed: c.WasUsed, + }, nil +} + +func (s *sqlHandledAuthenticationRequest) toHandledAuthenticationRequest(a *AuthenticationRequest) (*HandledAuthenticationRequest, error) { + var e RequestDeniedError + + if err := json.Unmarshal([]byte(s.Error), &e); err != nil { + return nil, errors.WithStack(err) + } + + return &HandledAuthenticationRequest{ + RememberFor: s.RememberFor, + Remember: s.Remember, + Challenge: s.Challenge, + RequestedAt: s.RequestedAt, + WasUsed: s.WasUsed, + ACR: s.ACR, + Error: &e, + AuthenticationRequest: a, + }, nil +} diff --git a/pkg/split_string.go b/consent/strategy.go similarity index 69% rename from pkg/split_string.go rename to consent/strategy.go index 7b9a477a06d..e4cf8526ba3 100644 --- a/pkg/split_string.go +++ b/consent/strategy.go @@ -14,20 +14,18 @@ * limitations under the License. * * @author Aeneas Rekkas - * @copyright 2015-2018 Aeneas Rekkas + * @Copyright 2017-2018 Aeneas Rekkas * @license Apache-2.0 */ -package pkg +package consent -import "strings" +import ( + "net/http" -// SplitNonEmpty is a special case of strings.Split -// which returns an empty slice if string is empty -func SplitNonEmpty(s, sep string) []string { - if s == "" { - return []string{} - } + "github.com/ory/fosite" +) - return strings.Split(s, sep) +type Strategy interface { + HandleOAuth2AuthorizationRequest(w http.ResponseWriter, r *http.Request, req fosite.AuthorizeRequester) (*HandledConsentRequest, error) } diff --git a/consent/strategy_default.go b/consent/strategy_default.go new file mode 100644 index 00000000000..ea2ada09e38 --- /dev/null +++ b/consent/strategy_default.go @@ -0,0 +1,359 @@ +/* + * Copyright © 2015-2018 Aeneas Rekkas + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * @author Aeneas Rekkas + * @Copyright 2017-2018 Aeneas Rekkas + * @license Apache-2.0 + */ + +package consent + +import ( + "net/http" + "net/url" + "strings" + "time" + + "github.com/gorilla/sessions" + "github.com/ory/fosite" + "github.com/ory/go-convenience/mapx" + "github.com/ory/go-convenience/stringslice" + "github.com/ory/go-convenience/stringsx" + "github.com/ory/go-convenience/urlx" + "github.com/ory/hydra/pkg" + "github.com/pborman/uuid" + "github.com/pkg/errors" +) + +const ( + cookieAuthenticationName = "oauth2_authentication_session" + cookieAuthenticationSIDName = "sid" + + cookieAuthenticationCSRFName = "oauth2_authentication_csrf" + cookieConsentCSRFName = "oauth2_consent_csrf" +) + +type DefaultStrategy struct { + AuthenticationURL string + ConsentURL string + IssuerURL string + OAuth2AuthURL string + M Manager + CookieStore sessions.Store + ScopeStrategy fosite.ScopeStrategy + RunsHTTPS bool + RequestMaxAge time.Duration +} + +func NewStrategy( + authenticationURL string, + consentURL string, + issuerURL string, + oAuth2AuthURL string, + m Manager, + cookieStore sessions.Store, + scopeStrategy fosite.ScopeStrategy, + runsHTTPS bool, + requestMaxAge time.Duration, +) *DefaultStrategy { + return &DefaultStrategy{ + AuthenticationURL: authenticationURL, + ConsentURL: consentURL, + IssuerURL: issuerURL, + OAuth2AuthURL: oAuth2AuthURL, + M: m, + CookieStore: cookieStore, + ScopeStrategy: scopeStrategy, + RunsHTTPS: runsHTTPS, + RequestMaxAge: requestMaxAge, + } +} + +var ErrAbortOAuth2Request = errors.New("The OAuth 2.0 Authorization request must be aborted") +var errNoPreviousConsentFound = errors.New("No previous OAuth 2.0 Consent could be found for this access request") + +func (s *DefaultStrategy) requestAuthentication(w http.ResponseWriter, r *http.Request, ar fosite.AuthorizeRequester) error { + prompt := stringsx.Splitx(ar.GetRequestForm().Get("prompt"), " ") + if stringslice.Has(prompt, "login") { + return s.forwardAuthenticationRequest(w, r, ar, "") + } + + // We try to open the session cookie. If it does not exist (indicated by the error), we must authenticate the user. + cookie, err := s.CookieStore.Get(r, cookieAuthenticationName) + if err != nil { + //id.L.WithError(err).Debug("No OAuth2 authentication session was found, performing consent authentication flow") + return s.forwardAuthenticationRequest(w, r, ar, "") + } + + sessionID := mapx.GetStringDefault(cookie.Values, cookieAuthenticationSIDName, "") + if sessionID == "" { + return s.forwardAuthenticationRequest(w, r, ar, "") + } + + session, err := s.M.GetAuthenticationSession(sessionID) + if errors.Cause(err) == pkg.ErrNotFound { + return s.forwardAuthenticationRequest(w, r, ar, "") + } else if err != nil { + return err + } + + return s.forwardAuthenticationRequest(w, r, ar, session.Subject) +} + +func (s *DefaultStrategy) forwardAuthenticationRequest(w http.ResponseWriter, r *http.Request, ar fosite.AuthorizeRequester, subject string) error { + skip := false + if subject != "" { + skip = true + } + + // Let'id validate that prompt is actually not "none" if we can't skip authentication + prompt := stringsx.Splitx(ar.GetRequestForm().Get("prompt"), " ") + if stringslice.Has(prompt, "none") && !skip { + return errors.WithStack(fosite.ErrLoginRequired.WithDebug(`Prompt "none" was requested, but no existing login session was found`)) + } + + // Set up csrf/challenge/verifier values + verifier := strings.Replace(uuid.New(), "-", "", -1) + challenge := strings.Replace(uuid.New(), "-", "", -1) + csrf := strings.Replace(uuid.New(), "-", "", -1) + + // Generate the request URL + iu, err := url.Parse(s.IssuerURL) + if err != nil { + return errors.WithStack(err) + } + iu = urlx.AppendPaths(iu, s.OAuth2AuthURL) + iu.RawQuery = r.URL.RawQuery + + // Set the session + if err := s.M.CreateAuthenticationRequest( + &AuthenticationRequest{ + Challenge: challenge, + Verifier: verifier, + CSRF: csrf, + Skip: skip, + RequestedScope: []string(ar.GetRequestedScopes()), + Subject: subject, + Client: sanitizeClient(ar), + RequestURL: iu.String(), + OpenIDConnectContext: &OpenIDConnectContext{ + ACRValues: stringsx.Splitx(ar.GetRequestForm().Get("acr_values"), " "), + UILocales: stringsx.Splitx(ar.GetRequestForm().Get("ui_locales"), " "), + Display: ar.GetRequestForm().Get("display"), + }, + }, + ); err != nil { + return errors.WithStack(err) + } + + if err := createCsrfSession(w, r, s.CookieStore, cookieAuthenticationCSRFName, csrf, s.RunsHTTPS); err != nil { + return errors.WithStack(err) + } + + au, err := url.Parse(s.AuthenticationURL) + if err != nil { + return errors.WithStack(err) + } + + q := au.Query() + q.Set("login_challenge", challenge) + au.RawQuery = q.Encode() + + http.Redirect(w, r, au.String(), http.StatusFound) + + // generate the verifier + return errors.WithStack(ErrAbortOAuth2Request) +} + +func (s *DefaultStrategy) verifyAuthentication(w http.ResponseWriter, r *http.Request, req fosite.AuthorizeRequester, verifier string) (*HandledAuthenticationRequest, error) { + session, err := s.M.VerifyAndInvalidateAuthenticationRequest(verifier) + if errors.Cause(err) == pkg.ErrNotFound { + return nil, errors.WithStack(fosite.ErrAccessDenied.WithDebug("The login verifier has already been used, has not been granted, or is invalid.")) + } else if err != nil { + return nil, err + } + + if session.Error != nil { + return nil, errors.WithStack(session.Error.toRFCError()) + } + + if session.RequestedAt.Add(s.RequestMaxAge).Before(time.Now()) { + return nil, errors.WithStack(fosite.ErrRequestUnauthorized.WithDebug("The login request has expired, please try again.")) + } + + if err := validateCsrfSession(r, s.CookieStore, cookieAuthenticationCSRFName, session.AuthenticationRequest.CSRF); err != nil { + return nil, err + } + + if !session.Remember { + return session, nil + } + + cookie, _ := s.CookieStore.Get(r, cookieAuthenticationName) + sid, err := mapx.GetString(cookie.Values, cookieAuthenticationSIDName) + if err != nil { + sid = uuid.New() + } + + if err := s.M.CreateAuthenticationSession(&AuthenticationSession{ + ID: sid, + Subject: session.Subject, + AuthenticatedAt: time.Now().UTC(), + }); err != nil { + return nil, err + } + + cookie.Values[cookieAuthenticationSIDName] = sid + if session.RememberFor > 0 { + cookie.Options.MaxAge = session.RememberFor + } + cookie.Options.HttpOnly = true + + if s.RunsHTTPS { + cookie.Options.Secure = true + } + + if err := cookie.Save(r, w); err != nil { + return nil, errors.WithStack(err) + } + return session, nil +} + +func (s *DefaultStrategy) requestConsent(w http.ResponseWriter, r *http.Request, ar fosite.AuthorizeRequester, authenticationSession *HandledAuthenticationRequest) error { + prompt := stringsx.Splitx(ar.GetRequestForm().Get("prompt"), " ") + if stringslice.Has(prompt, "consent") { + return s.forwardConsentRequest(w, r, ar, authenticationSession, nil) + } + + if ar.GetClient().IsPublic() { + return s.forwardConsentRequest(w, r, ar, authenticationSession, nil) + } + + if ar.GetResponseTypes().Has("token") { + // We're probably requesting the implicit or hybrid flow in which case we MUST authenticate and authorize the request + return s.forwardConsentRequest(w, r, ar, authenticationSession, nil) + } + + consentSessions, err := s.M.FindPreviouslyGrantedConsentRequests(ar.GetClient().GetID(), authenticationSession.Subject) + if errors.Cause(err) == errNoPreviousConsentFound { + return s.forwardConsentRequest(w, r, ar, authenticationSession, nil) + } else if err != nil { + return err + } + + if found := matchScopes(s.ScopeStrategy, consentSessions, ar.GetRequestedScopes()); found != nil { + return s.forwardConsentRequest(w, r, ar, authenticationSession, found) + } + + return s.forwardConsentRequest(w, r, ar, authenticationSession, nil) +} + +func (s *DefaultStrategy) forwardConsentRequest(w http.ResponseWriter, r *http.Request, ar fosite.AuthorizeRequester, as *HandledAuthenticationRequest, cs *HandledConsentRequest) error { + skip := false + if cs != nil { + skip = true + } + + // Let'id validate that prompt is actually not "none" if we can't skip authentication + prompt := stringsx.Splitx(ar.GetRequestForm().Get("prompt"), " ") + if stringslice.Has(prompt, "none") && !skip { + return errors.WithStack(fosite.ErrConsentRequired.WithDebug(`Prompt "none" was requested, but no previous consent was found`)) + } + + // Set up csrf/challenge/verifier values + verifier := strings.Replace(uuid.New(), "-", "", -1) + challenge := strings.Replace(uuid.New(), "-", "", -1) + csrf := strings.Replace(uuid.New(), "-", "", -1) + + if err := s.M.CreateConsentRequest( + &ConsentRequest{ + Challenge: challenge, + Verifier: verifier, + CSRF: csrf, + Skip: skip, + RequestedScope: []string(ar.GetRequestedScopes()), + Subject: as.Subject, + Client: sanitizeClient(ar), + RequestURL: as.AuthenticationRequest.RequestURL, + }, + ); err != nil { + return errors.WithStack(err) + } + + cu, err := url.Parse(s.ConsentURL) + if err != nil { + return errors.WithStack(err) + } + + if err := createCsrfSession(w, r, s.CookieStore, cookieConsentCSRFName, csrf, s.RunsHTTPS); err != nil { + return errors.WithStack(err) + } + + q := cu.Query() + q.Set("consent_challenge", challenge) + cu.RawQuery = q.Encode() + + http.Redirect(w, r, cu.String(), http.StatusFound) + + // generate the verifier + return errors.WithStack(ErrAbortOAuth2Request) +} + +func (s *DefaultStrategy) verifyConsent(w http.ResponseWriter, r *http.Request, req fosite.AuthorizeRequester, verifier string) (*HandledConsentRequest, error) { + session, err := s.M.VerifyAndInvalidateConsentRequest(verifier) + if errors.Cause(err) == pkg.ErrNotFound { + return nil, errors.WithStack(fosite.ErrAccessDenied.WithDebug("The consent verifier has already been used, has not been granted, or is invalid.")) + } else if err != nil { + return nil, err + } + + if session.RequestedAt.Add(s.RequestMaxAge).Before(time.Now()) { + return nil, errors.WithStack(fosite.ErrRequestUnauthorized.WithDebug("The consent request has expired, please try again.")) + } + + if session.Error != nil { + return nil, errors.WithStack(session.Error.toRFCError()) + } + + if err := validateCsrfSession(r, s.CookieStore, cookieConsentCSRFName, session.ConsentRequest.CSRF); err != nil { + return nil, err + } + + return session, nil +} + +func (s *DefaultStrategy) HandleOAuth2AuthorizationRequest(w http.ResponseWriter, r *http.Request, req fosite.AuthorizeRequester) (*HandledConsentRequest, error) { + authenticationVerifier := strings.TrimSpace(req.GetRequestForm().Get("login_verifier")) + consentVerifier := strings.TrimSpace(req.GetRequestForm().Get("consent_verifier")) + if authenticationVerifier == "" && consentVerifier == "" { + // ok, we need to process this request and redirect to auth endpoint + return nil, s.requestAuthentication(w, r, req) + } else if authenticationVerifier != "" { + authSession, err := s.verifyAuthentication(w, r, req, authenticationVerifier) + if err != nil { + return nil, err + } + + // ok, we need to process this request and redirect to auth endpoint + return nil, s.requestConsent(w, r, req, authSession) + } + + consentSession, err := s.verifyConsent(w, r, req, consentVerifier) + if err != nil { + return nil, err + } + + return consentSession, nil +} diff --git a/consent/strategy_default_test.go b/consent/strategy_default_test.go new file mode 100644 index 00000000000..32e2f980dd1 --- /dev/null +++ b/consent/strategy_default_test.go @@ -0,0 +1,460 @@ +/* + * Copyright © 2015-2018 Aeneas Rekkas + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * @author Aeneas Rekkas + * @Copyright 2017-2018 Aeneas Rekkas + * @license Apache-2.0 + */ + +package consent + +import ( + "fmt" + "net/http" + "net/http/cookiejar" + "net/http/httptest" + "testing" + "time" + + "github.com/gorilla/sessions" + "github.com/julienschmidt/httprouter" + "github.com/ory/fosite" + "github.com/ory/herodot" + "github.com/ory/hydra/client" + "github.com/ory/hydra/sdk/go/hydra/swagger" + "github.com/pkg/errors" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func mockProvider(h *func(w http.ResponseWriter, r *http.Request)) *httptest.Server { + return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + (*h)(w, r) + })) + +} + +func noopHandler(t *testing.T) func(w http.ResponseWriter, r *http.Request) { + return func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusNotImplemented) + } +} + +func newCookieJar() *cookiejar.Jar { + c, _ := cookiejar.New(&cookiejar.Options{}) + return c +} + +func TestStrategy(t *testing.T) { + var lph, cph, aph func(w http.ResponseWriter, r *http.Request) + lp := mockProvider(&lph) + cp := mockProvider(&cph) + ap := mockProvider(&aph) + + writer := herodot.NewJSONWriter(nil) + manager := NewMemoryManager() + handler := NewHandler(writer, manager) + router := httprouter.New() + handler.SetRoutes(router) + api := httptest.NewServer(router) + strategy := NewStrategy( + lp.URL, + cp.URL, + ap.URL, + "/oauth2/auth", + manager, + sessions.NewCookieStore([]byte("dummy-secret-yay")), + fosite.ExactScopeStrategy, + false, + time.Hour, + ) + _ = swagger.NewOAuth2ApiWithBasePath(api.URL) + apiClient := swagger.NewOAuth2ApiWithBasePath(api.URL) + + persistentCJ := newCookieJar() + + for k, tc := range []struct { + d string + lv string + cv string + lph, cph func(t *testing.T) func(w http.ResponseWriter, r *http.Request) + req fosite.AuthorizeRequest + expectSession *HandledConsentRequest + expectErr []bool + expectErrType []error + expectFinalStatusCode int + jar http.CookieJar + }{ + { + d: "This should fail because a login verifier was given that doesn't exist in the store", + req: fosite.AuthorizeRequest{Request: fosite.Request{Client: &client.Client{ID: "client-id"}}}, + lv: "invalid", + expectErrType: []error{fosite.ErrAccessDenied}, + expectErr: []bool{true}, + expectFinalStatusCode: http.StatusForbidden, + }, { + d: "This should fail because a consent verifier was given but no login verifier", + req: fosite.AuthorizeRequest{Request: fosite.Request{Client: &client.Client{ID: "client-id"}}}, + lv: "", + cv: "invalid", + expectErrType: []error{fosite.ErrAccessDenied}, + expectErr: []bool{true}, + expectFinalStatusCode: http.StatusForbidden, + }, + { + d: "This should fail because the request was redirected but the login endpoint doesn't do anything (like redirecting back)", + req: fosite.AuthorizeRequest{Request: fosite.Request{Client: &client.Client{ID: "client-id"}, Scopes: []string{"scope-a"}}}, + lph: func(t *testing.T) func(w http.ResponseWriter, r *http.Request) { + return func(w http.ResponseWriter, r *http.Request) { + lr, res, err := apiClient.GetLoginRequest(r.URL.Query().Get("login_challenge")) + require.NoError(t, err) + require.EqualValues(t, http.StatusOK, res.StatusCode) + assert.NotEmpty(t, lr.Challenge) + assert.EqualValues(t, r.URL.Query().Get("login_challenge"), lr.Challenge) + assert.EqualValues(t, "client-id", lr.Client.Id) + assert.EqualValues(t, []string{"scope-a"}, lr.RequestedScope) + assert.Contains(t, lr.RequestUrl, "/oauth2/auth?login_verifier=&consent_verifier=&") + assert.EqualValues(t, false, lr.Skip) + assert.EqualValues(t, "", lr.Subject) + assert.EqualValues(t, swagger.OpenIdConnectContext{AcrValues: nil, Display: "", UiLocales: nil}, lr.OidcContext) + w.WriteHeader(http.StatusNoContent) + } + }, + expectFinalStatusCode: http.StatusNoContent, + expectErrType: []error{ErrAbortOAuth2Request}, + expectErr: []bool{true}, + }, + { + d: "This should fail because the request was redirected but the login endpoint rejected the request", + req: fosite.AuthorizeRequest{Request: fosite.Request{Client: &client.Client{ID: "client-id"}, Scopes: []string{"scope-a"}}}, + lph: func(t *testing.T) func(w http.ResponseWriter, r *http.Request) { + return func(w http.ResponseWriter, r *http.Request) { + lr, res, err := apiClient.RejectLoginRequest(r.URL.Query().Get("login_challenge"), swagger.RejectRequest{ + Error_: fosite.ErrInteractionRequired.Name, + ErrorDebug: fosite.ErrInteractionRequired.Debug, + ErrorDescription: fosite.ErrInteractionRequired.Description, + ErrorHint: fosite.ErrInteractionRequired.Hint, + StatusCode: int64(fosite.ErrInteractionRequired.Code), + }) + require.NoError(t, err) + require.EqualValues(t, http.StatusOK, res.StatusCode) + assert.NotEmpty(t, lr.RedirectTo) + http.Redirect(w, r, lr.RedirectTo, http.StatusFound) + } + }, + expectFinalStatusCode: http.StatusBadRequest, + expectErrType: []error{ErrAbortOAuth2Request, fosite.ErrInteractionRequired}, + expectErr: []bool{true, true}, + }, + { + d: "This should fail because no cookie jar / invalid csrf", + req: fosite.AuthorizeRequest{Request: fosite.Request{Client: &client.Client{ID: "client-id"}, Scopes: []string{"scope-a"}}}, + lph: passAuthentication(apiClient, false), + cph: func(t *testing.T) func(w http.ResponseWriter, r *http.Request) { + return func(w http.ResponseWriter, r *http.Request) { + // this should never be called because csrf doesn't make it that far + require.True(t, false) + } + }, + expectFinalStatusCode: http.StatusForbidden, + expectErrType: []error{ErrAbortOAuth2Request, fosite.ErrRequestForbidden}, + expectErr: []bool{true, true}, + }, + { + d: "This should fail because consent endpoints idles after login was granted - but consent endpoint should be called because cookie jar exists", + jar: newCookieJar(), + req: fosite.AuthorizeRequest{Request: fosite.Request{Client: &client.Client{ID: "client-id"}, Scopes: []string{"scope-a"}}}, + lph: passAuthentication(apiClient, false), + cph: func(t *testing.T) func(w http.ResponseWriter, r *http.Request) { + return func(w http.ResponseWriter, r *http.Request) { + lr, res, err := apiClient.GetConsentRequest(r.URL.Query().Get("consent_challenge")) + require.NoError(t, err) + require.EqualValues(t, http.StatusOK, res.StatusCode) + assert.NotEmpty(t, lr.Challenge) + assert.EqualValues(t, r.URL.Query().Get("consent_challenge"), lr.Challenge) + assert.EqualValues(t, "client-id", lr.Client.Id) + assert.EqualValues(t, []string{"scope-a"}, lr.RequestedScope) + assert.Contains(t, lr.RequestUrl, "/oauth2/auth?login_verifier=&consent_verifier=&") + assert.EqualValues(t, false, lr.Skip) + assert.EqualValues(t, "user", lr.Subject) + assert.EqualValues(t, swagger.OpenIdConnectContext{AcrValues: nil, Display: "", UiLocales: nil}, lr.OidcContext) + w.WriteHeader(http.StatusNoContent) + } + }, + expectFinalStatusCode: http.StatusNoContent, + expectErrType: []error{ErrAbortOAuth2Request, ErrAbortOAuth2Request}, + expectErr: []bool{true, true}, + }, + { + d: "This should fail because consent verifier was set but does not exist", + jar: newCookieJar(), + cv: "invalid", + req: fosite.AuthorizeRequest{Request: fosite.Request{Client: &client.Client{ID: "client-id"}, Scopes: []string{"scope-a"}}}, + expectFinalStatusCode: http.StatusForbidden, + expectErrType: []error{fosite.ErrAccessDenied}, + expectErr: []bool{true}, + }, + { + d: "This should fail because consent endpoints denies the request after login was granted", + req: fosite.AuthorizeRequest{Request: fosite.Request{Client: &client.Client{ID: "client-id"}, Scopes: []string{"scope-a"}}}, + jar: newCookieJar(), + lph: passAuthentication(apiClient, false), + cph: func(t *testing.T) func(w http.ResponseWriter, r *http.Request) { + return func(w http.ResponseWriter, r *http.Request) { + v, res, err := apiClient.RejectConsentRequest(r.URL.Query().Get("consent_challenge"), swagger.RejectRequest{ + Error_: fosite.ErrInteractionRequired.Name, + ErrorDebug: fosite.ErrInteractionRequired.Debug, + ErrorDescription: fosite.ErrInteractionRequired.Description, + ErrorHint: fosite.ErrInteractionRequired.Hint, + StatusCode: int64(fosite.ErrInteractionRequired.Code), + }) + require.NoError(t, err) + require.EqualValues(t, http.StatusOK, res.StatusCode) + require.NotEmpty(t, v.RedirectTo) + http.Redirect(w, r, v.RedirectTo, http.StatusFound) + } + }, + expectFinalStatusCode: http.StatusBadRequest, + expectErrType: []error{ErrAbortOAuth2Request, ErrAbortOAuth2Request, fosite.ErrInteractionRequired}, + expectErr: []bool{true, true, true}, + }, + { + d: "This should pass because login and consent have been granted", + req: fosite.AuthorizeRequest{Request: fosite.Request{Client: &client.Client{ID: "client-id"}, Scopes: []string{"scope-a"}}}, + jar: newCookieJar(), + lph: passAuthentication(apiClient, false), + cph: passAuthorization(apiClient, false), + expectFinalStatusCode: http.StatusOK, + expectErrType: []error{ErrAbortOAuth2Request, ErrAbortOAuth2Request, nil}, + expectErr: []bool{true, true, false}, + expectSession: &HandledConsentRequest{ + ConsentRequest: &ConsentRequest{Subject: "user"}, + GrantedScope: []string{"scope-a"}, + Remember: false, + RememberFor: 0, + Session: &ConsentRequestSessionData{ + AccessToken: map[string]interface{}{"foo": "bar"}, + IDToken: map[string]interface{}{"bar": "baz"}, + }, + }, + }, + { + d: "This should pass because login and consent have been granted, this time we remember the decision", + req: fosite.AuthorizeRequest{Request: fosite.Request{Client: &client.Client{ID: "client-id"}, Scopes: []string{"scope-a"}}}, + jar: persistentCJ, + lph: passAuthentication(apiClient, true), + cph: passAuthorization(apiClient, true), + expectFinalStatusCode: http.StatusOK, + expectErrType: []error{ErrAbortOAuth2Request, ErrAbortOAuth2Request, nil}, + expectErr: []bool{true, true, false}, + expectSession: &HandledConsentRequest{ + ConsentRequest: &ConsentRequest{Subject: "user"}, + GrantedScope: []string{"scope-a"}, + Remember: true, + RememberFor: 0, + Session: &ConsentRequestSessionData{ + AccessToken: map[string]interface{}{"foo": "bar"}, + IDToken: map[string]interface{}{"bar": "baz"}, + }, + }, + }, + { + d: "This should pass but require consent because it's not an authorization_code flow", + req: fosite.AuthorizeRequest{ResponseTypes: fosite.Arguments{"token", "code", "id_token"}, Request: fosite.Request{Client: &client.Client{ID: "client-id"}, Scopes: []string{"scope-a"}}}, + jar: persistentCJ, + lph: func(t *testing.T) func(w http.ResponseWriter, r *http.Request) { + return func(w http.ResponseWriter, r *http.Request) { + rr, res, err := apiClient.GetLoginRequest(r.URL.Query().Get("login_challenge")) + require.NoError(t, err) + require.EqualValues(t, http.StatusOK, res.StatusCode) + assert.True(t, rr.Skip) + assert.Equal(t, "user", rr.Subject) + + v, res, err := apiClient.AcceptLoginRequest(r.URL.Query().Get("login_challenge"), swagger.AcceptLoginRequest{ + Subject: "user", + Remember: false, + RememberFor: 0, + Acr: "1", + }) + require.NoError(t, err) + require.EqualValues(t, http.StatusOK, res.StatusCode) + require.NotEmpty(t, v.RedirectTo) + http.Redirect(w, r, v.RedirectTo, http.StatusFound) + } + }, + cph: func(t *testing.T) func(w http.ResponseWriter, r *http.Request) { + return func(w http.ResponseWriter, r *http.Request) { + rr, res, err := apiClient.GetConsentRequest(r.URL.Query().Get("consent_challenge")) + require.NoError(t, err) + require.EqualValues(t, http.StatusOK, res.StatusCode) + assert.False(t, rr.Skip) + assert.Equal(t, "client-id", rr.Client.Id) + assert.Equal(t, "user", rr.Subject) + + v, res, err := apiClient.AcceptConsentRequest(r.URL.Query().Get("consent_challenge"), swagger.AcceptConsentRequest{ + GrantScope: []string{"scope-a"}, + Remember: false, + RememberFor: 0, + Session: swagger.ConsentRequestSession{ + AccessToken: map[string]interface{}{"foo": "bar"}, + IdToken: map[string]interface{}{"bar": "baz"}, + }, + }) + require.NoError(t, err) + require.EqualValues(t, http.StatusOK, res.StatusCode) + require.NotEmpty(t, v.RedirectTo) + http.Redirect(w, r, v.RedirectTo, http.StatusFound) + } + }, + expectFinalStatusCode: http.StatusOK, + expectErrType: []error{ErrAbortOAuth2Request, ErrAbortOAuth2Request, nil}, + expectErr: []bool{true, true, false}, + expectSession: &HandledConsentRequest{ + ConsentRequest: &ConsentRequest{Subject: "user"}, + GrantedScope: []string{"scope-a"}, + Remember: false, + RememberFor: 0, + Session: &ConsentRequestSessionData{ + AccessToken: map[string]interface{}{"foo": "bar"}, + IDToken: map[string]interface{}{"bar": "baz"}, + }, + }, + }, + { + d: "This should pass and confirm previous authentication and consent because it is a authorization_code", + req: fosite.AuthorizeRequest{ResponseTypes: fosite.Arguments{"code"}, Request: fosite.Request{Client: &client.Client{ID: "client-id"}, Scopes: []string{"scope-a"}}}, + jar: persistentCJ, + lph: func(t *testing.T) func(w http.ResponseWriter, r *http.Request) { + return func(w http.ResponseWriter, r *http.Request) { + rr, res, err := apiClient.GetLoginRequest(r.URL.Query().Get("login_challenge")) + require.NoError(t, err) + require.EqualValues(t, http.StatusOK, res.StatusCode) + assert.True(t, rr.Skip) + assert.Equal(t, "user", rr.Subject) + + v, res, err := apiClient.AcceptLoginRequest(r.URL.Query().Get("login_challenge"), swagger.AcceptLoginRequest{ + Subject: "user", + Remember: false, + RememberFor: 0, + Acr: "1", + }) + require.NoError(t, err) + require.EqualValues(t, http.StatusOK, res.StatusCode) + require.NotEmpty(t, v.RedirectTo) + http.Redirect(w, r, v.RedirectTo, http.StatusFound) + } + }, + cph: func(t *testing.T) func(w http.ResponseWriter, r *http.Request) { + return func(w http.ResponseWriter, r *http.Request) { + rr, res, err := apiClient.GetConsentRequest(r.URL.Query().Get("consent_challenge")) + require.NoError(t, err) + require.EqualValues(t, http.StatusOK, res.StatusCode) + assert.True(t, rr.Skip) + assert.Equal(t, "client-id", rr.Client.Id) + assert.Equal(t, "user", rr.Subject) + + v, res, err := apiClient.AcceptConsentRequest(r.URL.Query().Get("consent_challenge"), swagger.AcceptConsentRequest{ + GrantScope: []string{"scope-a"}, + Remember: false, + RememberFor: 0, + Session: swagger.ConsentRequestSession{ + AccessToken: map[string]interface{}{"foo": "bar"}, + IdToken: map[string]interface{}{"bar": "baz"}, + }, + }) + require.NoError(t, err) + require.EqualValues(t, http.StatusOK, res.StatusCode) + require.NotEmpty(t, v.RedirectTo) + http.Redirect(w, r, v.RedirectTo, http.StatusFound) + } + }, + expectFinalStatusCode: http.StatusOK, + expectErrType: []error{ErrAbortOAuth2Request, ErrAbortOAuth2Request, nil}, + expectErr: []bool{true, true, false}, + expectSession: &HandledConsentRequest{ + ConsentRequest: &ConsentRequest{Subject: "user"}, + GrantedScope: []string{"scope-a"}, + Remember: false, + RememberFor: 0, + Session: &ConsentRequestSessionData{ + AccessToken: map[string]interface{}{"foo": "bar"}, + IDToken: map[string]interface{}{"bar": "baz"}, + }, + }, + }, + } { + t.Run(fmt.Sprintf("case=%d", k), func(t *testing.T) { + if tc.lph != nil { + lph = tc.lph(t) + } else { + lph = noopHandler(t) + } + + if tc.cph != nil { + cph = tc.cph(t) + } else { + cph = noopHandler(t) + } + + calls := 0 + aph = func(w http.ResponseWriter, r *http.Request) { + require.True(t, len(tc.expectErrType) >= calls+1, "%d (expect) < %d (got)", len(tc.expectErrType), calls+1) + require.True(t, len(tc.expectErr) >= calls+1, "%d (expect) < %d (got)", len(tc.expectErr), calls+1) + require.NoError(t, r.ParseForm()) + tc.req.Form = r.Form + + c, err := strategy.HandleOAuth2AuthorizationRequest(w, r, &tc.req) + t.Logf("DefaultStrategy returned:\n\t%+v\n\t%s", c, err) + + if tc.expectErr[calls] { + assert.Error(t, err) + if tc.expectErrType[calls] != nil { + assert.EqualError(t, err, tc.expectErrType[calls].Error()) + } + } else { + require.NoError(t, err) + if tc.expectSession != nil { + require.NotNil(t, c) + assert.EqualValues(t, tc.expectSession.GrantedScope, c.GrantedScope) + assert.EqualValues(t, tc.expectSession.Remember, c.Remember) + assert.EqualValues(t, tc.expectSession.RememberFor, c.RememberFor) + assert.EqualValues(t, tc.expectSession.ConsentRequest.Subject, c.ConsentRequest.Subject) + } + } + + calls++ + if errors.Cause(err) == ErrAbortOAuth2Request { + // nothing to do, indicates redirect + } else if err != nil { + writer.WriteError(w, r, err) + } else { + writer.Write(w, r, c) + } + } + + cl := &http.Client{ + Jar: tc.jar, + } + resp, err := cl.Get( + ap.URL + "?" + + "login_verifier=" + tc.lv + "&" + + "consent_verifier=" + tc.cv + "&", + ) + require.NoError(t, err) + resp.Body.Close() + assert.EqualValues(t, tc.expectFinalStatusCode, resp.StatusCode) + }) + } +} diff --git a/consent/strategy_test_helper.go b/consent/strategy_test_helper.go new file mode 100644 index 00000000000..5a75183b8fb --- /dev/null +++ b/consent/strategy_test_helper.go @@ -0,0 +1,66 @@ +/* + * Copyright © 2015-2018 Aeneas Rekkas + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * @author Aeneas Rekkas + * @Copyright 2017-2018 Aeneas Rekkas + * @license Apache-2.0 + */ + +package consent + +import ( + "net/http" + "testing" + + "github.com/ory/hydra/sdk/go/hydra/swagger" + "github.com/stretchr/testify/require" +) + +var passAuthentication = func(apiClient *swagger.OAuth2Api, remember bool) func(t *testing.T) func(w http.ResponseWriter, r *http.Request) { + return func(t *testing.T) func(w http.ResponseWriter, r *http.Request) { + return func(w http.ResponseWriter, r *http.Request) { + v, res, err := apiClient.AcceptLoginRequest(r.URL.Query().Get("login_challenge"), swagger.AcceptLoginRequest{ + Subject: "user", + Remember: remember, + RememberFor: 0, + Acr: "1", + }) + require.NoError(t, err) + require.EqualValues(t, http.StatusOK, res.StatusCode) + require.NotEmpty(t, v.RedirectTo) + http.Redirect(w, r, v.RedirectTo, http.StatusFound) + } + } +} + +var passAuthorization = func(apiClient *swagger.OAuth2Api, remember bool) func(t *testing.T) func(w http.ResponseWriter, r *http.Request) { + return func(t *testing.T) func(w http.ResponseWriter, r *http.Request) { + return func(w http.ResponseWriter, r *http.Request) { + v, res, err := apiClient.AcceptConsentRequest(r.URL.Query().Get("consent_challenge"), swagger.AcceptConsentRequest{ + GrantScope: []string{"scope-a"}, + Remember: remember, + RememberFor: 0, + Session: swagger.ConsentRequestSession{ + AccessToken: map[string]interface{}{"foo": "bar"}, + IdToken: map[string]interface{}{"bar": "baz"}, + }, + }) + require.NoError(t, err) + require.EqualValues(t, http.StatusOK, res.StatusCode) + require.NotEmpty(t, v.RedirectTo) + http.Redirect(w, r, v.RedirectTo, http.StatusFound) + } + } +} diff --git a/consent/types.go b/consent/types.go new file mode 100644 index 00000000000..86df2c43576 --- /dev/null +++ b/consent/types.go @@ -0,0 +1,257 @@ +/* + * Copyright © 2015-2018 Aeneas Rekkas + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * @author Aeneas Rekkas + * @Copyright 2017-2018 Aeneas Rekkas + * @license Apache-2.0 + */ + +package consent + +import ( + "time" + + "github.com/ory/fosite" + "github.com/ory/hydra/client" +) + +// The response payload sent when accepting or rejecting a login or consent request. +// +// swagger:model completedRequest +type RequestHandlerResponse struct { + // RedirectURL is the URL which you should redirect the user to once the authentication process is completed. + RedirectTo string `json:"redirect_to"` +} + +type AuthenticationSession struct { + ID string `db:"id"` + AuthenticatedAt time.Time `db:"authenticated_at"` + Subject string `db:"subject"` +} + +// The request payload used to accept a login or consent request. +// +// swagger:model rejectRequest +type RequestDeniedError struct { + Name string `json:"error"` + Description string `json:"error_description"` + Hint string `json:"error_hint,omitempty"` + Code int `json:"status_code,omitempty"` + Debug string `json:"error_debug,omitempty"` +} + +func (e *RequestDeniedError) toRFCError() *fosite.RFC6749Error { + if e.Name == "" { + e.Name = fosite.ErrInvalidRequest.Name + } + if e.Code == 0 { + e.Code = fosite.ErrInvalidRequest.Code + } + if e.Description == "" { + e.Description = fosite.ErrInvalidRequest.Description + } + if e.Hint == "" { + e.Hint = fosite.ErrInvalidRequest.Hint + } + if e.Debug == "" { + e.Debug = fosite.ErrInvalidRequest.Debug + } + + return &fosite.RFC6749Error{ + Name: e.Name, + Description: e.Description, + Hint: e.Hint, + Code: e.Code, + Debug: e.Debug, + } +} + +// The request payload used to accept a consent request. +// +// swagger:model acceptConsentRequest +type HandledConsentRequest struct { + // GrantScope sets the scope the user authorized the client to use. Should be a subset of `requested_scope` + GrantedScope []string `json:"grant_scope"` + + // Session allows you to set (optional) session data for access and ID tokens. + Session *ConsentRequestSessionData `json:"session"` + + // Remember, if set to true, tells ORY Hydra to remember this consent authorization and reuse it if the same + // client asks the same user for the same, or a subset of, scope. + Remember bool `json:"remember"` + + // RememberFor sets how long the consent authorization should be remembered for in seconds. If set to `0`, the + // authorization will be remembered indefinitely. + RememberFor int `json:"remember_for"` + + ConsentRequest *ConsentRequest `json:"-"` + Error *RequestDeniedError `json:"-"` + Challenge string `json:"-"` + RequestedAt time.Time `json:"-"` + WasUsed bool `json:"-"` +} + +// The request payload used to accept a login request. +// +// swagger:model acceptLoginRequest +type HandledAuthenticationRequest struct { + // Remember, if set to true, tells ORY Hydra to remember this user by telling the user agent (browser) to store + // a cookie with authentication data. If the same user performs another OAuth 2.0 Authorization Request, he/she + // will not be asked to log in again. + Remember bool `json:"remember"` + + // RememberFor sets how long the authentication should be remembered for in seconds. If set to `0`, the + // authorization will be remembered indefinitely. + RememberFor int `json:"remember_for"` + + // ACR sets the Authentication AuthorizationContext Class Reference value for this authentication session. You can use it + // to express that, for example, a user authenticated using two factor authentication. + ACR string `json:"acr"` + + // Subject is the user ID of the end-user that authenticated. + Subject string `json:"subject"` + + AuthenticationRequest *AuthenticationRequest `json:"-"` + Error *RequestDeniedError `json:"-"` + Challenge string `json:"-"` + RequestedAt time.Time `json:"-"` + WasUsed bool `json:"-"` +} + +// Contains optional information about the OpenID Connect request. +// +// swagger:model openIDConnectContext +type OpenIDConnectContext struct { + // ACRValues is the Authentication AuthorizationContext Class Reference requested in the OAuth 2.0 Authorization request. + // It is a parameter defined by OpenID Connect and expresses which level of authentication (e.g. 2FA) is required. + // + // OpenID Connect defines it as follows: + // > Requested Authentication AuthorizationContext Class Reference values. Space-separated string that specifies the acr values + // that the Authorization Server is being requested to use for processing this Authentication Request, with the + // values appearing in order of preference. The Authentication AuthorizationContext Class satisfied by the authentication + // performed is returned as the acr Claim Value, as specified in Section 2. The acr Claim is requested as a + // Voluntary Claim by this parameter. + ACRValues []string `json:"acr_values,omitempty"` + + // UILocales is the End-User'id preferred languages and scripts for the user interface, represented as a + // space-separated list of BCP47 [RFC5646] language tag values, ordered by preference. For instance, the value + // "fr-CA fr en" represents a preference for French as spoken in Canada, then French (without a region designation), + // followed by English (without a region designation). An error SHOULD NOT result if some or all of the requested + // locales are not supported by the OpenID Provider. + UILocales []string `json:"ui_locales,omitempty"` + + // Display is a string value that specifies how the Authorization Server displays the authentication and consent user interface pages to the End-User. + // The defined values are: + // - page: The Authorization Server SHOULD display the authentication and consent UI consistent with a full User Agent page view. If the display parameter is not specified, this is the default display mode. + // - popup: The Authorization Server SHOULD display the authentication and consent UI consistent with a popup User Agent window. The popup User Agent window should be of an appropriate size for a login-focused dialog and should not obscure the entire window that it is popping up over. + // - touch: The Authorization Server SHOULD display the authentication and consent UI consistent with a device that leverages a touch interface. + // - wap: The Authorization Server SHOULD display the authentication and consent UI consistent with a "feature phone" type display. + // + // The Authorization Server MAY also attempt to detect the capabilities of the User Agent and present an appropriate display. + Display string `json:"display,omitempty"` + + // not supported + //LoginHint string `json:"login_hint,omitempty"` +} + +// Contains information on an ongoing login request. +// +// swagger:model loginRequest +type AuthenticationRequest struct { + // Challenge is the identifier ("authentication challenge") of the consent authentication request. It is used to + // identify the session. + Challenge string `json:"challenge"` + + // RequestedScope contains all scopes requested by the OAuth 2.0 client. + RequestedScope []string `json:"requested_scope"` + + // Skip, if true, implies that the client has requested the same scopes from the same user previously. + // If true, you can skip asking the user to grant the requested scopes, and simply forward the user to the redirect URL. + // + // This feature allows you to update / set session information. + Skip bool `json:"skip"` + + // Subject is the user ID of the end-user that authenticated. Now, that end user needs to grant or deny the scope + // requested by the OAuth 2.0 client. + Subject string `json:"subject"` + + // OpenIDConnectContext provides context for the (potential) OpenID Connect context. Implementation of these + // values in your app are optional but can be useful if you want to be fully compliant with the OpenID Connect spec. + OpenIDConnectContext *OpenIDConnectContext `json:"oidc_context"` + + // Client is the OAuth 2.0 Client that initiated the request. + Client *client.Client `json:"client"` + + // RequestURL is the original OAuth 2.0 Authorization URL requested by the OAuth 2.0 client. It is the URL which + // initiates the OAuth 2.0 Authorization Code or OAuth 2.0 Implicit flow. This URL is typically not needed, but + // might come in handy if you want to deal with additional request parameters. + RequestURL string `json:"request_url"` + + Verifier string `json:"-"` + CSRF string `json:"-"` +} + +// Contains information on an ongoing consent request. +// +// swagger:model consentRequest +type ConsentRequest struct { + // Challenge is the identifier ("authorization challenge") of the consent authorization request. It is used to + // identify the session. + Challenge string `json:"challenge"` + + // RequestedScope contains all scopes requested by the OAuth 2.0 client. + RequestedScope []string `json:"requested_scope"` + + // Skip, if true, implies that the client has requested the same scopes from the same user previously. + // If true, you must not ask the user to grant the requested scopes. You must however either allow or deny the + // consent request using the usual API call. + Skip bool `json:"skip"` + + // Subject is the user ID of the end-user that authenticated. Now, that end user needs to grant or deny the scope + // requested by the OAuth 2.0 client. + Subject string `json:"subject"` + + // OpenIDConnectContext provides context for the (potential) OpenID Connect context. Implementation of these + // values in your app are optional but can be useful if you want to be fully compliant with the OpenID Connect spec. + OpenIDConnectContext *OpenIDConnectContext `json:"oidc_context"` + + // Client is the OAuth 2.0 Client that initiated the request. + Client *client.Client `json:"client"` + + // RequestURL is the original OAuth 2.0 Authorization URL requested by the OAuth 2.0 client. It is the URL which + // initiates the OAuth 2.0 Authorization Code or OAuth 2.0 Implicit flow. This URL is typically not needed, but + // might come in handy if you want to deal with additional request parameters. + RequestURL string `json:"request_url"` + + Verifier string `json:"-"` + CSRF string `json:"-"` +} + +// Used to pass session data to a consent request. +// +// swagger:model consentRequestSession +type ConsentRequestSessionData struct { + // AccessToken sets session data for the access and refresh token, as well as any future tokens issued by the + // refresh grant. Keep in mind that this data will be available to anyone performing OAuth 2.0 Challenge Introspection. + // If only your services can perform OAuth 2.0 Challenge Introspection, this is usually fine. But if third parties + // can access that endpoint as well, sensitive data from the session might be exposed to them. Use with care! + AccessToken map[string]interface{} `json:"access_token"` + + // IDToken sets session data for the OpenID Connect ID token. Keep in mind that the session'id payloads are readable + // by anyone that has access to the ID Challenge. Use with care! + IDToken map[string]interface{} `json:"id_token"` + + //UserInfo map[string]interface{} `json:"userinfo"` +} diff --git a/docs/api.swagger.json b/docs/api.swagger.json index 28ab16e5b85..2301d279777 100644 --- a/docs/api.swagger.json +++ b/docs/api.swagger.json @@ -29,14 +29,7 @@ "paths": { "/.well-known/jwks.json": { "get": { - "security": [ - { - "oauth2": [ - "hydra.keys.get" - ] - } - ], - "description": "Returns metadata for discovering important JSON Web Keys. Currently, this endpoint returns the public key for verifying OpenID Connect ID Tokens.\n\nA JSON Web Key (JWK) is a JavaScript Object Notation (JSON) data structure that represents a cryptographic key. A JWK Set is a JSON data structure that represents a set of JWKs. A JSON Web Key is identified by its set and key id. ORY Hydra uses this functionality to store cryptographic keys used for TLS and JSON Web Tokens (such as OpenID Connect ID tokens), and allows storing user-defined keys as well.\n\nThe subject making the request needs to be assigned to a policy containing:\n\n```\n{\n\"resources\": [\"rn:hydra:keys:hydra.openid.id-token:public\"],\n\"actions\": [\"GET\"],\n\"effect\": \"allow\"\n}\n```", + "description": "Returns metadata for discovering important JSON Web Keys. Currently, this endpoint returns the public key for verifying OpenID Connect ID Tokens.\n\nA JSON Web Key (JWK) is a JavaScript Object Notation (JSON) data structure that represents a cryptographic key. A JWK Set is a JSON data structure that represents a set of JWKs. A JSON Web Key is identified by its set and key id. ORY Hydra uses this functionality to store cryptographic keys used for TLS and JSON Web Tokens (such as OpenID Connect ID tokens), and allows storing user-defined keys as well.", "consumes": [ "application/json" ], @@ -104,14 +97,7 @@ }, "/clients": { "get": { - "security": [ - { - "oauth2": [ - "hydra.clients" - ] - } - ], - "description": "This endpoint lists all clients in the database, and never returns client secrets.\n\nOAuth 2.0 clients are used to perform OAuth 2.0 and OpenID Connect flows. Usually, OAuth 2.0 clients are generated for applications which want to consume your OAuth 2.0 or OpenID Connect capabilities. To manage ORY Hydra, you will need an OAuth 2.0 Client as well. Make sure that this endpoint is well protected and only callable by first-party components.\n\nThe subject making the request needs to be assigned to a policy containing:\n\n```\n{\n\"resources\": [\"rn:hydra:clients\"],\n\"actions\": [\"get\"],\n\"effect\": \"allow\"\n}\n```", + "description": "This endpoint lists all clients in the database, and never returns client secrets.\n\nOAuth 2.0 clients are used to perform OAuth 2.0 and OpenID Connect flows. Usually, OAuth 2.0 clients are generated for applications which want to consume your OAuth 2.0 or OpenID Connect capabilities. To manage ORY Hydra, you will need an OAuth 2.0 Client as well. Make sure that this endpoint is well protected and only callable by first-party components.", "consumes": [ "application/json" ], @@ -161,14 +147,7 @@ } }, "post": { - "security": [ - { - "oauth2": [ - "hydra.clients" - ] - } - ], - "description": "Create a new OAuth 2.0 client If you pass `client_secret` the secret will be used, otherwise a random secret will be generated. The secret will be returned in the response and you will not be able to retrieve it later on. Write the secret down and keep it somwhere safe.\n\nOAuth 2.0 clients are used to perform OAuth 2.0 and OpenID Connect flows. Usually, OAuth 2.0 clients are generated for applications which want to consume your OAuth 2.0 or OpenID Connect capabilities. To manage ORY Hydra, you will need an OAuth 2.0 Client as well. Make sure that this endpoint is well protected and only callable by first-party components.\n\nThe subject making the request needs to be assigned to a policy containing:\n\n```\n{\n\"resources\": [\"rn:hydra:clients\"],\n\"actions\": [\"create\"],\n\"effect\": \"allow\"\n}\n```\n\nAdditionally, the context key \"owner\" is set to the owner of the client, allowing policies such as:\n\n```\n{\n\"resources\": [\"rn:hydra:clients\"],\n\"actions\": [\"create\"],\n\"effect\": \"allow\",\n\"conditions\": { \"owner\": { \"type\": \"EqualsSubjectCondition\" } }\n}\n```", + "description": "Create a new OAuth 2.0 client If you pass `client_secret` the secret will be used, otherwise a random secret will be generated. The secret will be returned in the response and you will not be able to retrieve it later on. Write the secret down and keep it somwhere safe.\n\nOAuth 2.0 clients are used to perform OAuth 2.0 and OpenID Connect flows. Usually, OAuth 2.0 clients are generated for applications which want to consume your OAuth 2.0 or OpenID Connect capabilities. To manage ORY Hydra, you will need an OAuth 2.0 Client as well. Make sure that this endpoint is well protected and only callable by first-party components.\n\nAdditionally, the context key \"owner\" is set to the owner of the client, allowing policies such as:\n\n```\n{\n\"resources\": [\"rn:hydra:clients\"],\n\"actions\": [\"create\"],\n\"effect\": \"allow\",\n\"conditions\": { \"owner\": { \"type\": \"EqualsSubjectCondition\" } }\n}\n```", "consumes": [ "application/json" ], @@ -215,14 +194,7 @@ }, "/clients/{id}": { "get": { - "security": [ - { - "oauth2": [ - "hydra.clients" - ] - } - ], - "description": "Get an OAUth 2.0 client by its ID. This endpoint never returns passwords.\n\nOAuth 2.0 clients are used to perform OAuth 2.0 and OpenID Connect flows. Usually, OAuth 2.0 clients are generated for applications which want to consume your OAuth 2.0 or OpenID Connect capabilities. To manage ORY Hydra, you will need an OAuth 2.0 Client as well. Make sure that this endpoint is well protected and only callable by first-party components.\n\nThe subject making the request needs to be assigned to a policy containing:\n\n```\n{\n\"resources\": [\"rn:hydra:clients:\u003csome-id\u003e\"],\n\"actions\": [\"get\"],\n\"effect\": \"allow\"\n}\n```\n\nAdditionally, the context key \"owner\" is set to the owner of the client, allowing policies such as:\n\n```\n{\n\"resources\": [\"rn:hydra:clients:\u003csome-id\u003e\"],\n\"actions\": [\"get\"],\n\"effect\": \"allow\",\n\"conditions\": { \"owner\": { \"type\": \"EqualsSubjectCondition\" } }\n}\n```", + "description": "Get an OAUth 2.0 client by its ID. This endpoint never returns passwords.\n\nOAuth 2.0 clients are used to perform OAuth 2.0 and OpenID Connect flows. Usually, OAuth 2.0 clients are generated for applications which want to consume your OAuth 2.0 or OpenID Connect capabilities. To manage ORY Hydra, you will need an OAuth 2.0 Client as well. Make sure that this endpoint is well protected and only callable by first-party components.", "consumes": [ "application/json" ], @@ -268,14 +240,7 @@ } }, "put": { - "security": [ - { - "oauth2": [ - "hydra.clients" - ] - } - ], - "description": "Update an existing OAuth 2.0 Client. If you pass `client_secret` the secret will be updated and returned via the API. This is the only time you will be able to retrieve the client secret, so write it down and keep it safe.\n\nOAuth 2.0 clients are used to perform OAuth 2.0 and OpenID Connect flows. Usually, OAuth 2.0 clients are generated for applications which want to consume your OAuth 2.0 or OpenID Connect capabilities. To manage ORY Hydra, you will need an OAuth 2.0 Client as well. Make sure that this endpoint is well protected and only callable by first-party components.\n\nThe subject making the request needs to be assigned to a policy containing:\n\n```\n{\n\"resources\": [\"rn:hydra:clients\"],\n\"actions\": [\"update\"],\n\"effect\": \"allow\"\n}\n```\n\nAdditionally, the context key \"owner\" is set to the owner of the client, allowing policies such as:\n\n```\n{\n\"resources\": [\"rn:hydra:clients\"],\n\"actions\": [\"update\"],\n\"effect\": \"allow\",\n\"conditions\": { \"owner\": { \"type\": \"EqualsSubjectCondition\" } }\n}\n```", + "description": "Update an existing OAuth 2.0 Client. If you pass `client_secret` the secret will be updated and returned via the API. This is the only time you will be able to retrieve the client secret, so write it down and keep it safe.\n\nOAuth 2.0 clients are used to perform OAuth 2.0 and OpenID Connect flows. Usually, OAuth 2.0 clients are generated for applications which want to consume your OAuth 2.0 or OpenID Connect capabilities. To manage ORY Hydra, you will need an OAuth 2.0 Client as well. Make sure that this endpoint is well protected and only callable by first-party components.", "consumes": [ "application/json" ], @@ -327,14 +292,7 @@ } }, "delete": { - "security": [ - { - "oauth2": [ - "hydra.clients" - ] - } - ], - "description": "Delete an existing OAuth 2.0 Client by its ID.\n\nOAuth 2.0 clients are used to perform OAuth 2.0 and OpenID Connect flows. Usually, OAuth 2.0 clients are generated for applications which want to consume your OAuth 2.0 or OpenID Connect capabilities. To manage ORY Hydra, you will need an OAuth 2.0 Client as well. Make sure that this endpoint is well protected and only callable by first-party components.\n\nThe subject making the request needs to be assigned to a policy containing:\n\n```\n{\n\"resources\": [\"rn:hydra:clients:\u003csome-id\u003e\"],\n\"actions\": [\"delete\"],\n\"effect\": \"allow\"\n}\n```\n\nAdditionally, the context key \"owner\" is set to the owner of the client, allowing policies such as:\n\n```\n{\n\"resources\": [\"rn:hydra:clients:\u003csome-id\u003e\"],\n\"actions\": [\"delete\"],\n\"effect\": \"allow\",\n\"conditions\": { \"owner\": { \"type\": \"EqualsSubjectCondition\" } }\n}\n```", + "description": "Delete an existing OAuth 2.0 Client by its ID.\n\nOAuth 2.0 clients are used to perform OAuth 2.0 and OpenID Connect flows. Usually, OAuth 2.0 clients are generated for applications which want to consume your OAuth 2.0 or OpenID Connect capabilities. To manage ORY Hydra, you will need an OAuth 2.0 Client as well. Make sure that this endpoint is well protected and only callable by first-party components.", "consumes": [ "application/json" ], @@ -397,14 +355,7 @@ }, "/keys/{set}": { "get": { - "security": [ - { - "oauth2": [ - "hydra.keys.get" - ] - } - ], - "description": "This endpoint can be used to retrieve JWK Sets stored in ORY Hydra.\n\nA JSON Web Key (JWK) is a JavaScript Object Notation (JSON) data structure that represents a cryptographic key. A JWK Set is a JSON data structure that represents a set of JWKs. A JSON Web Key is identified by its set and key id. ORY Hydra uses this functionality to store cryptographic keys used for TLS and JSON Web Tokens (such as OpenID Connect ID tokens), and allows storing user-defined keys as well.\n\nThe subject making the request needs to be assigned to a policy containing:\n\n```\n{\n\"resources\": [\"rn:hydra:keys:\u003cset\u003e:\u003ckid\u003e\"],\n\"actions\": [\"get\"],\n\"effect\": \"allow\"\n}\n```", + "description": "This endpoint can be used to retrieve JWK Sets stored in ORY Hydra.\n\nA JSON Web Key (JWK) is a JavaScript Object Notation (JSON) data structure that represents a cryptographic key. A JWK Set is a JSON data structure that represents a set of JWKs. A JSON Web Key is identified by its set and key id. ORY Hydra uses this functionality to store cryptographic keys used for TLS and JSON Web Tokens (such as OpenID Connect ID tokens), and allows storing user-defined keys as well.", "consumes": [ "application/json" ], @@ -449,14 +400,7 @@ } }, "put": { - "security": [ - { - "oauth2": [ - "hydra.keys.update" - ] - } - ], - "description": "Use this method if you do not want to let Hydra generate the JWKs for you, but instead save your own.\n\nA JSON Web Key (JWK) is a JavaScript Object Notation (JSON) data structure that represents a cryptographic key. A JWK Set is a JSON data structure that represents a set of JWKs. A JSON Web Key is identified by its set and key id. ORY Hydra uses this functionality to store cryptographic keys used for TLS and JSON Web Tokens (such as OpenID Connect ID tokens), and allows storing user-defined keys as well.\n\nThe subject making the request needs to be assigned to a policy containing:\n\n```\n{\n\"resources\": [\"rn:hydra:keys:\u003cset\u003e\"],\n\"actions\": [\"update\"],\n\"effect\": \"allow\"\n}\n```", + "description": "Use this method if you do not want to let Hydra generate the JWKs for you, but instead save your own.\n\nA JSON Web Key (JWK) is a JavaScript Object Notation (JSON) data structure that represents a cryptographic key. A JWK Set is a JSON data structure that represents a set of JWKs. A JSON Web Key is identified by its set and key id. ORY Hydra uses this functionality to store cryptographic keys used for TLS and JSON Web Tokens (such as OpenID Connect ID tokens), and allows storing user-defined keys as well.", "consumes": [ "application/json" ], @@ -508,14 +452,7 @@ } }, "post": { - "security": [ - { - "oauth2": [ - "hydra.keys.create" - ] - } - ], - "description": "This endpoint is capable of generating JSON Web Key Sets for you. There a different strategies available, such as symmetric cryptographic keys (HS256, HS512) and asymetric cryptographic keys (RS256, ECDSA). If the specified JSON Web Key Set does not exist, it will be created.\n\nA JSON Web Key (JWK) is a JavaScript Object Notation (JSON) data structure that represents a cryptographic key. A JWK Set is a JSON data structure that represents a set of JWKs. A JSON Web Key is identified by its set and key id. ORY Hydra uses this functionality to store cryptographic keys used for TLS and JSON Web Tokens (such as OpenID Connect ID tokens), and allows storing user-defined keys as well.\n\nThe subject making the request needs to be assigned to a policy containing:\n\n```\n{\n\"resources\": [\"rn:hydra:keys:\u003cset\u003e:\u003ckid\u003e\"],\n\"actions\": [\"create\"],\n\"effect\": \"allow\"\n}\n```", + "description": "This endpoint is capable of generating JSON Web Key Sets for you. There a different strategies available, such as symmetric cryptographic keys (HS256, HS512) and asymetric cryptographic keys (RS256, ECDSA). If the specified JSON Web Key Set does not exist, it will be created.\n\nA JSON Web Key (JWK) is a JavaScript Object Notation (JSON) data structure that represents a cryptographic key. A JWK Set is a JSON data structure that represents a set of JWKs. A JSON Web Key is identified by its set and key id. ORY Hydra uses this functionality to store cryptographic keys used for TLS and JSON Web Tokens (such as OpenID Connect ID tokens), and allows storing user-defined keys as well.", "consumes": [ "application/json" ], @@ -567,14 +504,7 @@ } }, "delete": { - "security": [ - { - "oauth2": [ - "hydra.keys.delete" - ] - } - ], - "description": "Use this endpoint to delete a complete JSON Web Key Set and all the keys in that set.\n\nA JSON Web Key (JWK) is a JavaScript Object Notation (JSON) data structure that represents a cryptographic key. A JWK Set is a JSON data structure that represents a set of JWKs. A JSON Web Key is identified by its set and key id. ORY Hydra uses this functionality to store cryptographic keys used for TLS and JSON Web Tokens (such as OpenID Connect ID tokens), and allows storing user-defined keys as well.\n\nThe subject making the request needs to be assigned to a policy containing:\n\n```\n{\n\"resources\": [\"rn:hydra:keys:\u003cset\u003e\"],\n\"actions\": [\"delete\"],\n\"effect\": \"allow\"\n}\n```", + "description": "Use this endpoint to delete a complete JSON Web Key Set and all the keys in that set.\n\nA JSON Web Key (JWK) is a JavaScript Object Notation (JSON) data structure that represents a cryptographic key. A JWK Set is a JSON data structure that represents a set of JWKs. A JSON Web Key is identified by its set and key id. ORY Hydra uses this functionality to store cryptographic keys used for TLS and JSON Web Tokens (such as OpenID Connect ID tokens), and allows storing user-defined keys as well.", "consumes": [ "application/json" ], @@ -618,14 +548,7 @@ }, "/keys/{set}/{kid}": { "get": { - "security": [ - { - "oauth2": [ - "hydra.keys.get" - ] - } - ], - "description": "This endpoint can be used to retrieve JWKs stored in ORY Hydra.\n\nA JSON Web Key (JWK) is a JavaScript Object Notation (JSON) data structure that represents a cryptographic key. A JWK Set is a JSON data structure that represents a set of JWKs. A JSON Web Key is identified by its set and key id. ORY Hydra uses this functionality to store cryptographic keys used for TLS and JSON Web Tokens (such as OpenID Connect ID tokens), and allows storing user-defined keys as well.\n\nThe subject making the request needs to be assigned to a policy containing:\n\n```\n{\n\"resources\": [\"rn:hydra:keys:\u003cset\u003e:\u003ckid\u003e\"],\n\"actions\": [\"get\"],\n\"effect\": \"allow\"\n}\n```", + "description": "This endpoint can be used to retrieve JWKs stored in ORY Hydra.\n\nA JSON Web Key (JWK) is a JavaScript Object Notation (JSON) data structure that represents a cryptographic key. A JWK Set is a JSON data structure that represents a set of JWKs. A JSON Web Key is identified by its set and key id. ORY Hydra uses this functionality to store cryptographic keys used for TLS and JSON Web Tokens (such as OpenID Connect ID tokens), and allows storing user-defined keys as well.", "consumes": [ "application/json" ], @@ -678,14 +601,7 @@ } }, "put": { - "security": [ - { - "oauth2": [ - "hydra.keys.update" - ] - } - ], - "description": "Use this method if you do not want to let Hydra generate the JWKs for you, but instead save your own.\n\nA JSON Web Key (JWK) is a JavaScript Object Notation (JSON) data structure that represents a cryptographic key. A JWK Set is a JSON data structure that represents a set of JWKs. A JSON Web Key is identified by its set and key id. ORY Hydra uses this functionality to store cryptographic keys used for TLS and JSON Web Tokens (such as OpenID Connect ID tokens), and allows storing user-defined keys as well.\n\nThe subject making the request needs to be assigned to a policy containing:\n\n```\n{\n\"resources\": [\"rn:hydra:keys:\u003cset\u003e:\u003ckid\u003e\"],\n\"actions\": [\"update\"],\n\"effect\": \"allow\"\n}\n```", + "description": "Use this method if you do not want to let Hydra generate the JWKs for you, but instead save your own.\n\nA JSON Web Key (JWK) is a JavaScript Object Notation (JSON) data structure that represents a cryptographic key. A JWK Set is a JSON data structure that represents a set of JWKs. A JSON Web Key is identified by its set and key id. ORY Hydra uses this functionality to store cryptographic keys used for TLS and JSON Web Tokens (such as OpenID Connect ID tokens), and allows storing user-defined keys as well.", "consumes": [ "application/json" ], @@ -745,14 +661,7 @@ } }, "delete": { - "security": [ - { - "oauth2": [ - "hydra.keys.delete" - ] - } - ], - "description": "Use this endpoint to delete a single JSON Web Key.\n\nA JSON Web Key (JWK) is a JavaScript Object Notation (JSON) data structure that represents a cryptographic key. A JWK Set is a JSON data structure that represents a set of JWKs. A JSON Web Key is identified by its set and key id. ORY Hydra uses this functionality to store cryptographic keys used for TLS and JSON Web Tokens (such as OpenID Connect ID tokens), and allows storing user-defined keys as well.\n\nThe subject making the request needs to be assigned to a policy containing:\n\n```\n{\n\"resources\": [\"rn:hydra:keys:\u003cset\u003e:\u003ckid\u003e\"],\n\"actions\": [\"delete\"],\n\"effect\": \"allow\"\n}\n```", + "description": "Use this endpoint to delete a single JSON Web Key.\n\nA JSON Web Key (JWK) is a JavaScript Object Notation (JSON) data structure that represents a cryptographic key. A JWK Set is a JSON data structure that represents a set of JWKs. A JSON Web Key is identified by its set and key id. ORY Hydra uses this functionality to store cryptographic keys used for TLS and JSON Web Tokens (such as OpenID Connect ID tokens), and allows storing user-defined keys as well.", "consumes": [ "application/json" ], @@ -830,16 +739,9 @@ } } }, - "/oauth2/consent/requests/{id}": { + "/oauth2/auth/requests/consent/{challenge}": { "get": { - "security": [ - { - "oauth2": [ - "hydra.consent" - ] - } - ], - "description": "Call this endpoint to receive information on consent requests. The consent request id is usually transmitted via the URL query `consent`.\nFor example: `http://consent-app.mydomain.com/?consent=1234abcd`\n\n\nThe subject making the request needs to be assigned to a policy containing:\n\n```\n{\n\"resources\": [\"rn:hydra:oauth2:consent:requests:\u003crequest-id\u003e\"],\n\"actions\": [\"get\"],\n\"effect\": \"allow\"\n}\n```", + "description": "When an authorization code, hybrid, or implicit OAuth 2.0 Flow is initiated, ORY Hydra asks the login provider\nto authenticate the user and then tell ORY Hydra now about it. If the user authenticated, he/she must now be asked if\nthe OAuth 2.0 Client which initiated the flow should be allowed to access the resources on the user's behalf.\n\nThe consent provider which handles this request and is a web app implemented and hosted by you. It shows a user interface which asks the user to\ngrant or deny the client access to the requested scope (\"Application my-dropbox-app wants write access to all your private files\").\n\nThe consent challenge is appended to the consent provider's URL to which the user's user-agent (browser) is redirected to. The consent\nprovider uses that challenge to fetch information on the OAuth2 request and then tells ORY Hydra if the user accepted\nor rejected the request.", "consumes": [ "application/json" ], @@ -853,24 +755,22 @@ "tags": [ "oAuth2" ], - "summary": "Receive consent request information", - "operationId": "getOAuth2ConsentRequest", + "summary": "Get consent request information", + "operationId": "getConsentRequest", "parameters": [ { - "uniqueItems": true, "type": "string", - "x-go-name": "ID", - "description": "The id of the OAuth 2.0 Consent Request.", - "name": "id", + "x-go-name": "Challenge", + "name": "challenge", "in": "path", "required": true } ], "responses": { "200": { - "description": "oAuth2ConsentRequest", + "description": "consentRequest", "schema": { - "$ref": "#/definitions/oAuth2ConsentRequest" + "$ref": "#/definitions/consentRequest" } }, "401": { @@ -882,16 +782,59 @@ } } }, - "/oauth2/consent/requests/{id}/accept": { - "patch": { - "security": [ + "/oauth2/auth/requests/consent/{challenge}/accept": { + "put": { + "description": "When an authorization code, hybrid, or implicit OAuth 2.0 Flow is initiated, ORY Hydra asks the login provider\nto authenticate the user and then tell ORY Hydra now about it. If the user authenticated, he/she must now be asked if\nthe OAuth 2.0 Client which initiated the flow should be allowed to access the resources on the user's behalf.\n\nThe consent provider which handles this request and is a web app implemented and hosted by you. It shows a user interface which asks the user to\ngrant or deny the client access to the requested scope (\"Application my-dropbox-app wants write access to all your private files\").\n\nThe consent challenge is appended to the consent provider's URL to which the user's user-agent (browser) is redirected to. The consent\nprovider uses that challenge to fetch information on the OAuth2 request and then tells ORY Hydra if the user accepted\nor rejected the request.\n\nThis endpoint tells ORY Hydra that the user has authorized the OAuth 2.0 client to access resources on his/her behalf.\nThe consent provider includes additional information, such as session data for access and ID tokens, and if the\nconsent request should be used as basis for future requests.\n\nThe response contains a redirect URL which the consent provider should redirect the user-agent to.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "schemes": [ + "http", + "https" + ], + "tags": [ + "oAuth2" + ], + "summary": "Accept an consent request", + "operationId": "acceptConsentRequest", + "parameters": [ + { + "type": "string", + "x-go-name": "Challenge", + "name": "challenge", + "in": "path", + "required": true + }, { - "oauth2": [ - "hydra.consent" - ] + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/acceptConsentRequest" + } } ], - "description": "Call this endpoint to accept a consent request. This usually happens when a user agrees to give access rights to\nan application.\n\n\nThe consent request id is usually transmitted via the URL query `consent`.\nFor example: `http://consent-app.mydomain.com/?consent=1234abcd`\n\n\nThe subject making the request needs to be assigned to a policy containing:\n\n```\n{\n\"resources\": [\"rn:hydra:oauth2:consent:requests:\u003crequest-id\u003e\"],\n\"actions\": [\"accept\"],\n\"effect\": \"allow\"\n}\n```", + "responses": { + "200": { + "description": "completedRequest", + "schema": { + "$ref": "#/definitions/completedRequest" + } + }, + "401": { + "$ref": "#/responses/genericError" + }, + "500": { + "$ref": "#/responses/genericError" + } + } + } + }, + "/oauth2/auth/requests/consent/{challenge}/reject": { + "put": { + "description": "When an authorization code, hybrid, or implicit OAuth 2.0 Flow is initiated, ORY Hydra asks the login provider\nto authenticate the user and then tell ORY Hydra now about it. If the user authenticated, he/she must now be asked if\nthe OAuth 2.0 Client which initiated the flow should be allowed to access the resources on the user's behalf.\n\nThe consent provider which handles this request and is a web app implemented and hosted by you. It shows a user interface which asks the user to\ngrant or deny the client access to the requested scope (\"Application my-dropbox-app wants write access to all your private files\").\n\nThe consent challenge is appended to the consent provider's URL to which the user's user-agent (browser) is redirected to. The consent\nprovider uses that challenge to fetch information on the OAuth2 request and then tells ORY Hydra if the user accepted\nor rejected the request.\n\nThis endpoint tells ORY Hydra that the user has not authorized the OAuth 2.0 client to access resources on his/her behalf.\nThe consent provider must include a reason why the consent was not granted.\n\nThe response contains a redirect URL which the consent provider should redirect the user-agent to.", "consumes": [ "application/json" ], @@ -905,28 +848,30 @@ "tags": [ "oAuth2" ], - "summary": "Accept a consent request", - "operationId": "acceptOAuth2ConsentRequest", + "summary": "Reject an consent request", + "operationId": "rejectConsentRequest", "parameters": [ { "type": "string", - "x-go-name": "ID", - "name": "id", + "x-go-name": "Challenge", + "name": "challenge", "in": "path", "required": true }, { "name": "Body", "in": "body", - "required": true, "schema": { - "$ref": "#/definitions/consentRequestAcceptance" + "$ref": "#/definitions/rejectRequest" } } ], "responses": { - "204": { - "$ref": "#/responses/emptyResponse" + "200": { + "description": "completedRequest", + "schema": { + "$ref": "#/definitions/completedRequest" + } }, "401": { "$ref": "#/responses/genericError" @@ -937,16 +882,52 @@ } } }, - "/oauth2/consent/requests/{id}/reject": { - "patch": { - "security": [ + "/oauth2/auth/requests/login/{challenge}": { + "get": { + "description": "When an authorization code, hybrid, or implicit OAuth 2.0 Flow is initiated, ORY Hydra asks the login provider\n(sometimes called \"identity provider\") to authenticate the user and then tell ORY Hydra now about it. The login\nprovider is an web-app you write and host, and it must be able to authenticate (\"show the user a login screen\")\na user (in OAuth2 the proper name for user is \"resource owner\").\n\nThe authentication challenge is appended to the login provider URL to which the user's user-agent (browser) is redirected to. The login\nprovider uses that challenge to fetch information on the OAuth2 request and then accept or reject the requested authentication process.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "schemes": [ + "http", + "https" + ], + "tags": [ + "oAuth2" + ], + "summary": "Get an login request", + "operationId": "getLoginRequest", + "parameters": [ { - "oauth2": [ - "hydra.consent" - ] + "type": "string", + "x-go-name": "Challenge", + "name": "challenge", + "in": "path", + "required": true } ], - "description": "Call this endpoint to reject a consent request. This usually happens when a user denies access rights to an\napplication.\n\n\nThe consent request id is usually transmitted via the URL query `consent`.\nFor example: `http://consent-app.mydomain.com/?consent=1234abcd`\n\n\nThe subject making the request needs to be assigned to a policy containing:\n\n```\n{\n\"resources\": [\"rn:hydra:oauth2:consent:requests:\u003crequest-id\u003e\"],\n\"actions\": [\"reject\"],\n\"effect\": \"allow\"\n}\n```", + "responses": { + "200": { + "description": "loginRequest", + "schema": { + "$ref": "#/definitions/loginRequest" + } + }, + "401": { + "$ref": "#/responses/genericError" + }, + "500": { + "$ref": "#/responses/genericError" + } + } + } + }, + "/oauth2/auth/requests/login/{challenge}/accept": { + "put": { + "description": "When an authorization code, hybrid, or implicit OAuth 2.0 Flow is initiated, ORY Hydra asks the login provider\n(sometimes called \"identity provider\") to authenticate the user and then tell ORY Hydra now about it. The login\nprovider is an web-app you write and host, and it must be able to authenticate (\"show the user a login screen\")\na user (in OAuth2 the proper name for user is \"resource owner\").\n\nThe authentication challenge is appended to the login provider URL to which the user's user-agent (browser) is redirected to. The login\nprovider uses that challenge to fetch information on the OAuth2 request and then accept or reject the requested authentication process.\n\nThis endpoint tells ORY Hydra that the user has successfully authenticated and includes additional information such as\nthe user's ID and if ORY Hydra should remember the user's user agent for future authentication attempts by setting\na cookie.\n\nThe response contains a redirect URL which the login provider should redirect the user-agent to.", "consumes": [ "application/json" ], @@ -960,28 +941,30 @@ "tags": [ "oAuth2" ], - "summary": "Reject a consent request", - "operationId": "rejectOAuth2ConsentRequest", + "summary": "Accept an login request", + "operationId": "acceptLoginRequest", "parameters": [ { "type": "string", - "x-go-name": "ID", - "name": "id", + "x-go-name": "Challenge", + "name": "challenge", "in": "path", "required": true }, { "name": "Body", "in": "body", - "required": true, "schema": { - "$ref": "#/definitions/consentRequestRejection" + "$ref": "#/definitions/acceptLoginRequest" } } ], "responses": { - "204": { - "$ref": "#/responses/emptyResponse" + "200": { + "description": "completedRequest", + "schema": { + "$ref": "#/definitions/completedRequest" + } }, "401": { "$ref": "#/responses/genericError" @@ -992,18 +975,58 @@ } } }, - "/oauth2/flush": { - "post": { - "security": [ + "/oauth2/auth/requests/login/{challenge}/reject": { + "put": { + "description": "When an authorization code, hybrid, or implicit OAuth 2.0 Flow is initiated, ORY Hydra asks the login provider\n(sometimes called \"identity provider\") to authenticate the user and then tell ORY Hydra now about it. The login\nprovider is an web-app you write and host, and it must be able to authenticate (\"show the user a login screen\")\na user (in OAuth2 the proper name for user is \"resource owner\").\n\nThe authentication challenge is appended to the login provider URL to which the user's user-agent (browser) is redirected to. The login\nprovider uses that challenge to fetch information on the OAuth2 request and then accept or reject the requested authentication process.\n\nThis endpoint tells ORY Hydra that the user has not authenticated and includes a reason why the authentication\nwas be denied.\n\nThe response contains a redirect URL which the login provider should redirect the user-agent to.", + "consumes": [ + "application/json" + ], + "produces": [ + "application/json" + ], + "schemes": [ + "http", + "https" + ], + "tags": [ + "oAuth2" + ], + "summary": "Reject an logout request", + "operationId": "rejectLoginRequest", + "parameters": [ { - "basic": [] + "type": "string", + "x-go-name": "Challenge", + "name": "challenge", + "in": "path", + "required": true }, { - "oauth2": [ - "hydra.oauth2.flush" - ] + "name": "Body", + "in": "body", + "schema": { + "$ref": "#/definitions/rejectRequest" + } } ], + "responses": { + "200": { + "description": "completedRequest", + "schema": { + "$ref": "#/definitions/completedRequest" + } + }, + "401": { + "$ref": "#/responses/genericError" + }, + "500": { + "$ref": "#/responses/genericError" + } + } + } + }, + "/oauth2/flush": { + "post": { "description": "This endpoint flushes expired OAuth2 access tokens from the database. You can set a time after which no tokens will be\nnot be touched, in case you want to keep recent tokens for auditing. Refresh tokens can not be flushed as they are deleted\nautomatically when performing the refresh flow.\n\n\n```\n{\n\"resources\": [\"rn:hydra:oauth2:tokens\"],\n\"actions\": [\"flush\"],\n\"effect\": \"allow\"\n}\n```", "consumes": [ "application/json" @@ -1046,9 +1069,7 @@ "basic": [] }, { - "oauth2": [ - "hydra.introspect" - ] + "oauth2": [] } ], "description": "The introspection endpoint allows to check if a token (both refresh and access) is active or not. An active token\nis neither expired nor revoked. If a token is active, additional information on the token will be included. You can\nset additional data for a token by setting `accessTokenExtra` during the consent flow.\n\n```\n{\n\"resources\": [\"rn:hydra:oauth2:tokens\"],\n\"actions\": [\"introspect\"],\n\"effect\": \"allow\"\n}\n```", @@ -1105,6 +1126,9 @@ "security": [ { "basic": [] + }, + { + "oauth2": [] } ], "description": "Revoking a token (both access and refresh) means that the tokens will be invalid. A revoked access token can no\nlonger be used to make access requests, and a revoked refresh token can no longer be used to refresh an access token.\nRevoking a refresh token also invalidates the access token that was created with it.", @@ -1184,19 +1208,14 @@ } } }, - "/policies": { - "get": { + "/userinfo": { + "post": { "security": [ { - "oauth2": [ - "hydra.policies" - ] + "oauth2": [] } ], - "description": "The subject making the request needs to be assigned to a policy containing:\n\n```\n{\n\"resources\": [\"rn:hydra:policies\"],\n\"actions\": [\"list\"],\n\"effect\": \"allow\"\n}\n```", - "consumes": [ - "application/json" - ], + "description": "This endpoint returns the payload of the ID Token, including the idTokenExtra values, of the provided OAuth 2.0 access token.\nThe endpoint implements http://openid.net/specs/openid-connect-core-1_0.html#UserInfo .", "produces": [ "application/json" ], @@ -1205,833 +1224,37 @@ "https" ], "tags": [ - "policy" - ], - "summary": "List Access Control Policies", - "operationId": "listPolicies", - "parameters": [ - { - "type": "integer", - "format": "int64", - "x-go-name": "Offset", - "description": "The offset from where to start looking.", - "name": "offset", - "in": "query" - }, - { - "type": "integer", - "format": "int64", - "x-go-name": "Limit", - "description": "The maximum amount of policies returned.", - "name": "limit", - "in": "query" - } + "oAuth2" ], + "summary": "OpenID Connect Userinfo", + "operationId": "userinfo", "responses": { "200": { - "$ref": "#/responses/policyList" + "description": "userinfoResponse", + "schema": { + "$ref": "#/definitions/userinfoResponse" + } }, "401": { "$ref": "#/responses/genericError" }, - "403": { - "$ref": "#/responses/genericError" - }, "500": { "$ref": "#/responses/genericError" } } - }, - "post": { - "security": [ - { - "oauth2": [ - "hydra.policies" - ] + } + } + }, + "definitions": { + "Handler": { + "type": "object", + "properties": { + "Generators": { + "type": "object", + "additionalProperties": { + "$ref": "#/definitions/KeyGenerator" } - ], - "description": "The subject making the request needs to be assigned to a policy containing:\n\n```\n{\n\"resources\": [\"rn:hydra:policies\"],\n\"actions\": [\"create\"],\n\"effect\": \"allow\"\n}\n```", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "schemes": [ - "http", - "https" - ], - "tags": [ - "policy" - ], - "summary": "Create an Access Control Policy", - "operationId": "createPolicy", - "parameters": [ - { - "name": "Body", - "in": "body", - "schema": { - "$ref": "#/definitions/policy" - } - } - ], - "responses": { - "201": { - "description": "policy", - "schema": { - "$ref": "#/definitions/policy" - } - }, - "401": { - "$ref": "#/responses/genericError" - }, - "403": { - "$ref": "#/responses/genericError" - }, - "500": { - "$ref": "#/responses/genericError" - } - } - } - }, - "/policies/{id}": { - "get": { - "security": [ - { - "oauth2": [ - "hydra.policies" - ] - } - ], - "description": "The subject making the request needs to be assigned to a policy containing:\n\n```\n{\n\"resources\": [\"rn:hydra:policies:\u003cid\u003e\"],\n\"actions\": [\"get\"],\n\"effect\": \"allow\"\n}\n```", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "schemes": [ - "http", - "https" - ], - "tags": [ - "policy" - ], - "summary": "Get an Access Control Policy", - "operationId": "getPolicy", - "parameters": [ - { - "type": "string", - "x-go-name": "ID", - "description": "The id of the policy.", - "name": "id", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "policy", - "schema": { - "$ref": "#/definitions/policy" - } - }, - "401": { - "$ref": "#/responses/genericError" - }, - "403": { - "$ref": "#/responses/genericError" - }, - "500": { - "$ref": "#/responses/genericError" - } - } - }, - "put": { - "security": [ - { - "oauth2": [ - "hydra.policies" - ] - } - ], - "description": "The subject making the request needs to be assigned to a policy containing:\n\n```\n{\n\"resources\": [\"rn:hydra:policies\"],\n\"actions\": [\"update\"],\n\"effect\": \"allow\"\n}\n```", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "schemes": [ - "http", - "https" - ], - "tags": [ - "policy" - ], - "summary": "Update an Access Control Polic", - "operationId": "updatePolicy", - "parameters": [ - { - "type": "string", - "x-go-name": "ID", - "description": "The id of the policy.", - "name": "id", - "in": "path", - "required": true - }, - { - "name": "Body", - "in": "body", - "schema": { - "$ref": "#/definitions/policy" - } - } - ], - "responses": { - "200": { - "description": "policy", - "schema": { - "$ref": "#/definitions/policy" - } - }, - "401": { - "$ref": "#/responses/genericError" - }, - "403": { - "$ref": "#/responses/genericError" - }, - "500": { - "$ref": "#/responses/genericError" - } - } - }, - "delete": { - "security": [ - { - "oauth2": [ - "hydra.policies" - ] - } - ], - "description": "The subject making the request needs to be assigned to a policy containing:\n\n```\n{\n\"resources\": [\"rn:hydra:policies:\u003cid\u003e\"],\n\"actions\": [\"delete\"],\n\"effect\": \"allow\"\n}\n```", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "schemes": [ - "http", - "https" - ], - "tags": [ - "policy" - ], - "summary": "Delete an Access Control Policy", - "operationId": "deletePolicy", - "parameters": [ - { - "type": "string", - "x-go-name": "ID", - "description": "The id of the policy.", - "name": "id", - "in": "path", - "required": true - } - ], - "responses": { - "204": { - "$ref": "#/responses/emptyResponse" - }, - "401": { - "$ref": "#/responses/genericError" - }, - "403": { - "$ref": "#/responses/genericError" - }, - "500": { - "$ref": "#/responses/genericError" - } - } - } - }, - "/userinfo": { - "post": { - "security": [ - { - "oauth2": [] - } - ], - "description": "This endpoint returns the payload of the ID Token, including the idTokenExtra values, of the provided OAuth 2.0 access token.\nThe endpoint implements http://openid.net/specs/openid-connect-core-1_0.html#UserInfo .", - "produces": [ - "application/json" - ], - "schemes": [ - "http", - "https" - ], - "tags": [ - "oAuth2" - ], - "summary": "OpenID Connect Userinfo", - "operationId": "userinfo", - "responses": { - "200": { - "description": "userinfoResponse", - "schema": { - "$ref": "#/definitions/userinfoResponse" - } - }, - "401": { - "$ref": "#/responses/genericError" - }, - "500": { - "$ref": "#/responses/genericError" - } - } - } - }, - "/warden/allowed": { - "post": { - "security": [ - { - "oauth2": [ - "hydra.warden" - ] - } - ], - "description": "Checks if a subject (typically a user or a service) is allowed to perform an action on a resource. This endpoint requires a subject,\na resource name, an action name and a context. If the subject is not allowed to perform the action on the resource,\nthis endpoint returns a 200 response with `{ \"allowed\": false}`, otherwise `{ \"allowed\": true }` is returned.\n\n\nThe subject making the request needs to be assigned to a policy containing:\n\n```\n{\n\"resources\": [\"rn:hydra:warden:allowed\"],\n\"actions\": [\"decide\"],\n\"effect\": \"allow\"\n}\n```", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "schemes": [ - "http", - "https" - ], - "tags": [ - "warden" - ], - "summary": "Check if an access request is valid (without providing an access token)", - "operationId": "doesWardenAllowAccessRequest", - "parameters": [ - { - "name": "Body", - "in": "body", - "schema": { - "$ref": "#/definitions/wardenAccessRequest" - } - } - ], - "responses": { - "200": { - "description": "wardenAccessRequestResponse", - "schema": { - "$ref": "#/definitions/wardenAccessRequestResponse" - } - }, - "401": { - "$ref": "#/responses/genericError" - }, - "403": { - "$ref": "#/responses/genericError" - }, - "500": { - "$ref": "#/responses/genericError" - } - } - } - }, - "/warden/groups": { - "get": { - "security": [ - { - "oauth2": [ - "hydra.warden.groups" - ] - } - ], - "description": "The subject making the request needs to be assigned to a policy containing:\n\n```\n{\n\"resources\": [\"rn:hydra:warden:groups\"],\n\"actions\": [\"list\"],\n\"effect\": \"allow\"\n}\n```", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "schemes": [ - "http", - "https" - ], - "tags": [ - "warden" - ], - "summary": "List groups", - "operationId": "listGroups", - "parameters": [ - { - "type": "string", - "x-go-name": "Member", - "description": "The id of the member to look up.", - "name": "member", - "in": "query" - }, - { - "type": "integer", - "format": "int64", - "x-go-name": "Limit", - "description": "The maximum amount of policies returned.", - "name": "limit", - "in": "query" - }, - { - "type": "integer", - "format": "int64", - "x-go-name": "Offset", - "description": "The offset from where to start looking.", - "name": "offset", - "in": "query" - } - ], - "responses": { - "200": { - "$ref": "#/responses/listGroupsResponse" - }, - "401": { - "$ref": "#/responses/genericError" - }, - "403": { - "$ref": "#/responses/genericError" - }, - "500": { - "$ref": "#/responses/genericError" - } - } - }, - "post": { - "security": [ - { - "oauth2": [ - "hydra.warden.groups" - ] - } - ], - "description": "The subject making the request needs to be assigned to a policy containing:\n\n```\n{\n\"resources\": [\"rn:hydra:warden:groups\"],\n\"actions\": [\"create\"],\n\"effect\": \"allow\"\n}\n```", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "schemes": [ - "http", - "https" - ], - "tags": [ - "warden" - ], - "summary": "Create a group", - "operationId": "createGroup", - "parameters": [ - { - "name": "Body", - "in": "body", - "schema": { - "$ref": "#/definitions/group" - } - } - ], - "responses": { - "201": { - "description": "group", - "schema": { - "$ref": "#/definitions/group" - } - }, - "401": { - "$ref": "#/responses/genericError" - }, - "403": { - "$ref": "#/responses/genericError" - }, - "500": { - "$ref": "#/responses/genericError" - } - } - } - }, - "/warden/groups/{id}": { - "get": { - "security": [ - { - "oauth2": [ - "hydra.warden.groups" - ] - } - ], - "description": "The subject making the request needs to be assigned to a policy containing:\n\n```\n{\n\"resources\": [\"rn:hydra:warden:groups:\u003cid\u003e\"],\n\"actions\": [\"create\"],\n\"effect\": \"allow\"\n}\n```", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "schemes": [ - "http", - "https" - ], - "tags": [ - "warden" - ], - "summary": "Get a group by id", - "operationId": "getGroup", - "parameters": [ - { - "type": "string", - "x-go-name": "ID", - "description": "The id of the group to look up.", - "name": "id", - "in": "path", - "required": true - } - ], - "responses": { - "201": { - "description": "group", - "schema": { - "$ref": "#/definitions/group" - } - }, - "401": { - "$ref": "#/responses/genericError" - }, - "403": { - "$ref": "#/responses/genericError" - }, - "500": { - "$ref": "#/responses/genericError" - } - } - }, - "delete": { - "security": [ - { - "oauth2": [ - "hydra.warden.groups" - ] - } - ], - "description": "The subject making the request needs to be assigned to a policy containing:\n\n```\n{\n\"resources\": [\"rn:hydra:warden:groups:\u003cid\u003e\"],\n\"actions\": [\"delete\"],\n\"effect\": \"allow\"\n}\n```", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "schemes": [ - "http", - "https" - ], - "tags": [ - "warden" - ], - "summary": "Delete a group by id", - "operationId": "deleteGroup", - "parameters": [ - { - "type": "string", - "x-go-name": "ID", - "description": "The id of the group to look up.", - "name": "id", - "in": "path", - "required": true - } - ], - "responses": { - "204": { - "$ref": "#/responses/emptyResponse" - }, - "401": { - "$ref": "#/responses/genericError" - }, - "403": { - "$ref": "#/responses/genericError" - }, - "500": { - "$ref": "#/responses/genericError" - } - } - } - }, - "/warden/groups/{id}/members": { - "post": { - "security": [ - { - "oauth2": [ - "hydra.warden.groups" - ] - } - ], - "description": "The subject making the request needs to be assigned to a policy containing:\n\n```\n{\n\"resources\": [\"rn:hydra:warden:groups:\u003cid\u003e\"],\n\"actions\": [\"members.add\"],\n\"effect\": \"allow\"\n}\n```", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "schemes": [ - "http", - "https" - ], - "tags": [ - "warden" - ], - "summary": "Add members to a group", - "operationId": "addMembersToGroup", - "parameters": [ - { - "type": "string", - "x-go-name": "ID", - "description": "The id of the group to modify.", - "name": "id", - "in": "path", - "required": true - }, - { - "name": "Body", - "in": "body", - "schema": { - "$ref": "#/definitions/groupMembers" - } - } - ], - "responses": { - "204": { - "$ref": "#/responses/emptyResponse" - }, - "401": { - "$ref": "#/responses/genericError" - }, - "403": { - "$ref": "#/responses/genericError" - }, - "500": { - "$ref": "#/responses/genericError" - } - } - }, - "delete": { - "security": [ - { - "oauth2": [ - "hydra.warden.groups" - ] - } - ], - "description": "The subject making the request needs to be assigned to a policy containing:\n\n```\n{\n\"resources\": [\"rn:hydra:warden:groups:\u003cid\u003e\"],\n\"actions\": [\"members.remove\"],\n\"effect\": \"allow\"\n}\n```", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "schemes": [ - "http", - "https" - ], - "tags": [ - "warden" - ], - "summary": "Remove members from a group", - "operationId": "removeMembersFromGroup", - "parameters": [ - { - "type": "string", - "x-go-name": "ID", - "description": "The id of the group to modify.", - "name": "id", - "in": "path", - "required": true - }, - { - "name": "Body", - "in": "body", - "schema": { - "$ref": "#/definitions/groupMembers" - } - } - ], - "responses": { - "204": { - "$ref": "#/responses/emptyResponse" - }, - "401": { - "$ref": "#/responses/genericError" - }, - "403": { - "$ref": "#/responses/genericError" - }, - "500": { - "$ref": "#/responses/genericError" - } - } - } - }, - "/warden/token/allowed": { - "post": { - "security": [ - { - "oauth2": [ - "hydra.warden" - ] - } - ], - "description": "Checks if a token is valid and if the token subject is allowed to perform an action on a resource.\nThis endpoint requires a token, a scope, a resource name, an action name and a context.\n\n\nIf a token is expired/invalid, has not been granted the requested scope or the subject is not allowed to\nperform the action on the resource, this endpoint returns a 200 response with `{ \"allowed\": false}`.\n\n\nExtra data set through the `accessTokenExtra` field in the consent flow will be included in the response.\n\n\nThe subject making the request needs to be assigned to a policy containing:\n\n```\n{\n\"resources\": [\"rn:hydra:warden:token:allowed\"],\n\"actions\": [\"decide\"],\n\"effect\": \"allow\"\n}\n```", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "schemes": [ - "http", - "https" - ], - "tags": [ - "warden" - ], - "summary": "Check if an access request is valid (providing an access token)", - "operationId": "doesWardenAllowTokenAccessRequest", - "parameters": [ - { - "name": "Body", - "in": "body", - "schema": { - "$ref": "#/definitions/wardenTokenAccessRequest" - } - } - ], - "responses": { - "200": { - "description": "wardenTokenAccessRequestResponse", - "schema": { - "$ref": "#/definitions/wardenTokenAccessRequestResponse" - } - }, - "401": { - "$ref": "#/responses/genericError" - }, - "403": { - "$ref": "#/responses/genericError" - }, - "500": { - "$ref": "#/responses/genericError" - } - } - } - } - }, - "definitions": { - "ConsentRequest": { - "type": "object", - "title": "ConsentRequest represents a consent request.", - "properties": { - "clientId": { - "description": "ClientID is the client id that initiated the OAuth2 request.", - "type": "string", - "x-go-name": "ClientID" - }, - "expiresAt": { - "description": "ExpiresAt is the time where the access request will expire.", - "type": "string", - "format": "date-time", - "x-go-name": "ExpiresAt" - }, - "id": { - "description": "ID is the id of this consent request.", - "type": "string", - "x-go-name": "ID" - }, - "redirectUrl": { - "description": "Redirect URL is the URL where the user agent should be redirected to after the consent has been\naccepted or rejected.", - "type": "string", - "x-go-name": "RedirectURL" - }, - "requestedScopes": { - "description": "RequestedScopes represents a list of scopes that have been requested by the OAuth2 request initiator.", - "type": "array", - "items": { - "type": "string" - }, - "x-go-name": "RequestedScopes" - } - }, - "x-go-package": "github.com/ory/hydra/oauth2" - }, - "ConsentRequestManager": { - "type": "object", - "x-go-package": "github.com/ory/hydra/oauth2" - }, - "Context": { - "description": "Context contains an access token's session data", - "type": "object", - "properties": { - "accessTokenExtra": { - "description": "Extra represents arbitrary session data.", - "type": "object", - "additionalProperties": { - "type": "object" - }, - "x-go-name": "Extra" - }, - "clientId": { - "description": "ClientID is id of the client the token was issued for..", - "type": "string", - "x-go-name": "ClientID" - }, - "expiresAt": { - "description": "ExpiresAt is the expiry timestamp.", - "type": "string", - "format": "date-time", - "x-go-name": "ExpiresAt" - }, - "grantedScopes": { - "description": "GrantedScopes is a list of scopes that the subject authorized when asked for consent.", - "type": "array", - "items": { - "type": "string" - }, - "x-go-name": "GrantedScopes" - }, - "issuedAt": { - "description": "IssuedAt is the token creation time stamp.", - "type": "string", - "format": "date-time", - "x-go-name": "IssuedAt" - }, - "issuer": { - "description": "Issuer is the id of the issuer, typically an hydra instance.", - "type": "string", - "x-go-name": "Issuer" }, - "subject": { - "description": "Subject is the identity that authorized issuing the token, for example a user or an OAuth2 app.\nThis is usually a uuid but you can choose a urn or some other id too.", - "type": "string", - "x-go-name": "Subject" - } - }, - "x-go-package": "github.com/ory/hydra/firewall" - }, - "Firewall": { - "type": "object", - "title": "Firewall offers various validation strategies for access tokens.", - "x-go-package": "github.com/ory/hydra/firewall" - }, - "Handler": { - "type": "object", - "properties": { "H": { "$ref": "#/definitions/Writer" }, @@ -2040,12 +1263,9 @@ }, "ResourcePrefix": { "type": "string" - }, - "W": { - "$ref": "#/definitions/Firewall" } }, - "x-go-package": "github.com/ory/hydra/warden/group" + "x-go-package": "github.com/ory/hydra/jwk" }, "KeyGenerator": { "type": "object", @@ -2053,7 +1273,7 @@ }, "Manager": { "type": "object", - "x-go-package": "github.com/ory/hydra/warden/group" + "x-go-package": "github.com/ory/hydra/jwk" }, "RawMessage": { "description": "It implements Marshaler and Unmarshaler and can\nbe used to delay JSON decoding or precompute a JSON encoding.", @@ -2070,103 +1290,172 @@ "type": "object", "x-go-package": "github.com/ory/hydra/vendor/github.com/ory/herodot" }, - "consentRequestAcceptance": { + "acceptConsentRequest": { "type": "object", - "title": "AcceptConsentRequestPayload represents data that will be used to accept a consent request.", + "title": "The request payload used to accept a consent request.", "properties": { - "accessTokenExtra": { - "description": "AccessTokenExtra represents arbitrary data that will be added to the access token and that will be returned\non introspection and warden requests.", - "type": "object", - "additionalProperties": { - "type": "object" - }, - "x-go-name": "AccessTokenExtra" - }, - "grantScopes": { - "description": "A list of scopes that the user agreed to grant. It should be a subset of requestedScopes from the consent request.", + "grant_scope": { + "description": "GrantScope sets the scope the user authorized the client to use. Should be a subset of `requested_scope`", "type": "array", "items": { "type": "string" }, - "x-go-name": "GrantScopes" + "x-go-name": "GrantedScope" }, - "idTokenExtra": { - "description": "IDTokenExtra represents arbitrary data that will be added to the ID token. The ID token will only be issued\nif the user agrees to it and if the client requested an ID token.", - "type": "object", - "additionalProperties": { - "type": "object" - }, - "x-go-name": "IDTokenExtra" + "remember": { + "description": "Remember, if set to true, tells ORY Hydra to remember this consent authorization and reuse it if the same\nclient asks the same user for the same, or a subset of, scope.", + "type": "boolean", + "x-go-name": "Remember" + }, + "remember_for": { + "description": "RememberFor sets how long the consent authorization should be remembered for in seconds. If set to `0`, the\nauthorization will be remembered indefinitely.", + "type": "integer", + "format": "int64", + "x-go-name": "RememberFor" + }, + "session": { + "$ref": "#/definitions/consentRequestSession" + } + }, + "x-go-name": "HandledConsentRequest", + "x-go-package": "github.com/ory/hydra/consent" + }, + "acceptLoginRequest": { + "type": "object", + "title": "The request payload used to accept a login request.", + "properties": { + "acr": { + "description": "ACR sets the Authentication AuthorizationContext Class Reference value for this authentication session. You can use it\nto express that, for example, a user authenticated using two factor authentication.", + "type": "string", + "x-go-name": "ACR" + }, + "remember": { + "description": "Remember, if set to true, tells ORY Hydra to remember this user by telling the user agent (browser) to store\na cookie with authentication data. If the same user performs another OAuth 2.0 Authorization Request, he/she\nwill not be asked to log in again.", + "type": "boolean", + "x-go-name": "Remember" + }, + "remember_for": { + "description": "RememberFor sets how long the authentication should be remembered for in seconds. If set to `0`, the\nauthorization will be remembered indefinitely.", + "type": "integer", + "format": "int64", + "x-go-name": "RememberFor" }, "subject": { - "description": "Subject represents a unique identifier of the user (or service, or legal entity, ...) that accepted the\nOAuth2 request.", + "description": "Subject is the user ID of the end-user that authenticated.", "type": "string", "x-go-name": "Subject" } }, - "x-go-name": "AcceptConsentRequestPayload", - "x-go-package": "github.com/ory/hydra/oauth2" + "x-go-name": "HandledAuthenticationRequest", + "x-go-package": "github.com/ory/hydra/consent" }, - "consentRequestRejection": { + "authenticationSession": { "type": "object", - "title": "RejectConsentRequestPayload represents data that will be used to reject a consent request.", "properties": { - "reason": { - "description": "Reason represents the reason why the user rejected the consent request.", + "AuthenticatedAt": { "type": "string", - "x-go-name": "Reason" + "format": "date-time" + }, + "ID": { + "type": "string" + }, + "Subject": { + "type": "string" } }, - "x-go-name": "RejectConsentRequestPayload", - "x-go-package": "github.com/ory/hydra/oauth2" + "x-go-package": "github.com/ory/hydra/consent" }, - "flushInactiveOAuth2TokensRequest": { + "completedRequest": { "type": "object", + "title": "The response payload sent when accepting or rejecting a login or consent request.", "properties": { - "notAfter": { - "description": "NotAfter sets after which point tokens should not be flushed. This is useful when you want to keep a history\nof recently issued tokens for auditing.", + "redirect_to": { + "description": "RedirectURL is the URL which you should redirect the user to once the authentication process is completed.", "type": "string", - "format": "date-time", - "x-go-name": "NotAfter" + "x-go-name": "RedirectTo" } }, - "x-go-name": "FlushInactiveOAuth2TokensRequest", - "x-go-package": "github.com/ory/hydra/oauth2" + "x-go-name": "RequestHandlerResponse", + "x-go-package": "github.com/ory/hydra/consent" }, - "group": { - "description": "Group represents a warden group", + "consentRequest": { "type": "object", + "title": "Contains information on an ongoing consent request.", "properties": { - "id": { - "description": "ID is the groups id.", + "challenge": { + "description": "Challenge is the identifier (\"authorization challenge\") of the consent authorization request. It is used to\nidentify the session.", "type": "string", - "x-go-name": "ID" + "x-go-name": "Challenge" }, - "members": { - "description": "Members is who belongs to the group.", + "client": { + "$ref": "#/definitions/oAuth2Client" + }, + "oidc_context": { + "$ref": "#/definitions/openIDConnectContext" + }, + "request_url": { + "description": "RequestURL is the original OAuth 2.0 Authorization URL requested by the OAuth 2.0 client. It is the URL which\ninitiates the OAuth 2.0 Authorization Code or OAuth 2.0 Implicit flow. This URL is typically not needed, but\nmight come in handy if you want to deal with additional request parameters.", + "type": "string", + "x-go-name": "RequestURL" + }, + "requested_scope": { + "description": "RequestedScope contains all scopes requested by the OAuth 2.0 client.", "type": "array", "items": { "type": "string" }, - "x-go-name": "Members" + "x-go-name": "RequestedScope" + }, + "skip": { + "description": "Skip, if true, implies that the client has requested the same scopes from the same user previously.\nIf true, you must not ask the user to grant the requested scopes. You must however either allow or deny the\nconsent request using the usual API call.", + "type": "boolean", + "x-go-name": "Skip" + }, + "subject": { + "description": "Subject is the user ID of the end-user that authenticated. Now, that end user needs to grant or deny the scope\nrequested by the OAuth 2.0 client.", + "type": "string", + "x-go-name": "Subject" } }, - "x-go-name": "Group", - "x-go-package": "github.com/ory/hydra/warden/group" + "x-go-name": "ConsentRequest", + "x-go-package": "github.com/ory/hydra/consent" }, - "groupMembers": { + "consentRequestSession": { "type": "object", + "title": "Used to pass session data to a consent request.", "properties": { - "members": { - "type": "array", - "items": { - "type": "string" + "access_token": { + "description": "AccessToken sets session data for the access and refresh token, as well as any future tokens issued by the\nrefresh grant. Keep in mind that this data will be available to anyone performing OAuth 2.0 Challenge Introspection.\nIf only your services can perform OAuth 2.0 Challenge Introspection, this is usually fine. But if third parties\ncan access that endpoint as well, sensitive data from the session might be exposed to them. Use with care!", + "type": "object", + "additionalProperties": { + "type": "object" + }, + "x-go-name": "AccessToken" + }, + "id_token": { + "description": "IDToken sets session data for the OpenID Connect ID token. Keep in mind that the session'id payloads are readable\nby anyone that has access to the ID Challenge. Use with care!", + "type": "object", + "additionalProperties": { + "type": "object" }, - "x-go-name": "Members" + "x-go-name": "IDToken" + } + }, + "x-go-name": "ConsentRequestSessionData", + "x-go-package": "github.com/ory/hydra/consent" + }, + "flushInactiveOAuth2TokensRequest": { + "type": "object", + "properties": { + "notAfter": { + "description": "NotAfter sets after which point tokens should not be flushed. This is useful when you want to keep a history\nof recently issued tokens for auditing.", + "type": "string", + "format": "date-time", + "x-go-name": "NotAfter" } }, - "x-go-name": "membersRequest", - "x-go-package": "github.com/ory/hydra/warden/group" + "x-go-name": "FlushInactiveOAuth2TokensRequest", + "x-go-package": "github.com/ory/hydra/oauth2" }, "joseWebKeySetRequest": { "type": "object", @@ -2289,16 +1578,58 @@ "alg": { "description": "The algorithm to be used for creating the key. Supports \"RS256\", \"ES512\", \"HS512\", and \"HS256\"", "type": "string", - "x-go-name": "Algorithm" + "x-go-name": "Algorithm" + }, + "kid": { + "description": "The kid of the key to be created", + "type": "string", + "x-go-name": "KeyID" + } + }, + "x-go-name": "createRequest", + "x-go-package": "github.com/ory/hydra/jwk" + }, + "loginRequest": { + "type": "object", + "title": "Contains information on an ongoing login request.", + "properties": { + "challenge": { + "description": "Challenge is the identifier (\"authentication challenge\") of the consent authentication request. It is used to\nidentify the session.", + "type": "string", + "x-go-name": "Challenge" + }, + "client": { + "$ref": "#/definitions/oAuth2Client" + }, + "oidc_context": { + "$ref": "#/definitions/openIDConnectContext" + }, + "request_url": { + "description": "RequestURL is the original OAuth 2.0 Authorization URL requested by the OAuth 2.0 client. It is the URL which\ninitiates the OAuth 2.0 Authorization Code or OAuth 2.0 Implicit flow. This URL is typically not needed, but\nmight come in handy if you want to deal with additional request parameters.", + "type": "string", + "x-go-name": "RequestURL" }, - "kid": { - "description": "The kid of the key to be created", + "requested_scope": { + "description": "RequestedScope contains all scopes requested by the OAuth 2.0 client.", + "type": "array", + "items": { + "type": "string" + }, + "x-go-name": "RequestedScope" + }, + "skip": { + "description": "Skip, if true, implies that the client has requested the same scopes from the same user previously.\nIf true, you can skip asking the user to grant the requested scopes, and simply forward the user to the redirect URL.\n\nThis feature allows you to update / set session information.", + "type": "boolean", + "x-go-name": "Skip" + }, + "subject": { + "description": "Subject is the user ID of the end-user that authenticated. Now, that end user needs to grant or deny the scope\nrequested by the OAuth 2.0 client.", "type": "string", - "x-go-name": "KeyID" + "x-go-name": "Subject" } }, - "x-go-name": "createRequest", - "x-go-package": "github.com/ory/hydra/jwk" + "x-go-name": "AuthenticationRequest", + "x-go-package": "github.com/ory/hydra/consent" }, "oAuth2Client": { "type": "object", @@ -2393,42 +1724,6 @@ "x-go-name": "Client", "x-go-package": "github.com/ory/hydra/client" }, - "oAuth2ConsentRequest": { - "type": "object", - "title": "ConsentRequest represents a consent request.", - "properties": { - "clientId": { - "description": "ClientID is the client id that initiated the OAuth2 request.", - "type": "string", - "x-go-name": "ClientID" - }, - "expiresAt": { - "description": "ExpiresAt is the time where the access request will expire.", - "type": "string", - "x-go-name": "ExpiresAt" - }, - "id": { - "description": "ID is the id of this consent request.", - "type": "string", - "x-go-name": "ID" - }, - "redirectUrl": { - "description": "Redirect URL is the URL where the user agent should be redirected to after the consent has been\naccepted or rejected.", - "type": "string", - "x-go-name": "RedirectURL" - }, - "requestedScopes": { - "description": "RequestedScopes represents a list of scopes that have been requested by the OAuth2 request initiator.", - "type": "array", - "items": { - "type": "string" - }, - "x-go-name": "RequestedScopes" - } - }, - "x-go-name": "swaggerConsentRequest", - "x-go-package": "github.com/ory/hydra/oauth2" - }, "oAuth2TokenIntrospection": { "type": "object", "properties": { @@ -2538,117 +1833,63 @@ "x-go-name": "swaggerOAuthTokenResponse", "x-go-package": "github.com/ory/hydra/oauth2" }, - "policy": { + "openIDConnectContext": { "type": "object", + "title": "Contains optional information about the OpenID Connect request.", "properties": { - "actions": { - "description": "Actions impacted by the policy.", + "acr_values": { + "description": "ACRValues is the Authentication AuthorizationContext Class Reference requested in the OAuth 2.0 Authorization request.\nIt is a parameter defined by OpenID Connect and expresses which level of authentication (e.g. 2FA) is required.\n\nOpenID Connect defines it as follows:\n\u003e Requested Authentication AuthorizationContext Class Reference values. Space-separated string that specifies the acr values\nthat the Authorization Server is being requested to use for processing this Authentication Request, with the\nvalues appearing in order of preference. The Authentication AuthorizationContext Class satisfied by the authentication\nperformed is returned as the acr Claim Value, as specified in Section 2. The acr Claim is requested as a\nVoluntary Claim by this parameter.", "type": "array", "items": { "type": "string" }, - "x-go-name": "Actions" - }, - "conditions": { - "description": "Conditions under which the policy is active.", - "type": "object", - "additionalProperties": { - "type": "object", - "properties": { - "options": { - "type": "object", - "additionalProperties": { - "type": "object" - }, - "x-go-name": "Options" - }, - "type": { - "type": "string", - "x-go-name": "Type" - } - } - }, - "x-go-name": "Conditions" - }, - "description": { - "description": "Description of the policy.", - "type": "string", - "x-go-name": "Description" + "x-go-name": "ACRValues" }, - "effect": { - "description": "Effect of the policy", + "display": { + "description": "Display is a string value that specifies how the Authorization Server displays the authentication and consent user interface pages to the End-User.\nThe defined values are:\npage: The Authorization Server SHOULD display the authentication and consent UI consistent with a full User Agent page view. If the display parameter is not specified, this is the default display mode.\npopup: The Authorization Server SHOULD display the authentication and consent UI consistent with a popup User Agent window. The popup User Agent window should be of an appropriate size for a login-focused dialog and should not obscure the entire window that it is popping up over.\ntouch: The Authorization Server SHOULD display the authentication and consent UI consistent with a device that leverages a touch interface.\nwap: The Authorization Server SHOULD display the authentication and consent UI consistent with a \"feature phone\" type display.\n\nThe Authorization Server MAY also attempt to detect the capabilities of the User Agent and present an appropriate display.", "type": "string", - "x-go-name": "Effect" + "x-go-name": "Display" }, - "id": { - "description": "ID of the policy.", - "type": "string", - "x-go-name": "ID" - }, - "resources": { - "description": "Resources impacted by the policy.", - "type": "array", - "items": { - "type": "string" - }, - "x-go-name": "Resources" - }, - "subjects": { - "description": "Subjects impacted by the policy.", + "ui_locales": { + "description": "UILocales is the End-User'id preferred languages and scripts for the user interface, represented as a\nspace-separated list of BCP47 [RFC5646] language tag values, ordered by preference. For instance, the value\n\"fr-CA fr en\" represents a preference for French as spoken in Canada, then French (without a region designation),\nfollowed by English (without a region designation). An error SHOULD NOT result if some or all of the requested\nlocales are not supported by the OpenID Provider.", "type": "array", "items": { "type": "string" }, - "x-go-name": "Subjects" + "x-go-name": "UILocales" } }, - "x-go-name": "swaggerPolicy", - "x-go-package": "github.com/ory/hydra/policy" + "x-go-name": "OpenIDConnectContext", + "x-go-package": "github.com/ory/hydra/consent" }, - "swaggerAcceptConsentRequest": { + "rejectRequest": { "type": "object", - "required": [ - "id", - "Body" - ], + "title": "The request payload used to accept a login or consent request.", "properties": { - "Body": { - "$ref": "#/definitions/consentRequestAcceptance" + "error": { + "type": "string", + "x-go-name": "Name" }, - "id": { - "description": "in: path", + "error_debug": { "type": "string", - "x-go-name": "ID" - } - }, - "x-go-package": "github.com/ory/hydra/oauth2" - }, - "swaggerCreatePolicyParameters": { - "type": "object", - "properties": { - "Body": { - "$ref": "#/definitions/policy" - } - }, - "x-go-package": "github.com/ory/hydra/policy" - }, - "swaggerDoesWardenAllowAccessRequestParameters": { - "type": "object", - "properties": { - "Body": { - "$ref": "#/definitions/wardenAccessRequest" - } - }, - "x-go-package": "github.com/ory/hydra/warden" - }, - "swaggerDoesWardenAllowTokenAccessRequestParameters": { - "type": "object", - "properties": { - "Body": { - "$ref": "#/definitions/wardenTokenAccessRequest" + "x-go-name": "Debug" + }, + "error_description": { + "type": "string", + "x-go-name": "Description" + }, + "error_hint": { + "type": "string", + "x-go-name": "Hint" + }, + "status_code": { + "type": "integer", + "format": "int64", + "x-go-name": "Code" } }, - "x-go-package": "github.com/ory/hydra/warden" + "x-go-name": "RequestDeniedError", + "x-go-package": "github.com/ory/hydra/consent" }, "swaggerFlushInactiveAccessTokens": { "type": "object", @@ -2659,17 +1900,6 @@ }, "x-go-package": "github.com/ory/hydra/oauth2" }, - "swaggerGetPolicyParameters": { - "type": "object", - "properties": { - "id": { - "description": "The id of the policy.\nin: path", - "type": "string", - "x-go-name": "ID" - } - }, - "x-go-package": "github.com/ory/hydra/policy" - }, "swaggerJsonWebKeyQuery": { "type": "object", "required": [ @@ -2761,53 +1991,6 @@ }, "x-go-package": "github.com/ory/hydra/jwk" }, - "swaggerListPolicyParameters": { - "type": "object", - "properties": { - "limit": { - "description": "The maximum amount of policies returned.\nin: query", - "type": "integer", - "format": "int64", - "x-go-name": "Limit" - }, - "offset": { - "description": "The offset from where to start looking.\nin: query", - "type": "integer", - "format": "int64", - "x-go-name": "Offset" - } - }, - "x-go-package": "github.com/ory/hydra/policy" - }, - "swaggerListPolicyResponse": { - "description": "A policy", - "type": "object", - "properties": { - "Body": { - "description": "in: body\ntype: array", - "type": "array", - "items": { - "$ref": "#/definitions/policy" - } - } - }, - "x-go-package": "github.com/ory/hydra/policy" - }, - "swaggerOAuthConsentRequestPayload": { - "type": "object", - "required": [ - "id" - ], - "properties": { - "id": { - "description": "The id of the OAuth 2.0 Consent Request.", - "type": "string", - "uniqueItems": true, - "x-go-name": "ID" - } - }, - "x-go-package": "github.com/ory/hydra/oauth2" - }, "swaggerOAuthIntrospectionRequest": { "type": "object", "required": [ @@ -2827,24 +2010,6 @@ }, "x-go-package": "github.com/ory/hydra/oauth2" }, - "swaggerRejectConsentRequest": { - "type": "object", - "required": [ - "id", - "Body" - ], - "properties": { - "Body": { - "$ref": "#/definitions/consentRequestRejection" - }, - "id": { - "description": "in: path", - "type": "string", - "x-go-name": "ID" - } - }, - "x-go-package": "github.com/ory/hydra/oauth2" - }, "swaggerRevokeOAuth2TokenParameters": { "type": "object", "required": [ @@ -2859,45 +2024,6 @@ }, "x-go-package": "github.com/ory/hydra/oauth2" }, - "swaggerUpdatePolicyParameters": { - "type": "object", - "properties": { - "Body": { - "$ref": "#/definitions/policy" - }, - "id": { - "description": "The id of the policy.\nin: path", - "type": "string", - "x-go-name": "ID" - } - }, - "x-go-package": "github.com/ory/hydra/policy" - }, - "tokenAllowedRequest": { - "type": "object", - "properties": { - "action": { - "description": "Action is the action that is requested on the resource.", - "type": "string", - "x-go-name": "Action" - }, - "context": { - "description": "Context is the request's environmental context.", - "type": "object", - "additionalProperties": { - "type": "object" - }, - "x-go-name": "Context" - }, - "resource": { - "description": "Resource is the resource that access is requested to.", - "type": "string", - "x-go-name": "Resource" - } - }, - "x-go-name": "TokenAccessRequest", - "x-go-package": "github.com/ory/hydra/firewall" - }, "userinfoResponse": { "description": "The userinfo response", "type": "object", @@ -3002,142 +2128,6 @@ "x-go-name": "swaggeruserinfoResponsePayload", "x-go-package": "github.com/ory/hydra/oauth2" }, - "wardenAccessRequest": { - "type": "object", - "title": "AccessRequest is the warden's request object.", - "properties": { - "action": { - "description": "Action is the action that is requested on the resource.", - "type": "string", - "x-go-name": "Action" - }, - "context": { - "description": "Context is the request's environmental context.", - "type": "object", - "additionalProperties": { - "type": "object" - }, - "x-go-name": "Context" - }, - "resource": { - "description": "Resource is the resource that access is requested to.", - "type": "string", - "x-go-name": "Resource" - }, - "subject": { - "description": "Subejct is the subject that is requesting access.", - "type": "string", - "x-go-name": "Subject" - } - }, - "x-go-name": "AccessRequest", - "x-go-package": "github.com/ory/hydra/firewall" - }, - "wardenAccessRequestResponse": { - "description": "The warden access request response", - "type": "object", - "properties": { - "allowed": { - "description": "Allowed is true if the request is allowed and false otherwise.", - "type": "boolean", - "x-go-name": "Allowed" - } - }, - "x-go-name": "swaggerWardenAccessRequestResponse", - "x-go-package": "github.com/ory/hydra/warden" - }, - "wardenTokenAccessRequest": { - "type": "object", - "properties": { - "action": { - "description": "Action is the action that is requested on the resource.", - "type": "string", - "x-go-name": "Action" - }, - "context": { - "description": "Context is the request's environmental context.", - "type": "object", - "additionalProperties": { - "type": "object" - }, - "x-go-name": "Context" - }, - "resource": { - "description": "Resource is the resource that access is requested to.", - "type": "string", - "x-go-name": "Resource" - }, - "scopes": { - "description": "Scopes is an array of scopes that are requried.", - "type": "array", - "items": { - "type": "string" - }, - "x-go-name": "Scopes" - }, - "token": { - "description": "Token is the token to introspect.", - "type": "string", - "x-go-name": "Token" - } - }, - "x-go-name": "swaggerWardenTokenAccessRequest", - "x-go-package": "github.com/ory/hydra/warden" - }, - "wardenTokenAccessRequestResponse": { - "description": "The warden access request (with token) response", - "type": "object", - "properties": { - "accessTokenExtra": { - "description": "Extra represents arbitrary session data.", - "type": "object", - "additionalProperties": { - "type": "object" - }, - "x-go-name": "Extra" - }, - "allowed": { - "description": "Allowed is true if the request is allowed and false otherwise.", - "type": "boolean", - "x-go-name": "Allowed" - }, - "clientId": { - "description": "ClientID is the id of the OAuth2 client that requested the token.", - "type": "string", - "x-go-name": "ClientID" - }, - "expiresAt": { - "description": "ExpiresAt is the expiry timestamp.", - "type": "string", - "x-go-name": "ExpiresAt" - }, - "grantedScopes": { - "description": "GrantedScopes is a list of scopes that the subject authorized when asked for consent.", - "type": "array", - "items": { - "type": "string" - }, - "x-go-name": "GrantedScopes" - }, - "issuedAt": { - "description": "IssuedAt is the token creation time stamp.", - "type": "string", - "x-go-name": "IssuedAt" - }, - "issuer": { - "description": "Issuer is the id of the issuer, typically an hydra instance.", - "type": "string", - "x-go-name": "Issuer" - }, - "subject": { - "description": "Subject is the identity that authorized issuing the token, for example a user or an OAuth2 app.\nThis is usually a uuid but you can choose a urn or some other id too.", - "type": "string", - "x-go-name": "Subject" - } - }, - "x-go-name": "swaggerWardenTokenAccessRequestResponsePayload", - "x-go-package": "github.com/ory/hydra/warden" - }, "wellKnown": { "type": "object", "required": [ @@ -3284,15 +2274,6 @@ } } }, - "listGroupsResponse": { - "description": "A list of groups the member is belonging to", - "schema": { - "type": "array", - "items": { - "$ref": "#/definitions/group" - } - } - }, "oAuth2ClientList": { "description": "A list of clients.", "schema": { @@ -3301,15 +2282,6 @@ "$ref": "#/definitions/oAuth2Client" } } - }, - "policyList": { - "description": "A policy", - "schema": { - "type": "array", - "items": { - "$ref": "#/definitions/policy" - } - } } }, "securityDefinitions": { @@ -3322,15 +2294,6 @@ "authorizationUrl": "https://your-hydra-instance.com/oauth2/auth", "tokenUrl": "https://your-hydra-instance.com/oauth2/token", "scopes": { - "hydra.clients": "A scope required to manage OAuth 2.0 Clients", - "hydra.consent": "A scope required to fetch and modify consent requests", - "hydra.keys.create": "A scope required to create JSON Web Keys", - "hydra.keys.delete": "A scope required to delete JSON Web Keys", - "hydra.keys.get": "A scope required to fetch JSON Web Keys", - "hydra.keys.update": "A scope required to get JSON Web Keys", - "hydra.policies": "A scope required to manage access control policies", - "hydra.warden": "A scope required to make access control inquiries", - "hydra.warden.groups": "A scope required to manage warden groups", "offline": "A scope required when requesting refresh tokens", "openid": "Request an OpenID Connect ID Token" } diff --git a/integration/sql_schema_test.go b/integration/sql_schema_test.go index 42cc2d5dca9..c1a3484da07 100644 --- a/integration/sql_schema_test.go +++ b/integration/sql_schema_test.go @@ -22,9 +22,11 @@ package integration import ( "testing" + "time" "github.com/ory/fosite" "github.com/ory/hydra/client" + "github.com/ory/hydra/consent" "github.com/ory/hydra/jwk" "github.com/ory/hydra/oauth2" "github.com/ory/ladon" @@ -49,7 +51,7 @@ func TestSQLSchema(t *testing.T) { cm := &client.SQLManager{DB: db, Hasher: &fosite.BCrypt{}} jm := jwk.SQLManager{DB: db, Cipher: &jwk.AEAD{Key: []byte("11111111111111111111111111111111")}} om := oauth2.FositeSQLStore{Manager: cm, DB: db, L: logrus.New()} - crm := oauth2.NewConsentRequestSQLManager(db) + crm := consent.NewSQLManager(db, nil) pm := lsql.NewSQLManager(db, nil) _, err := pm.CreateSchemas("", "hydra_policy_migration") @@ -67,6 +69,10 @@ func TestSQLSchema(t *testing.T) { require.NoError(t, jm.AddKey("integration-test-foo", jwk.First(p1))) require.NoError(t, pm.Create(&ladon.DefaultPolicy{ID: "integration-test-foo", Resources: []string{"foo"}, Actions: []string{"bar"}, Subjects: []string{"baz"}, Effect: "allow"})) require.NoError(t, cm.CreateClient(&client.Client{ID: "integration-test-foo"})) - require.NoError(t, crm.PersistConsentRequest(&oauth2.ConsentRequest{ID: "integration-test-foo"})) + require.NoError(t, crm.CreateAuthenticationSession(&consent.AuthenticationSession{ + ID: "foo", + AuthenticatedAt: time.Now(), + Subject: "bar", + })) require.NoError(t, om.CreateAccessTokenSession(nil, "asdfasdf", r)) } diff --git a/metrics/middleware.go b/metrics/middleware.go index 120ca916f42..210a6a96a8e 100644 --- a/metrics/middleware.go +++ b/metrics/middleware.go @@ -225,7 +225,7 @@ func anonymizePath(path string, salt string) string { oauth2.WellKnownPath, oauth2.IntrospectPath, oauth2.RevocationPath, - oauth2.ConsentRequestPath, + //oauth2.ConsentRequestPath, "/health/status", "/", } diff --git a/oauth2/consent.go b/oauth2/consent.go deleted file mode 100644 index d2d82cb4b4f..00000000000 --- a/oauth2/consent.go +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright © 2015-2018 Aeneas Rekkas - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * @author Aeneas Rekkas - * @copyright 2015-2018 Aeneas Rekkas - * @license Apache-2.0 - */ - -package oauth2 - -import ( - "github.com/gorilla/sessions" - "github.com/ory/fosite" -) - -type ConsentStrategy interface { - ValidateConsentRequest(req fosite.AuthorizeRequester, session string, cookie *sessions.Session) (claims *Session, err error) - CreateConsentRequest(req fosite.AuthorizeRequester, redirectURL string, cookie *sessions.Session) (token string, err error) -} diff --git a/oauth2/consent_handler.go b/oauth2/consent_handler.go deleted file mode 100644 index a86da95cc80..00000000000 --- a/oauth2/consent_handler.go +++ /dev/null @@ -1,169 +0,0 @@ -/* - * Copyright © 2015-2018 Aeneas Rekkas - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * @author Aeneas Rekkas - * @copyright 2015-2018 Aeneas Rekkas - * @license Apache-2.0 - */ - -package oauth2 - -import ( - "encoding/json" - "net/http" - - "github.com/julienschmidt/httprouter" - "github.com/ory/herodot" - "github.com/pkg/errors" -) - -const ( - ConsentRequestAccepted = "accepted" - ConsentRequestRejected = "rejected" - - ConsentRequestPath = "/oauth2/consent/requests" - - ConsentResource = "oauth2:consent:requests:%s" - ConsentScope = "hydra.consent" -) - -type ConsentSessionHandler struct { - H herodot.Writer - M ConsentRequestManager - - ResourcePrefix string -} - -func (h *ConsentSessionHandler) PrefixResource(resource string) string { - if h.ResourcePrefix == "" { - h.ResourcePrefix = "rn:hydra" - } - - if h.ResourcePrefix[len(h.ResourcePrefix)-1] == ':' { - h.ResourcePrefix = h.ResourcePrefix[:len(h.ResourcePrefix)-1] - } - - return h.ResourcePrefix + ":" + resource -} - -func (h *ConsentSessionHandler) SetRoutes(r *httprouter.Router) { - r.GET(ConsentRequestPath+"/:id", h.FetchConsentRequest) - r.PATCH(ConsentRequestPath+"/:id/reject", h.RejectConsentRequestHandler) - r.PATCH(ConsentRequestPath+"/:id/accept", h.AcceptConsentRequestHandler) -} - -// swagger:route GET /oauth2/consent/requests/{id} oAuth2 getOAuth2ConsentRequest -// -// Receive consent request information -// -// Call this endpoint to receive information on consent requests. The consent request id is usually transmitted via the URL query `consent`. -// For example: `http://consent-app.mydomain.com/?consent=1234abcd` -// -// Consumes: -// - application/json -// -// Produces: -// - application/json -// -// Schemes: http, https -// -// Responses: -// 200: oAuth2ConsentRequest -// 401: genericError -// 500: genericError -func (h *ConsentSessionHandler) FetchConsentRequest(w http.ResponseWriter, r *http.Request, ps httprouter.Params) { - if session, err := h.M.GetConsentRequest(ps.ByName("id")); err != nil { - h.H.WriteError(w, r, err) - return - } else { - h.H.Write(w, r, session) - } -} - -// swagger:route PATCH /oauth2/consent/requests/{id}/reject oAuth2 rejectOAuth2ConsentRequest -// -// Reject a consent request -// -// Call this endpoint to reject a consent request. This usually happens when a user denies access rights to an -// application. -// -// -// The consent request id is usually transmitted via the URL query `consent`. -// For example: `http://consent-app.mydomain.com/?consent=1234abcd` -// -// Consumes: -// - application/json -// -// Produces: -// - application/json -// -// Schemes: http, https -// -// Responses: -// 204: emptyResponse -// 401: genericError -// 500: genericError -func (h *ConsentSessionHandler) RejectConsentRequestHandler(w http.ResponseWriter, r *http.Request, ps httprouter.Params) { - var payload RejectConsentRequestPayload - if err := json.NewDecoder(r.Body).Decode(&payload); err != nil { - h.H.WriteError(w, r, errors.WithStack(err)) - return - } - - if err := h.M.RejectConsentRequest(ps.ByName("id"), &payload); err != nil { - h.H.WriteError(w, r, err) - return - } - - w.WriteHeader(http.StatusNoContent) -} - -// swagger:route PATCH /oauth2/consent/requests/{id}/accept oAuth2 acceptOAuth2ConsentRequest -// -// Accept a consent request -// -// Call this endpoint to accept a consent request. This usually happens when a user agrees to give access rights to -// an application. -// -// -// The consent request id is usually transmitted via the URL query `consent`. -// For example: `http://consent-app.mydomain.com/?consent=1234abcd` -// -// Consumes: -// - application/json -// -// Produces: -// - application/json -// -// Schemes: http, https -// -// Responses: -// 204: emptyResponse -// 401: genericError -// 500: genericError -func (h *ConsentSessionHandler) AcceptConsentRequestHandler(w http.ResponseWriter, r *http.Request, ps httprouter.Params) { - var payload AcceptConsentRequestPayload - if err := json.NewDecoder(r.Body).Decode(&payload); err != nil { - h.H.WriteError(w, r, errors.WithStack(err)) - return - } - - if err := h.M.AcceptConsentRequest(ps.ByName("id"), &payload); err != nil { - h.H.WriteError(w, r, err) - return - } - - w.WriteHeader(http.StatusNoContent) -} diff --git a/oauth2/consent_manager.go b/oauth2/consent_manager.go deleted file mode 100644 index 17e97ddb8c6..00000000000 --- a/oauth2/consent_manager.go +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright © 2015-2018 Aeneas Rekkas - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * @author Aeneas Rekkas - * @copyright 2015-2018 Aeneas Rekkas - * @license Apache-2.0 - */ - -package oauth2 - -import "time" - -// ConsentRequest represents a consent request. -type ConsentRequest struct { - // ID is the id of this consent request. - ID string `json:"id"` - - // RequestedScopes represents a list of scopes that have been requested by the OAuth2 request initiator. - RequestedScopes []string `json:"requestedScopes"` - - // ClientID is the client id that initiated the OAuth2 request. - ClientID string `json:"clientId"` - - // ExpiresAt is the time where the access request will expire. - ExpiresAt time.Time `json:"expiresAt"` - - // Redirect URL is the URL where the user agent should be redirected to after the consent has been - // accepted or rejected. - RedirectURL string `json:"redirectUrl"` - - CSRF string `json:"-"` - GrantedScopes []string `json:"-"` - Subject string `json:"-"` - AccessTokenExtra map[string]interface{} `json:"-"` - IDTokenExtra map[string]interface{} `json:"-"` - Consent string `json:"-"` - DenyReason string `json:"-"` -} - -func (c *ConsentRequest) IsConsentGranted() bool { - return c.Consent == ConsentRequestAccepted -} - -// AcceptConsentRequestPayload represents data that will be used to accept a consent request. -// -// swagger:model consentRequestAcceptance -type AcceptConsentRequestPayload struct { - // AccessTokenExtra represents arbitrary data that will be added to the access token and that will be returned - // on introspection and warden requests. - AccessTokenExtra map[string]interface{} `json:"accessTokenExtra"` - - // IDTokenExtra represents arbitrary data that will be added to the ID token. The ID token will only be issued - // if the user agrees to it and if the client requested an ID token. - IDTokenExtra map[string]interface{} `json:"idTokenExtra"` - - // Subject represents a unique identifier of the user (or service, or legal entity, ...) that accepted the - // OAuth2 request. - Subject string `json:"subject"` - - // A list of scopes that the user agreed to grant. It should be a subset of requestedScopes from the consent request. - GrantScopes []string `json:"grantScopes"` -} - -// RejectConsentRequestPayload represents data that will be used to reject a consent request. -// -// swagger:model consentRequestRejection -type RejectConsentRequestPayload struct { - // Reason represents the reason why the user rejected the consent request. - Reason string `json:"reason"` -} - -type ConsentRequestManager interface { - PersistConsentRequest(*ConsentRequest) error - AcceptConsentRequest(id string, payload *AcceptConsentRequestPayload) error - RejectConsentRequest(id string, payload *RejectConsentRequestPayload) error - GetConsentRequest(id string) (*ConsentRequest, error) -} diff --git a/oauth2/consent_manager_memory.go b/oauth2/consent_manager_memory.go deleted file mode 100644 index 8cb25f1c52b..00000000000 --- a/oauth2/consent_manager_memory.go +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright © 2015-2018 Aeneas Rekkas - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * @author Aeneas Rekkas - * @copyright 2015-2018 Aeneas Rekkas - * @license Apache-2.0 - */ - -package oauth2 - -import ( - "sync" - - "github.com/ory/hydra/pkg" - "github.com/pkg/errors" -) - -type ConsentRequestMemoryManager struct { - requests map[string]ConsentRequest - sync.RWMutex -} - -func NewConsentRequestMemoryManager() *ConsentRequestMemoryManager { - return &ConsentRequestMemoryManager{requests: map[string]ConsentRequest{}} -} - -func (m *ConsentRequestMemoryManager) PersistConsentRequest(session *ConsentRequest) error { - m.Lock() - defer m.Unlock() - m.requests[session.ID] = *session - return nil -} - -func (m *ConsentRequestMemoryManager) AcceptConsentRequest(id string, payload *AcceptConsentRequestPayload) error { - session, err := m.GetConsentRequest(id) - if err != nil { - return err - } - - session.Subject = payload.Subject - session.AccessTokenExtra = payload.AccessTokenExtra - session.IDTokenExtra = payload.IDTokenExtra - session.Consent = ConsentRequestAccepted - session.GrantedScopes = payload.GrantScopes - - return m.PersistConsentRequest(session) -} - -func (m *ConsentRequestMemoryManager) RejectConsentRequest(id string, payload *RejectConsentRequestPayload) error { - session, err := m.GetConsentRequest(id) - if err != nil { - return err - } - - session.Consent = ConsentRequestRejected - session.DenyReason = payload.Reason - return m.PersistConsentRequest(session) -} - -func (m *ConsentRequestMemoryManager) GetConsentRequest(id string) (*ConsentRequest, error) { - m.RLock() - defer m.RUnlock() - if session, found := m.requests[id]; !found { - return nil, errors.Wrap(pkg.ErrNotFound, "") - } else { - return &session, nil - } -} diff --git a/oauth2/consent_manager_sql.go b/oauth2/consent_manager_sql.go deleted file mode 100644 index 94d8a974e79..00000000000 --- a/oauth2/consent_manager_sql.go +++ /dev/null @@ -1,253 +0,0 @@ -/* - * Copyright © 2015-2018 Aeneas Rekkas - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * @author Aeneas Rekkas - * @copyright 2015-2018 Aeneas Rekkas - * @license Apache-2.0 - */ - -package oauth2 - -import ( - "database/sql" - "encoding/json" - "fmt" - "strings" - "time" - - "github.com/jmoiron/sqlx" - "github.com/ory/hydra/pkg" - "github.com/pborman/uuid" - "github.com/pkg/errors" - "github.com/rubenv/sql-migrate" -) - -var sqlConsentParams = []string{ - "id", "client_id", "expires_at", "redirect_url", "requested_scopes", - "csrf", "granted_scopes", "access_token_extra", "id_token_extra", - "consent", "deny_reason", "subject", -} - -var consentMigrations = &migrate.MemoryMigrationSource{ - Migrations: []*migrate.Migration{ - { - Id: "1", - Up: []string{`CREATE TABLE IF NOT EXISTS hydra_consent_request ( - id varchar(36) NOT NULL PRIMARY KEY, - requested_scopes text NOT NULL, - client_id text NOT NULL, - expires_at timestamp NOT NULL, - redirect_url text NOT NULL, - csrf text NOT NULL, - granted_scopes text NOT NULL, - access_token_extra text NOT NULL, - id_token_extra text NOT NULL, - consent text NOT NULL, - deny_reason text NOT NULL, - subject text NOT NULL -)`}, - Down: []string{ - "DROP TABLE hydra_consent_request", - }, - }, - }, -} - -type consentRequestSqlData struct { - ID string `db:"id"` - RequestedScopes string `db:"requested_scopes"` - ClientID string `db:"client_id"` - ExpiresAt time.Time `db:"expires_at"` - RedirectURL string `db:"redirect_url"` - CSRF string `db:"csrf"` - GrantedScopes string `db:"granted_scopes"` - AccessTokenExtra string `db:"access_token_extra"` - IDTokenExtra string `db:"id_token_extra"` - Consent string `db:"consent"` - DenyReason string `db:"deny_reason"` - Subject string `db:"subject"` -} - -func newConsentRequestSqlData(request *ConsentRequest) (*consentRequestSqlData, error) { - for k, scope := range request.RequestedScopes { - request.RequestedScopes[k] = strings.Replace(scope, " ", "", -1) - } - for k, scope := range request.GrantedScopes { - request.GrantedScopes[k] = strings.Replace(scope, " ", "", -1) - } - - atext := "" - idtext := "" - - if request.AccessTokenExtra != nil { - if out, err := json.Marshal(request.AccessTokenExtra); err != nil { - return nil, errors.WithStack(err) - } else { - atext = string(out) - } - } - - if request.IDTokenExtra != nil { - if out, err := json.Marshal(request.IDTokenExtra); err != nil { - return nil, errors.WithStack(err) - } else { - idtext = string(out) - } - } - - return &consentRequestSqlData{ - ID: request.ID, - RequestedScopes: strings.Join(request.RequestedScopes, " "), - GrantedScopes: strings.Join(request.GrantedScopes, " "), - ClientID: request.ClientID, - ExpiresAt: request.ExpiresAt, - RedirectURL: request.RedirectURL, - CSRF: request.CSRF, - AccessTokenExtra: atext, - IDTokenExtra: idtext, - Consent: request.Consent, - DenyReason: request.DenyReason, - Subject: request.Subject, - }, nil -} - -func (r *consentRequestSqlData) toConsentRequest() (*ConsentRequest, error) { - var atext, idtext map[string]interface{} - - if r.IDTokenExtra != "" { - if err := json.Unmarshal([]byte(r.IDTokenExtra), &idtext); err != nil { - return nil, errors.WithStack(err) - } - } - - if r.AccessTokenExtra != "" { - if err := json.Unmarshal([]byte(r.AccessTokenExtra), &atext); err != nil { - return nil, errors.WithStack(err) - } - } - - return &ConsentRequest{ - ID: r.ID, - ClientID: r.ClientID, - ExpiresAt: r.ExpiresAt, - RedirectURL: r.RedirectURL, - CSRF: r.CSRF, - Consent: r.Consent, - DenyReason: r.DenyReason, - RequestedScopes: strings.Split(r.RequestedScopes, " "), - GrantedScopes: strings.Split(r.GrantedScopes, " "), - AccessTokenExtra: atext, - IDTokenExtra: idtext, - Subject: r.Subject, - }, nil -} - -type ConsentRequestSQLManager struct { - db *sqlx.DB -} - -func NewConsentRequestSQLManager(db *sqlx.DB) *ConsentRequestSQLManager { - return &ConsentRequestSQLManager{db: db} -} - -func (m *ConsentRequestSQLManager) CreateSchemas() (int, error) { - migrate.SetTable("hydra_consent_request_migration") - n, err := migrate.Exec(m.db.DB, m.db.DriverName(), consentMigrations, migrate.Up) - if err != nil { - return 0, errors.Wrapf(err, "Could not migrate sql schema, applied %d migrations", n) - } - return n, nil -} - -func (m *ConsentRequestSQLManager) PersistConsentRequest(request *ConsentRequest) error { - if request.ID == "" { - request.ID = uuid.New() - } - - data, err := newConsentRequestSqlData(request) - if err != nil { - return errors.WithStack(err) - } - - query := fmt.Sprintf( - "INSERT INTO hydra_consent_request (%s) VALUES (%s)", - strings.Join(sqlConsentParams, ", "), - ":"+strings.Join(sqlConsentParams, ", :"), - ) - if _, err := m.db.NamedExec(query, data); err != nil { - return errors.WithStack(err) - } - return nil -} - -func (m *ConsentRequestSQLManager) AcceptConsentRequest(id string, payload *AcceptConsentRequestPayload) error { - r, err := m.GetConsentRequest(id) - if err != nil { - return errors.WithStack(err) - } - - r.Subject = payload.Subject - r.AccessTokenExtra = payload.AccessTokenExtra - r.IDTokenExtra = payload.IDTokenExtra - r.Consent = ConsentRequestAccepted - r.GrantedScopes = payload.GrantScopes - - return m.updateConsentRequest(r) -} - -func (m *ConsentRequestSQLManager) RejectConsentRequest(id string, payload *RejectConsentRequestPayload) error { - r, err := m.GetConsentRequest(id) - if err != nil { - return errors.WithStack(err) - } - - r.Consent = ConsentRequestRejected - r.DenyReason = payload.Reason - - return m.updateConsentRequest(r) -} - -func (m *ConsentRequestSQLManager) updateConsentRequest(request *ConsentRequest) error { - d, err := newConsentRequestSqlData(request) - if err != nil { - return errors.WithStack(err) - } - - var query []string - for _, param := range sqlConsentParams { - query = append(query, fmt.Sprintf("%s=:%s", param, param)) - } - - if _, err := m.db.NamedExec(fmt.Sprintf(`UPDATE hydra_consent_request SET %s WHERE id=:id`, strings.Join(query, ", ")), d); err != nil { - return errors.WithStack(err) - } - - return nil -} - -func (m *ConsentRequestSQLManager) GetConsentRequest(id string) (*ConsentRequest, error) { - var d consentRequestSqlData - if err := m.db.Get(&d, m.db.Rebind("SELECT * FROM hydra_consent_request WHERE id=?"), id); err == sql.ErrNoRows { - return nil, errors.WithStack(pkg.ErrNotFound) - } else if err != nil { - return nil, errors.WithStack(err) - } - - r, err := d.toConsentRequest() - if err != nil { - return nil, errors.WithStack(err) - } - return r, nil -} diff --git a/oauth2/consent_manager_sql_test.go b/oauth2/consent_manager_sql_test.go deleted file mode 100644 index 4cef2bd0167..00000000000 --- a/oauth2/consent_manager_sql_test.go +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright © 2015-2018 Aeneas Rekkas - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * @author Aeneas Rekkas - * @copyright 2015-2018 Aeneas Rekkas - * @license Apache-2.0 - */ - -package oauth2 - -import ( - "testing" - "time" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestConsentRequestSqlDataTransforms(t *testing.T) { - t.Parallel() - for _, tc := range []struct { - d string - r *ConsentRequest - }{ - { - d: "fully hydrated request object", - r: &ConsentRequest{ - ID: "id", - ClientID: "client-id", - RequestedScopes: []string{"foo", "bar"}, - GrantedScopes: []string{"baz", "bar"}, - CSRF: "some-csrf", - ExpiresAt: time.Now().UTC().Round(time.Second), - Consent: ConsentRequestAccepted, - DenyReason: "some reason", - AccessTokenExtra: map[string]interface{}{"atfoo": "bar", "atbaz": "bar"}, - IDTokenExtra: map[string]interface{}{"idfoo": "bar", "idbaz": "bar"}, - RedirectURL: "https://redirect-me/foo", - Subject: "Peter", - }, - }, - } { - t.Run(tc.d, func(t *testing.T) { - s, err := newConsentRequestSqlData(tc.r) - require.Nil(t, err) - - o, err := s.toConsentRequest() - require.NoError(t, err) - - assert.EqualValues(t, tc.r, o) - }) - } -} diff --git a/oauth2/consent_manager_test.go b/oauth2/consent_manager_test.go deleted file mode 100644 index 44e26175403..00000000000 --- a/oauth2/consent_manager_test.go +++ /dev/null @@ -1,132 +0,0 @@ -/* - * Copyright © 2015-2018 Aeneas Rekkas - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * @author Aeneas Rekkas - * @copyright 2015-2018 Aeneas Rekkas - * @license Apache-2.0 - */ - -package oauth2_test - -import ( - "fmt" - "log" - "testing" - "time" - - "github.com/ory/hydra/integration" - . "github.com/ory/hydra/oauth2" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -var consentManagers = map[string]ConsentRequestManager{ - "memory": NewConsentRequestMemoryManager(), -} - -func connectToMySQLConsent() { - var db = integration.ConnectToMySQL() - s := NewConsentRequestSQLManager(db) - - if _, err := s.CreateSchemas(); err != nil { - log.Fatalf("Could not create postgres schema: %v", err) - } - - consentManagers["mysql"] = s -} - -func connectToPGConsent() { - var db = integration.ConnectToPostgres() - s := NewConsentRequestSQLManager(db) - - if _, err := s.CreateSchemas(); err != nil { - log.Fatalf("Could not create postgres schema: %v", err) - } - - consentManagers["postgres"] = s -} - -func tTestConsentRequestManagerReadWrite(t *testing.T) { - req := &ConsentRequest{ - ID: "id-1", - ClientID: "client-id", - RequestedScopes: []string{"foo", "bar"}, - GrantedScopes: []string{"baz", "bar"}, - CSRF: "some-csrf", - ExpiresAt: time.Now().UTC().Round(time.Minute), - Consent: ConsentRequestAccepted, - DenyReason: "some reason", - AccessTokenExtra: map[string]interface{}{"atfoo": "bar", "atbaz": "bar"}, - IDTokenExtra: map[string]interface{}{"idfoo": "bar", "idbaz": "bar"}, - RedirectURL: "https://redirect-me/foo", - Subject: "Peter", - } - - for k, m := range consentManagers { - t.Run(fmt.Sprintf("case=%s", k), func(t *testing.T) { - _, err := m.GetConsentRequest("1234") - assert.Error(t, err) - - require.NoError(t, m.PersistConsentRequest(req)) - - got, err := m.GetConsentRequest(req.ID) - require.NoError(t, err) - - require.Equal(t, req.ExpiresAt.Unix(), got.ExpiresAt.Unix()) - got.ExpiresAt = req.ExpiresAt - assert.EqualValues(t, req, got) - }) - } -} - -func TestConsentRequestManagerUpdate(t *testing.T) { - req := &ConsentRequest{ - ID: "id-2", - ClientID: "client-id", - RequestedScopes: []string{"foo", "bar"}, - GrantedScopes: []string{"baz", "bar"}, - CSRF: "some-csrf", - ExpiresAt: time.Now().UTC().Round(time.Minute), - Consent: ConsentRequestRejected, - DenyReason: "some reason", - AccessTokenExtra: map[string]interface{}{"atfoo": "bar", "atbaz": "bar"}, - IDTokenExtra: map[string]interface{}{"idfoo": "bar", "idbaz": "bar"}, - RedirectURL: "https://redirect-me/foo", - Subject: "Peter", - } - - for k, m := range consentManagers { - t.Run(fmt.Sprintf("case=%s", k), func(t *testing.T) { - require.NoError(t, m.PersistConsentRequest(req)) - - got, err := m.GetConsentRequest(req.ID) - require.NoError(t, err) - assert.False(t, got.IsConsentGranted()) - require.Equal(t, req.ExpiresAt.Unix(), got.ExpiresAt.Unix()) - got.ExpiresAt = req.ExpiresAt - assert.EqualValues(t, req, got) - - require.NoError(t, m.AcceptConsentRequest(req.ID, new(AcceptConsentRequestPayload))) - got, err = m.GetConsentRequest(req.ID) - require.NoError(t, err) - assert.True(t, got.IsConsentGranted()) - - require.NoError(t, m.RejectConsentRequest(req.ID, new(RejectConsentRequestPayload))) - got, err = m.GetConsentRequest(req.ID) - require.NoError(t, err) - assert.False(t, got.IsConsentGranted()) - }) - } -} diff --git a/oauth2/consent_sdk_test.go b/oauth2/consent_sdk_test.go deleted file mode 100644 index 17ab81e0767..00000000000 --- a/oauth2/consent_sdk_test.go +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Copyright © 2015-2018 Aeneas Rekkas - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * @author Aeneas Rekkas - * @copyright 2015-2018 Aeneas Rekkas - * @license Apache-2.0 - */ - -package oauth2_test - -import ( - "net/http" - "net/http/httptest" - "testing" - "time" - - "github.com/julienschmidt/httprouter" - "github.com/ory/herodot" - . "github.com/ory/hydra/oauth2" - hydra "github.com/ory/hydra/sdk/go/hydra/swagger" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestConsentSDK(t *testing.T) { - req := &ConsentRequest{ - ID: "id-3", - ClientID: "client-id", - RequestedScopes: []string{"foo", "bar"}, - GrantedScopes: []string{"baz", "bar"}, - CSRF: "some-csrf", - ExpiresAt: time.Now().UTC().Round(time.Minute), - Consent: ConsentRequestAccepted, - DenyReason: "some reason", - AccessTokenExtra: map[string]interface{}{"atfoo": "bar", "atbaz": "bar"}, - IDTokenExtra: map[string]interface{}{"idfoo": "bar", "idbaz": "bar"}, - RedirectURL: "https://redirect-me/foo", - Subject: "Peter", - } - - memm := NewConsentRequestMemoryManager() - - require.NoError(t, memm.PersistConsentRequest(req)) - h := &ConsentSessionHandler{M: memm, H: herodot.NewJSONWriter(nil)} - - r := httprouter.New() - h.SetRoutes(r) - server := httptest.NewServer(r) - - client := hydra.NewOAuth2ApiWithBasePath(server.URL) - - got, _, err := client.GetOAuth2ConsentRequest(req.ID) - require.NoError(t, err) - assert.EqualValues(t, req.ID, got.Id) - assert.EqualValues(t, req.ClientID, got.ClientId) - assert.EqualValues(t, req.RequestedScopes, got.RequestedScopes) - assert.EqualValues(t, req.RedirectURL, got.RedirectUrl) - - accept := hydra.ConsentRequestAcceptance{ - Subject: "some-subject", - GrantScopes: []string{"scope1", "scope2"}, - AccessTokenExtra: map[string]interface{}{"at": "bar"}, - IdTokenExtra: map[string]interface{}{"id": "bar"}, - } - - response, err := client.AcceptOAuth2ConsentRequest(req.ID, accept) - require.NoError(t, err) - assert.EqualValues(t, http.StatusNoContent, response.StatusCode) - - gotMem, err := memm.GetConsentRequest(req.ID) - require.NoError(t, err) - assert.Equal(t, accept.Subject, gotMem.Subject) - assert.Equal(t, accept.GrantScopes, gotMem.GrantedScopes) - assert.Equal(t, accept.AccessTokenExtra, gotMem.AccessTokenExtra) - assert.Equal(t, accept.IdTokenExtra, gotMem.IDTokenExtra) - assert.True(t, gotMem.IsConsentGranted()) - - response, err = client.RejectOAuth2ConsentRequest(req.ID, hydra.ConsentRequestRejection{Reason: "MyReason"}) - require.NoError(t, err) - assert.EqualValues(t, http.StatusNoContent, response.StatusCode) - - gotMem, err = memm.GetConsentRequest(req.ID) - require.NoError(t, err) - assert.Equal(t, "MyReason", gotMem.DenyReason) - assert.False(t, gotMem.IsConsentGranted()) -} diff --git a/oauth2/consent_strategy.go b/oauth2/consent_strategy.go deleted file mode 100644 index a445ad0acaf..00000000000 --- a/oauth2/consent_strategy.go +++ /dev/null @@ -1,148 +0,0 @@ -/* - * Copyright © 2015-2018 Aeneas Rekkas - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * @author Aeneas Rekkas - * @copyright 2015-2018 Aeneas Rekkas - * @license Apache-2.0 - */ - -package oauth2 - -import ( - "net/http" - "time" - - "github.com/gorilla/sessions" - "github.com/ory/fosite" - "github.com/ory/fosite/handler/openid" - ejwt "github.com/ory/fosite/token/jwt" - "github.com/pborman/uuid" - "github.com/pkg/errors" -) - -const ( - CookieCSRFKey = "consent_csrf" -) - -type DefaultConsentStrategy struct { - Issuer string - - KeyID string - DefaultIDTokenLifespan time.Duration - DefaultChallengeLifespan time.Duration - ConsentManager ConsentRequestManager -} - -func (s *DefaultConsentStrategy) validateSession(req fosite.AuthorizeRequester, consent *ConsentRequest, cookie *sessions.Session) error { - if j, ok := cookie.Values[CookieCSRFKey]; !ok { - return errors.Errorf("Session cookie is missing CSRF token") - } else if js, ok := j.(string); !ok { - return errors.Errorf("CSRF value in session cookie is not a string") - } else if js != consent.CSRF { - return errors.Errorf("CSRF value in session cookie does not match consent CSRF value") - } else if consent.CSRF != req.GetRequestForm().Get("consent_csrf") { - return errors.Errorf("CSRF value from query parameters does not match consent CSRF value") - } - - if time.Now().UTC().After(consent.ExpiresAt) { - return errors.Errorf("Consent session expired") - } - - if consent.ClientID != req.GetClient().GetID() { - return errors.Errorf("ClientID mismatch") - } - - if consent.Subject == "" { - return errors.Errorf("Subject key is empty or undefined in consent response, check your payload.") - } - - return nil -} - -func (s *DefaultConsentStrategy) ValidateConsentRequest(req fosite.AuthorizeRequester, session string, cookie *sessions.Session) (*Session, error) { - defer delete(cookie.Values, CookieCSRFKey) - - consent, err := s.ConsentManager.GetConsentRequest(session) - if err != nil { - return nil, errors.WithStack(err) - } - - if !consent.IsConsentGranted() { - err := errors.New("The resource owner denied consent for this request") - return nil, &fosite.RFC6749Error{ - Name: "rejected_consent_request", - Description: consent.DenyReason, - Debug: err.Error(), - Hint: consent.DenyReason, - Code: http.StatusUnauthorized, - } - } - - if err := s.validateSession(req, consent, cookie); err != nil { - if err := s.ConsentManager.RejectConsentRequest(session, &RejectConsentRequestPayload{ - Reason: "Unable to validate consent request", - }); err != nil { - return nil, err - } - return nil, err - } - - for _, scope := range consent.GrantedScopes { - req.GrantScope(scope) - } - - return &Session{ - DefaultSession: &openid.DefaultSession{ - Claims: &ejwt.IDTokenClaims{ - Audience: req.GetClient().GetID(), - Subject: consent.Subject, - Issuer: s.Issuer, - IssuedAt: time.Now().UTC(), - ExpiresAt: time.Now().UTC().Add(s.DefaultIDTokenLifespan), - AuthTime: time.Now().UTC(), - RequestedAt: time.Now().UTC(), - Extra: consent.IDTokenExtra, - }, - // required for lookup on jwk endpoint - Headers: &ejwt.Headers{Extra: map[string]interface{}{"kid": s.KeyID}}, - Subject: consent.Subject, - }, - Extra: consent.AccessTokenExtra, - }, err -} - -func (s *DefaultConsentStrategy) CreateConsentRequest(req fosite.AuthorizeRequester, redirectURL string, cookie *sessions.Session) (string, error) { - csrf := uuid.New() - id := uuid.New() - - cookie.Values[CookieCSRFKey] = csrf - consent := &ConsentRequest{ - ID: id, - CSRF: csrf, - GrantedScopes: []string{}, - RequestedScopes: req.GetRequestedScopes(), - ClientID: req.GetClient().GetID(), - ExpiresAt: time.Now().UTC().Add(s.DefaultChallengeLifespan), - RedirectURL: redirectURL + "&consent=" + id + "&consent_csrf=" + csrf, - AccessTokenExtra: map[string]interface{}{}, - IDTokenExtra: map[string]interface{}{}, - } - - if err := s.ConsentManager.PersistConsentRequest(consent); err != nil { - return "", errors.WithStack(err) - } - - return id, nil -} diff --git a/oauth2/consent_strategy_test.go b/oauth2/consent_strategy_test.go deleted file mode 100644 index 5b1dc3d7aa2..00000000000 --- a/oauth2/consent_strategy_test.go +++ /dev/null @@ -1,150 +0,0 @@ -/* - * Copyright © 2015-2018 Aeneas Rekkas - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * @author Aeneas Rekkas - * @copyright 2015-2018 Aeneas Rekkas - * @license Apache-2.0 - */ - -package oauth2 - -import ( - "fmt" - "net/url" - "testing" - "time" - - "github.com/gorilla/sessions" - "github.com/ory/fosite" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestConsentStrategy(t *testing.T) { - t.Run("suite=validate", func(t *testing.T) { - - strategy := &DefaultConsentStrategy{ConsentManager: NewConsentRequestMemoryManager()} - - require.NoError(t, strategy.ConsentManager.PersistConsentRequest(&ConsentRequest{ - ID: "not_granted", - Consent: ConsentRequestRejected, - })) - require.NoError(t, strategy.ConsentManager.PersistConsentRequest(&ConsentRequest{ - ID: "granted", - Consent: ConsentRequestAccepted, - ClientID: "client_id", - Subject: "peter", - CSRF: "csrf_token", - ExpiresAt: time.Now().UTC().Add(time.Hour), - })) - require.NoError(t, strategy.ConsentManager.PersistConsentRequest(&ConsentRequest{ - ID: "granted_csrf_cookie", - Consent: ConsentRequestAccepted, - ClientID: "client_id", - Subject: "peter", - CSRF: "csrf_token", - ExpiresAt: time.Now().UTC().Add(time.Hour), - })) - require.NoError(t, strategy.ConsentManager.PersistConsentRequest(&ConsentRequest{ - ID: "granted_csrf_request", - Consent: ConsentRequestAccepted, - ClientID: "client_id", - Subject: "peter", - CSRF: "csrf_token", - ExpiresAt: time.Now().UTC().Add(time.Hour), - })) - require.NoError(t, strategy.ConsentManager.PersistConsentRequest(&ConsentRequest{ - ID: "granted_expired", - Consent: ConsentRequestAccepted, - Subject: "peter", - ClientID: "client_id", - ExpiresAt: time.Now().UTC().Add(-time.Hour), - CSRF: "csrf_token", - })) - - for _, tc := range []struct { - req *fosite.AuthorizeRequest - session string - cookie *sessions.Session - expectErr bool - assert func(*testing.T, *Session) - d string - }{ - { - d: "invalid session", - session: "not_granted", - expectErr: true, - cookie: &sessions.Session{Values: map[interface{}]interface{}{CookieCSRFKey: "csrf_token"}}, - }, - { - d: "session expired", - session: "granted_expired", - expectErr: true, - req: &fosite.AuthorizeRequest{Request: fosite.Request{Client: &fosite.DefaultClient{ID: "client_id"}, Form: url.Values{"consent_csrf": {"csrf_token"}}}}, - cookie: &sessions.Session{Values: map[interface{}]interface{}{CookieCSRFKey: "csrf_token"}}, - }, - { - d: "granted", - session: "granted", - expectErr: false, - req: &fosite.AuthorizeRequest{Request: fosite.Request{Client: &fosite.DefaultClient{ID: "client_id"}, Form: url.Values{"consent_csrf": {"csrf_token"}}}}, - cookie: &sessions.Session{Values: map[interface{}]interface{}{CookieCSRFKey: "csrf_token"}}, - }, - { - d: "client mismatch", - session: "granted", - expectErr: true, - req: &fosite.AuthorizeRequest{Request: fosite.Request{Client: &fosite.DefaultClient{ID: "mismatch_client"}, Form: url.Values{"consent_csrf": {"csrf_token"}}}}, - cookie: &sessions.Session{Values: map[interface{}]interface{}{CookieCSRFKey: "csrf_token"}}, - }, - { - d: "consent request was not initiated by this user agent", - session: "granted_csrf_cookie", - expectErr: true, - req: &fosite.AuthorizeRequest{Request: fosite.Request{Client: &fosite.DefaultClient{ID: "client_id"}, Form: url.Values{"consent_csrf": {"csrf_token"}}}}, - cookie: &sessions.Session{Values: map[interface{}]interface{}{CookieCSRFKey: "very_different_csrf_token"}}, - assert: func(t *testing.T, session *Session) { - cr, err := strategy.ConsentManager.GetConsentRequest("granted_csrf_cookie") - require.NoError(t, err) - assert.False(t, cr.IsConsentGranted()) - }, - }, - { - d: "authorize url contains csrf token that does not match token set in consent request", - session: "granted_csrf_request", - expectErr: true, - req: &fosite.AuthorizeRequest{Request: fosite.Request{Client: &fosite.DefaultClient{ID: "client_id"}}}, - cookie: &sessions.Session{Values: map[interface{}]interface{}{CookieCSRFKey: "csrf_token"}}, - assert: func(t *testing.T, session *Session) { - cr, err := strategy.ConsentManager.GetConsentRequest("granted_csrf_request") - require.NoError(t, err) - assert.False(t, cr.IsConsentGranted()) - }, - }, - } { - t.Run(fmt.Sprintf("case=%s", tc.d), func(t *testing.T) { - res, err := strategy.ValidateConsentRequest(tc.req, tc.session, tc.cookie) - if tc.expectErr { - require.Error(t, err) - } else { - require.NoError(t, err) - if tc.assert != nil { - tc.assert(t, res) - } - } - }) - } - }) -} diff --git a/oauth2/doc.go b/oauth2/doc.go index 1acf1a60ee5..26ff4e392a2 100644 --- a/oauth2/doc.go +++ b/oauth2/doc.go @@ -20,26 +20,6 @@ package oauth2 -// ConsentRequest represents a consent request. -// swagger:model oAuth2ConsentRequest -type swaggerConsentRequest struct { - // ID is the id of this consent request. - ID string `json:"id"` - - // RequestedScopes represents a list of scopes that have been requested by the OAuth2 request initiator. - RequestedScopes []string `json:"requestedScopes,omitempty"` - - // ClientID is the client id that initiated the OAuth2 request. - ClientID string `json:"clientId"` - - // ExpiresAt is the time where the access request will expire. - ExpiresAt string `json:"expiresAt"` - - // Redirect URL is the URL where the user agent should be redirected to after the consent has been - // accepted or rejected. - RedirectURL string `json:"redirectUrl"` -} - // swagger:parameters revokeOAuth2Token type swaggerRevokeOAuth2TokenParameters struct { // in: formData @@ -47,28 +27,6 @@ type swaggerRevokeOAuth2TokenParameters struct { Token string `json:"token"` } -// swagger:parameters rejectOAuth2ConsentRequest -type swaggerRejectConsentRequest struct { - // in: path - // required: true - ID string `json:"id"` - - // in: body - // required: true - Body RejectConsentRequestPayload -} - -// swagger:parameters acceptOAuth2ConsentRequest -type swaggerAcceptConsentRequest struct { - // in: path - // required: true - ID string `json:"id"` - - // in: body - // required: true - Body AcceptConsentRequestPayload -} - // swagger:parameters flushInactiveOAuth2Tokens type swaggerFlushInactiveAccessTokens struct { // in: body @@ -233,13 +191,3 @@ type swaggerOAuthIntrospectionRequest struct { // in: formData Scope string `json:"scope"` } - -// swagger:parameters getOAuth2ConsentRequest acceptConsentRequest rejectConsentRequest -type swaggerOAuthConsentRequestPayload struct { - // The id of the OAuth 2.0 Consent Request. - // - // unique: true - // required: true - // in: path - ID string `json:"id"` -} diff --git a/oauth2/fosite_store_test.go b/oauth2/fosite_store_test.go index 187769a88b3..3124de3b6e3 100644 --- a/oauth2/fosite_store_test.go +++ b/oauth2/fosite_store_test.go @@ -58,8 +58,6 @@ func TestMain(m *testing.M) { integration.BootParallel([]func(){ connectToPG, connectToMySQL, - connectToPGConsent, - connectToMySQLConsent, }) } diff --git a/oauth2/handler.go b/oauth2/handler.go index c0d855629ad..cc3ec4daf17 100644 --- a/oauth2/handler.go +++ b/oauth2/handler.go @@ -23,23 +23,24 @@ package oauth2 import ( "context" "encoding/json" - "net" "net/http" - "net/url" "strings" "time" "github.com/julienschmidt/httprouter" "github.com/ory/fosite" + "github.com/ory/fosite/handler/openid" + "github.com/ory/fosite/token/jwt" + "github.com/ory/hydra/consent" "github.com/ory/hydra/pkg" "github.com/pkg/errors" - "github.com/sirupsen/logrus" ) const ( OpenIDConnectKeyName = "hydra.openid.id-token" - DefaultConsentPath = "/oauth2/consent-fallback" + DefaultConsentPath = "/oauth2/fallbacks/consent" + DefaultErrorPath = "/oauth2/fallbacks/error" TokenPath = "/oauth2/token" AuthPath = "/oauth2/auth" @@ -51,10 +52,6 @@ const ( IntrospectPath = "/oauth2/introspect" RevocationPath = "/oauth2/revoke" FlushPath = "/oauth2/flush" - - IntrospectScope = "hydra.introspect" - - consentCookieName = "consent_session" ) // swagger:model wellKnown @@ -133,6 +130,7 @@ func (h *Handler) SetRoutes(r *httprouter.Router) { r.GET(AuthPath, h.AuthHandler) r.POST(AuthPath, h.AuthHandler) r.GET(DefaultConsentPath, h.DefaultConsentHandler) + r.GET(DefaultErrorPath, h.DefaultErrorHandler) r.POST(IntrospectPath, h.IntrospectHandler) r.POST(RevocationPath, h.RevocationHandler) r.GET(WellKnownPath, h.WellKnownHandler) @@ -460,42 +458,39 @@ func (h *Handler) AuthHandler(w http.ResponseWriter, r *http.Request, _ httprout return } - // A session_token will be available if the user was authenticated an gave consent - consent := authorizeRequest.GetRequestForm().Get("consent") - if consent == "" { - // otherwise redirect to log in endpoint - if err := h.redirectToConsent(w, r, authorizeRequest); err != nil { - pkg.LogError(err, h.L) - h.writeAuthorizeError(w, authorizeRequest, err) - return - } - return - } - - cookie, err := h.CookieStore.Get(r, consentCookieName) - if err != nil { - pkg.LogError(err, h.L) - h.writeAuthorizeError(w, authorizeRequest, errors.Wrapf(fosite.ErrServerError, "Could not open session: %s", err)) + session, err := h.Consent.HandleOAuth2AuthorizationRequest(w, r, authorizeRequest) + if errors.Cause(err) == consent.ErrAbortOAuth2Request { + // do nothing return - } - - // decode consent_token claims - // verify anti-CSRF (inject state) and anti-replay token (expiry time, good value would be 10 seconds) - session, err := h.Consent.ValidateConsentRequest(authorizeRequest, consent, cookie) - if err != nil { + } else if err != nil { pkg.LogError(err, h.L) h.writeAuthorizeError(w, authorizeRequest, err) return } - if err := cookie.Save(r, w); err != nil { - pkg.LogError(err, h.L) - h.writeAuthorizeError(w, authorizeRequest, errors.Wrapf(fosite.ErrServerError, "Could not store session cookie: %s", err)) - return + for _, scope := range session.GrantedScope { + authorizeRequest.GrantScope(scope) } // done - response, err := h.OAuth2.NewAuthorizeResponse(ctx, authorizeRequest, session) + response, err := h.OAuth2.NewAuthorizeResponse(ctx, authorizeRequest, &Session{ + DefaultSession: &openid.DefaultSession{ + Claims: &jwt.IDTokenClaims{ + Audience: authorizeRequest.GetClient().GetID(), + Subject: session.ConsentRequest.Subject, + Issuer: h.IssuerURL, + IssuedAt: time.Now().UTC(), + ExpiresAt: time.Now().Add(h.IDTokenLifespan).UTC(), + AuthTime: time.Now().UTC(), + RequestedAt: time.Now().UTC(), + Extra: session.Session.IDToken, + }, + // required for lookup on jwk endpoint + Headers: &jwt.Headers{Extra: map[string]interface{}{"kid": h.IDTokenPublicKeyID}}, + Subject: session.ConsentRequest.Subject, + }, + Extra: session.Session.AccessToken, + }) if err != nil { pkg.LogError(err, h.L) h.writeAuthorizeError(w, authorizeRequest, err) @@ -505,54 +500,11 @@ func (h *Handler) AuthHandler(w http.ResponseWriter, r *http.Request, _ httprout h.OAuth2.WriteAuthorizeResponse(w, authorizeRequest, response) } -func (h *Handler) redirectToConsent(w http.ResponseWriter, r *http.Request, authorizeRequest fosite.AuthorizeRequester) error { - // Error can be ignored because a session will always be returned - cookie, _ := h.CookieStore.Get(r, consentCookieName) - - host, _, err := net.SplitHostPort(r.Host) - if err != nil { - host = r.Host - } - - authUrl, err := url.Parse(h.Issuer + AuthPath) - if err != nil { - return err - } - authHost, _, err := net.SplitHostPort(authUrl.Host) - if err != nil { - authHost = authUrl.Host - } - if authHost != host { - h.L.WithFields(logrus.Fields{ - "request_host": host, - "issuer_host": authHost, - }).Warnln("Host from auth request does not match issuer host. The consent return redirect may fail.") - } - authUrl.RawQuery = r.URL.RawQuery - - challenge, err := h.Consent.CreateConsentRequest(authorizeRequest, authUrl.String(), cookie) - if err != nil { - return err - } - - p := h.ConsentURL - q := p.Query() - q.Set("consent", challenge) - p.RawQuery = q.Encode() - - if err := cookie.Save(r, w); err != nil { - return err - } - - http.Redirect(w, r, p.String(), http.StatusFound) - return nil -} - func (h *Handler) writeAuthorizeError(w http.ResponseWriter, ar fosite.AuthorizeRequester, err error) { if !ar.IsRedirectURIValid() { var rfcerr = fosite.ErrorToRFC6749Error(err) - redirectURI := h.ConsentURL + redirectURI := h.ErrorURL query := redirectURI.Query() query.Add("error", rfcerr.Name) query.Add("error_description", rfcerr.Description) diff --git a/oauth2/handler_default_consent_endpoint.go b/oauth2/handler_fallback_endpoints.go similarity index 50% rename from oauth2/handler_default_consent_endpoint.go rename to oauth2/handler_fallback_endpoints.go index 14d62a67963..d52d2fcc5ba 100644 --- a/oauth2/handler_default_consent_endpoint.go +++ b/oauth2/handler_fallback_endpoints.go @@ -21,29 +21,56 @@ package oauth2 import ( + "fmt" "net/http" "github.com/julienschmidt/httprouter" ) func (h *Handler) DefaultConsentHandler(w http.ResponseWriter, r *http.Request, _ httprouter.Params) { - h.L.Warnln("It looks like no consent endpoint was set. All OAuth2 flows except client credentials will fail.") + h.L.Warnln("It looks like no consent/login URL was set. All OAuth2 flows except client credentials will fail.") w.Write([]byte(` - Misconfigured consent endpoint + Misconfigured consent/login URL

- It looks like you forgot to set the consent endpoint url, which can be set using the CONSENT_URL + It looks like you forgot to set the consent/login provider url, which can be set using the CONSENT_URL and LOGIN_URL environment variable.

- If you are an administrator, please read + If you are an administrator, please read the guide to understand what you need to do. If you are a user, please contact the administrator.

`)) } + +func (h *Handler) DefaultErrorHandler(w http.ResponseWriter, r *http.Request, _ httprouter.Params) { + h.L.Warnln("It looks like no OAuth2 Error URL was set.") + + fmt.Fprintf(w, ` + + + An OAuth 2.0 Error Occurred + + +

+ The OAuth2 request resulted in an error. +

+
    +
  • Error: %s
  • +
  • Description: %s
  • +
+

+ You are seeing this default error page because the administrator has not set a dedicated error URL. + If you are an administrator, please read the guide to understand what you + need to do. If you are a user, please contact the administrator. +

+ + +`, r.URL.Query().Get("error"), r.URL.Query().Get("error_description")) +} diff --git a/oauth2/handler_default_consent_endpoint_test.go b/oauth2/handler_fallback_endpoints_test.go similarity index 100% rename from oauth2/handler_default_consent_endpoint_test.go rename to oauth2/handler_fallback_endpoints_test.go diff --git a/oauth2/handler_struct.go b/oauth2/handler_struct.go index cfdff75b4a3..2b5b936054e 100644 --- a/oauth2/handler_struct.go +++ b/oauth2/handler_struct.go @@ -27,44 +27,36 @@ import ( "github.com/gorilla/sessions" "github.com/ory/fosite" "github.com/ory/herodot" + "github.com/ory/hydra/consent" "github.com/ory/hydra/pkg" "github.com/sirupsen/logrus" ) type Handler struct { OAuth2 fosite.OAuth2Provider - Consent ConsentStrategy + Consent consent.Strategy Storage pkg.FositeStorer H herodot.Writer ForcedHTTP bool - ConsentURL url.URL + ErrorURL url.URL AccessTokenLifespan time.Duration + IDTokenLifespan time.Duration CookieStore sessions.Store + IDTokenPublicKeyID string + + IssuerURL string + L logrus.FieldLogger ScopeStrategy fosite.ScopeStrategy Issuer string - ResourcePrefix string - ClaimsSupported string ScopesSupported string UserinfoEndpoint string } - -func (h *Handler) PrefixResource(resource string) string { - if h.ResourcePrefix == "" { - h.ResourcePrefix = "rn:hydra" - } - - if h.ResourcePrefix[len(h.ResourcePrefix)-1] == ':' { - h.ResourcePrefix = h.ResourcePrefix[:len(h.ResourcePrefix)-1] - } - - return h.ResourcePrefix + ":" + resource -} diff --git a/oauth2/handler_test.go b/oauth2/handler_test.go index db1b5a2fd21..e93e0501fd9 100644 --- a/oauth2/handler_test.go +++ b/oauth2/handler_test.go @@ -22,8 +22,6 @@ package oauth2_test import ( "context" - "crypto/rand" - "crypto/rsa" "encoding/json" "net/http" "net/http/httptest" @@ -31,16 +29,12 @@ import ( "testing" "time" - "github.com/gorilla/sessions" "github.com/julienschmidt/httprouter" "github.com/ory/fosite" - "github.com/ory/fosite/compose" - "github.com/ory/fosite/storage" "github.com/ory/herodot" "github.com/ory/hydra/client" "github.com/ory/hydra/oauth2" hydra "github.com/ory/hydra/sdk/go/hydra/swagger" - "github.com/sirupsen/logrus" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -181,66 +175,3 @@ func TestHandlerWellKnown(t *testing.T) { assert.EqualValues(t, wellKnownResp.ScopesSupported, []string{"offline", "openid", "foo", "bar"}) assert.Equal(t, wellKnownResp.UserinfoEndpoint, "bar") } - -type FakeConsentStrategy struct { - RedirectURL string -} - -func (s *FakeConsentStrategy) ValidateConsentRequest(authorizeRequest fosite.AuthorizeRequester, token string, session *sessions.Session) (claims *oauth2.Session, err error) { - return nil, nil -} - -func (s *FakeConsentStrategy) CreateConsentRequest(authorizeRequest fosite.AuthorizeRequester, redirectURL string, session *sessions.Session) (token string, err error) { - s.RedirectURL = redirectURL - return "token", nil -} - -func TestIssuerRedirect(t *testing.T) { - storage := storage.NewExampleStore() - secret := []byte("my super secret password password password password") - config := compose.Config{} - privateKey, _ := rsa.GenerateKey(rand.Reader, 2048) - - consentUrl, _ := url.Parse("http://consent.localhost") - - cs := &FakeConsentStrategy{} - - h := &oauth2.Handler{ - H: herodot.NewJSONWriter(nil), - Issuer: "http://127.0.0.1/some/proxied/path", - OAuth2: compose.ComposeAllEnabled(&config, storage, secret, privateKey), - ConsentURL: *consentUrl, - ScopeStrategy: fosite.WildcardScopeStrategy, - CookieStore: sessions.NewCookieStore([]byte("my super secret password")), - Consent: cs, - L: logrus.New(), - } - - r := httprouter.New() - h.SetRoutes(r) - ts := httptest.NewServer(r) - - authUrl, _ := url.Parse(ts.URL) - v := url.Values{} - v.Set("response_type", "code") - v.Set("client_id", "my-client") - v.Set("redirect_uri", "http://localhost:3846/callback") - v.Set("scope", "openid") - v.Set("state", "my super secret state") - authUrl.Path = "/oauth2/auth" - authUrl.RawQuery = v.Encode() - - client := &http.Client{ - CheckRedirect: func(req *http.Request, via []*http.Request) error { - return http.ErrUseLastResponse - }, - } - - res, _ := client.Get(authUrl.String()) - - authRedirect, _ := url.Parse(cs.RedirectURL) - assert.Equal(t, "/some/proxied/path/oauth2/auth", authRedirect.Path, "The redirect URL sent in the challenge includes the full issuer path") - assert.Equal(t, authUrl.Query(), authRedirect.Query(), "The auth redirect should have the same parameters with the addition of challenge") - - defer res.Body.Close() -} diff --git a/oauth2/oauth2_auth_code_test.go b/oauth2/oauth2_auth_code_test.go index 503e047cfba..d22bf5fa856 100644 --- a/oauth2/oauth2_auth_code_test.go +++ b/oauth2/oauth2_auth_code_test.go @@ -21,6 +21,8 @@ package oauth2_test import ( + "bytes" + "encoding/json" "io/ioutil" "net/http" "net/http/cookiejar" @@ -29,51 +31,20 @@ import ( "testing" "time" - "encoding/json" - - "bytes" - "github.com/julienschmidt/httprouter" - hydra "github.com/ory/hydra/sdk/go/hydra/swagger" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "golang.org/x/oauth2" ) func TestAuthCode(t *testing.T) { - var consentHandler httprouter.Handle var callbackHandler httprouter.Handle - - router.GET("/consent", func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) { - consentHandler(w, r, ps) - }) router.GET("/callback", func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) { callbackHandler(w, r, ps) }) t.Run("case=test accept consent request", func(t *testing.T) { var code string - var validConsent bool - - consentHandler = func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) { - cr, response, err := consentClient.GetOAuth2ConsentRequest(r.URL.Query().Get("consent")) - assert.NoError(t, err) - assert.Equal(t, http.StatusOK, response.StatusCode) - - assert.EqualValues(t, []string{"hydra.*", "offline", "openid"}, cr.RequestedScopes) - assert.Equal(t, r.URL.Query().Get("consent"), cr.Id) - assert.True(t, strings.Contains(cr.RedirectUrl, "oauth2/auth?client_id=app-client")) - - response, err = consentClient.AcceptOAuth2ConsentRequest(r.URL.Query().Get("consent"), hydra.ConsentRequestAcceptance{ - Subject: "foo", - GrantScopes: []string{"hydra.*", "offline", "openid"}, - }) - require.NoError(t, err) - assert.Equal(t, http.StatusNoContent, response.StatusCode) - - http.Redirect(w, r, cr.RedirectUrl, http.StatusFound) - validConsent = true - } callbackHandler = func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) { code = r.URL.Query().Get("code") @@ -91,7 +62,6 @@ func TestAuthCode(t *testing.T) { _, err = ioutil.ReadAll(resp.Body) require.NoError(t, err) - assert.True(t, validConsent) require.NotEmpty(t, code) token, err := oauthConfig.Exchange(oauth2.NoContext, code) @@ -147,25 +117,13 @@ func TestAuthCode(t *testing.T) { }) t.Run("case=test deny consent request", func(t *testing.T) { - var validConsent bool - - consentHandler = func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) { - cr, response, err := consentClient.GetOAuth2ConsentRequest(r.URL.Query().Get("consent")) - assert.NoError(t, err) - assert.Equal(t, http.StatusOK, response.StatusCode) + consentStrategy.deny = true - response, err = consentClient.RejectOAuth2ConsentRequest(r.URL.Query().Get("consent"), hydra.ConsentRequestRejection{Reason: "some reason"}) - require.NoError(t, err) - assert.Equal(t, http.StatusNoContent, response.StatusCode) - - http.Redirect(w, r, cr.RedirectUrl, http.StatusFound) - validConsent = true - } callbackHandler = func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) { t.Logf("GOT URL: %s", r.URL.String()) - assert.Equal(t, "some reason", r.URL.Query().Get("error_description")) - assert.Equal(t, "rejected_consent_request", r.URL.Query().Get("error")) + assert.Equal(t, "The request is not allowed", r.URL.Query().Get("error_description")) + assert.Equal(t, "request_forbidden", r.URL.Query().Get("error")) w.WriteHeader(http.StatusNoContent) } @@ -177,8 +135,9 @@ func TestAuthCode(t *testing.T) { require.NoError(t, err) defer resp.Body.Close() - assert.True(t, validConsent) assert.Equal(t, http.StatusNoContent, resp.StatusCode) + + consentStrategy.deny = false }) } diff --git a/oauth2/oauth2_test.go b/oauth2/oauth2_test.go index 7b41d642bb5..e661a55ba59 100644 --- a/oauth2/oauth2_test.go +++ b/oauth2/oauth2_test.go @@ -21,8 +21,8 @@ package oauth2_test import ( + "net/http" "net/http/httptest" - "net/url" "time" "github.com/gorilla/sessions" @@ -31,9 +31,9 @@ import ( "github.com/ory/fosite/compose" "github.com/ory/herodot" hc "github.com/ory/hydra/client" + "github.com/ory/hydra/consent" . "github.com/ory/hydra/oauth2" "github.com/ory/hydra/pkg" - hydra "github.com/ory/hydra/sdk/go/hydra/swagger" "github.com/sirupsen/logrus" "golang.org/x/oauth2" "golang.org/x/oauth2/clientcredentials" @@ -54,6 +54,27 @@ var fc = &compose.Config{ AccessTokenLifespan: time.Second, } +type consentMock struct{ deny bool } + +func (c *consentMock) HandleOAuth2AuthorizationRequest(w http.ResponseWriter, r *http.Request, req fosite.AuthorizeRequester) (*consent.HandledConsentRequest, error) { + if c.deny { + return nil, fosite.ErrRequestForbidden + } + + return &consent.HandledConsentRequest{ + ConsentRequest: &consent.ConsentRequest{ + Subject: "foo", + }, + GrantedScope: []string{"offline", "openid", "hydra.*"}, + Session: &consent.ConsentRequestSessionData{ + AccessToken: map[string]interface{}{}, + IDToken: map[string]interface{}{}, + }, + }, nil +} + +var consentStrategy = &consentMock{} + var handler = &Handler{ OAuth2: compose.Compose( fc, @@ -73,17 +94,13 @@ var handler = &Handler{ compose.OAuth2TokenRevocationFactory, compose.OAuth2TokenIntrospectionFactory, ), - Consent: &DefaultConsentStrategy{ - Issuer: "http://hydra.localhost", - ConsentManager: consentManager, - DefaultChallengeLifespan: time.Hour, - DefaultIDTokenLifespan: time.Hour * 24, - }, - CookieStore: sessions.NewCookieStore([]byte("foo-secret")), - ForcedHTTP: true, - L: logrus.New(), - ScopeStrategy: fosite.HierarchicScopeStrategy, - H: herodot.NewJSONWriter(nil), + Consent: consentStrategy, + CookieStore: sessions.NewCookieStore([]byte("foo-secret")), + ForcedHTTP: true, + L: logrus.New(), + ScopeStrategy: fosite.HierarchicScopeStrategy, + H: herodot.NewJSONWriter(nil), + IDTokenLifespan: time.Minute, } var router = httprouter.New() @@ -91,27 +108,13 @@ var ts *httptest.Server var oauthConfig *oauth2.Config var oauthClientConfig *clientcredentials.Config -var consentHandler *ConsentSessionHandler -var consentManager = NewConsentRequestMemoryManager() -var consentClient *hydra.OAuth2Api - func init() { - consentHandler = &ConsentSessionHandler{ - H: herodot.NewJSONWriter(nil), - M: consentManager, - } - ts = httptest.NewServer(router) handler.Issuer = ts.URL handler.SetRoutes(router) - consentHandler.SetRoutes(router) h, _ := hasher.Hash([]byte("secret")) - consentClient = hydra.NewOAuth2ApiWithBasePath(ts.URL) - - c, _ := url.Parse(ts.URL + "/consent") - handler.ConsentURL = *c store.Manager.(*hc.MemoryManager).Clients = append(store.Manager.(*hc.MemoryManager).Clients, hc.Client{ ID: "app-client", diff --git a/oauth2/session.go b/oauth2/session.go index c116be9045e..ef045594f5d 100644 --- a/oauth2/session.go +++ b/oauth2/session.go @@ -14,7 +14,7 @@ * limitations under the License. * * @author Aeneas Rekkas - * @copyright 2015-2018 Aeneas Rekkas + * @Copyright 2017-2018 Aeneas Rekkas * @license Apache-2.0 */ @@ -40,6 +40,8 @@ func NewSession(subject string) *Session { Headers: new(jwt.Headers), Subject: subject, }, + Audience: []string{}, + Extra: map[string]interface{}{}, } } diff --git a/pkg/joinURL.go b/pkg/joinURL.go deleted file mode 100644 index c6beecc76d6..00000000000 --- a/pkg/joinURL.go +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright © 2015-2018 Aeneas Rekkas - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * @author Aeneas Rekkas - * @copyright 2015-2018 Aeneas Rekkas - * @license Apache-2.0 - */ - -package pkg - -import ( - "fmt" - "net/url" - "path" -) - -func JoinURLStrings(host string, parts ...string) string { - var trailing string - - last := parts[len(parts)-1] - if last[len(last)-1:] == "/" { - trailing = "/" - } - - u, err := url.Parse(host) - if err != nil { - return fmt.Sprintf("%s%s", path.Join(append([]string{u.Path}, parts...)...), trailing) - } - - if u.Path == "" { - u.Path = "/" - } - return fmt.Sprintf("%s://%s%s%s", u.Scheme, u.Host, path.Join(append([]string{u.Path}, parts...)...), trailing) -} diff --git a/pkg/joinURL_test.go b/pkg/joinURL_test.go deleted file mode 100644 index d91cff5c20f..00000000000 --- a/pkg/joinURL_test.go +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright © 2015-2018 Aeneas Rekkas - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * @author Aeneas Rekkas - * @copyright 2015-2018 Aeneas Rekkas - * @license Apache-2.0 - */ - -package pkg - -import ( - "testing" - - "github.com/stretchr/testify/assert" -) - -func TestJoinURLStrings(t *testing.T) { - for k, c := range []struct { - give []string - get string - }{ - { - give: []string{"http://localhost/", "/home"}, - get: "http://localhost/home", - }, - { - give: []string{"http://localhost", "/home"}, - get: "http://localhost/home", - }, - { - give: []string{"https://localhost/", "/home"}, - get: "https://localhost/home", - }, - { - give: []string{"http://localhost/", "/home", "home/", "/home/"}, - get: "http://localhost/home/home/home/", - }, - } { - assert.Equal(t, c.get, JoinURLStrings(c.give[0], c.give[1:]...), "Case %d", k) - } -} diff --git a/pkg/url.go b/pkg/url.go deleted file mode 100644 index cc5b8fe780a..00000000000 --- a/pkg/url.go +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright © 2015-2018 Aeneas Rekkas - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * @author Aeneas Rekkas - * @copyright 2015-2018 Aeneas Rekkas - * @license Apache-2.0 - */ - -package pkg - -import ( - "net/url" - "path" -) - -func CopyURL(u *url.URL) *url.URL { - a := new(url.URL) - *a = *u - return a -} - -func JoinURL(u *url.URL, args ...string) (ep *url.URL) { - ep = CopyURL(u) - ep.Path = path.Join(append([]string{ep.Path}, args...)...) - return ep -} diff --git a/sdk/go/hydra/sdk_api.go b/sdk/go/hydra/sdk_api.go index 6334a295551..9af379679ca 100644 --- a/sdk/go/hydra/sdk_api.go +++ b/sdk/go/hydra/sdk_api.go @@ -46,15 +46,19 @@ type JWKApi interface { } type OAuth2API interface { - AcceptOAuth2ConsentRequest(id string, body swagger.ConsentRequestAcceptance) (*swagger.APIResponse, error) + AcceptConsentRequest(challenge string, body swagger.AcceptConsentRequest) (*swagger.CompletedRequest, *swagger.APIResponse, error) + AcceptLoginRequest(challenge string, body swagger.AcceptLoginRequest) (*swagger.CompletedRequest, *swagger.APIResponse, error) + RejectConsentRequest(challenge string, body swagger.RejectRequest) (*swagger.CompletedRequest, *swagger.APIResponse, error) + RejectLoginRequest(challenge string, body swagger.RejectRequest) (*swagger.CompletedRequest, *swagger.APIResponse, error) + GetLoginRequest(challenge string) (*swagger.LoginRequest, *swagger.APIResponse, error) + GetConsentRequest(challenge string) (*swagger.ConsentRequest, *swagger.APIResponse, error) + CreateOAuth2Client(body swagger.OAuth2Client) (*swagger.OAuth2Client, *swagger.APIResponse, error) DeleteOAuth2Client(id string) (*swagger.APIResponse, error) GetOAuth2Client(id string) (*swagger.OAuth2Client, *swagger.APIResponse, error) - GetOAuth2ConsentRequest(id string) (*swagger.OAuth2ConsentRequest, *swagger.APIResponse, error) GetWellKnown() (*swagger.WellKnown, *swagger.APIResponse, error) IntrospectOAuth2Token(token string, scope string) (*swagger.OAuth2TokenIntrospection, *swagger.APIResponse, error) ListOAuth2Clients(limit int64, offset int64) ([]swagger.OAuth2Client, *swagger.APIResponse, error) - RejectOAuth2ConsentRequest(id string, body swagger.ConsentRequestRejection) (*swagger.APIResponse, error) RevokeOAuth2Token(token string) (*swagger.APIResponse, error) UpdateOAuth2Client(id string, body swagger.OAuth2Client) (*swagger.OAuth2Client, *swagger.APIResponse, error) diff --git a/sdk/go/hydra/swagger/README.md b/sdk/go/hydra/swagger/README.md index 272e2b63ab6..2bbbebe9c28 100644 --- a/sdk/go/hydra/swagger/README.md +++ b/sdk/go/hydra/swagger/README.md @@ -30,18 +30,21 @@ Class | Method | HTTP request | Description *JsonWebKeyApi* | [**GetJsonWebKeySet**](docs/JsonWebKeyApi.md#getjsonwebkeyset) | **Get** /keys/{set} | Retrieve a JSON Web Key Set *JsonWebKeyApi* | [**UpdateJsonWebKey**](docs/JsonWebKeyApi.md#updatejsonwebkey) | **Put** /keys/{set}/{kid} | Update a JSON Web Key *JsonWebKeyApi* | [**UpdateJsonWebKeySet**](docs/JsonWebKeyApi.md#updatejsonwebkeyset) | **Put** /keys/{set} | Update a JSON Web Key Set -*OAuth2Api* | [**AcceptOAuth2ConsentRequest**](docs/OAuth2Api.md#acceptoauth2consentrequest) | **Patch** /oauth2/consent/requests/{id}/accept | Accept a consent request +*OAuth2Api* | [**AcceptConsentRequest**](docs/OAuth2Api.md#acceptconsentrequest) | **Put** /oauth2/auth/requests/consent/{challenge}/accept | Accept an consent request +*OAuth2Api* | [**AcceptLoginRequest**](docs/OAuth2Api.md#acceptloginrequest) | **Put** /oauth2/auth/requests/login/{challenge}/accept | Accept an login request *OAuth2Api* | [**CreateOAuth2Client**](docs/OAuth2Api.md#createoauth2client) | **Post** /clients | Create an OAuth 2.0 client *OAuth2Api* | [**DeleteOAuth2Client**](docs/OAuth2Api.md#deleteoauth2client) | **Delete** /clients/{id} | Deletes an OAuth 2.0 Client *OAuth2Api* | [**FlushInactiveOAuth2Tokens**](docs/OAuth2Api.md#flushinactiveoauth2tokens) | **Post** /oauth2/flush | Flush Expired OAuth2 Access Tokens +*OAuth2Api* | [**GetConsentRequest**](docs/OAuth2Api.md#getconsentrequest) | **Get** /oauth2/auth/requests/consent/{challenge} | Get consent request information +*OAuth2Api* | [**GetLoginRequest**](docs/OAuth2Api.md#getloginrequest) | **Get** /oauth2/auth/requests/login/{challenge} | Get an login request *OAuth2Api* | [**GetOAuth2Client**](docs/OAuth2Api.md#getoauth2client) | **Get** /clients/{id} | Get an OAuth 2.0 Client. -*OAuth2Api* | [**GetOAuth2ConsentRequest**](docs/OAuth2Api.md#getoauth2consentrequest) | **Get** /oauth2/consent/requests/{id} | Receive consent request information *OAuth2Api* | [**GetWellKnown**](docs/OAuth2Api.md#getwellknown) | **Get** /.well-known/openid-configuration | Server well known configuration *OAuth2Api* | [**IntrospectOAuth2Token**](docs/OAuth2Api.md#introspectoauth2token) | **Post** /oauth2/introspect | Introspect OAuth2 tokens *OAuth2Api* | [**ListOAuth2Clients**](docs/OAuth2Api.md#listoauth2clients) | **Get** /clients | List OAuth 2.0 Clients *OAuth2Api* | [**OauthAuth**](docs/OAuth2Api.md#oauthauth) | **Get** /oauth2/auth | The OAuth 2.0 authorize endpoint *OAuth2Api* | [**OauthToken**](docs/OAuth2Api.md#oauthtoken) | **Post** /oauth2/token | The OAuth 2.0 token endpoint -*OAuth2Api* | [**RejectOAuth2ConsentRequest**](docs/OAuth2Api.md#rejectoauth2consentrequest) | **Patch** /oauth2/consent/requests/{id}/reject | Reject a consent request +*OAuth2Api* | [**RejectConsentRequest**](docs/OAuth2Api.md#rejectconsentrequest) | **Put** /oauth2/auth/requests/consent/{challenge}/reject | Reject an consent request +*OAuth2Api* | [**RejectLoginRequest**](docs/OAuth2Api.md#rejectloginrequest) | **Put** /oauth2/auth/requests/login/{challenge}/reject | Reject an logout request *OAuth2Api* | [**RevokeOAuth2Token**](docs/OAuth2Api.md#revokeoauth2token) | **Post** /oauth2/revoke | Revoke OAuth2 tokens *OAuth2Api* | [**UpdateOAuth2Client**](docs/OAuth2Api.md#updateoauth2client) | **Put** /clients/{id} | Update an OAuth 2.0 Client *OAuth2Api* | [**Userinfo**](docs/OAuth2Api.md#userinfo) | **Post** /userinfo | OpenID Connect Userinfo @@ -50,10 +53,12 @@ Class | Method | HTTP request | Description ## Documentation For Models + - [AcceptConsentRequest](docs/AcceptConsentRequest.md) + - [AcceptLoginRequest](docs/AcceptLoginRequest.md) + - [AuthenticationSession](docs/AuthenticationSession.md) + - [CompletedRequest](docs/CompletedRequest.md) - [ConsentRequest](docs/ConsentRequest.md) - - [ConsentRequestAcceptance](docs/ConsentRequestAcceptance.md) - - [ConsentRequestManager](docs/ConsentRequestManager.md) - - [ConsentRequestRejection](docs/ConsentRequestRejection.md) + - [ConsentRequestSession](docs/ConsentRequestSession.md) - [FlushInactiveOAuth2TokensRequest](docs/FlushInactiveOAuth2TokensRequest.md) - [Handler](docs/Handler.md) - [InlineResponse200](docs/InlineResponse200.md) @@ -63,22 +68,21 @@ Class | Method | HTTP request | Description - [JsonWebKeySet](docs/JsonWebKeySet.md) - [JsonWebKeySetGeneratorRequest](docs/JsonWebKeySetGeneratorRequest.md) - [KeyGenerator](docs/KeyGenerator.md) + - [LoginRequest](docs/LoginRequest.md) - [Manager](docs/Manager.md) - [OAuth2Client](docs/OAuth2Client.md) - - [OAuth2ConsentRequest](docs/OAuth2ConsentRequest.md) - [OAuth2TokenIntrospection](docs/OAuth2TokenIntrospection.md) - [OauthTokenResponse](docs/OauthTokenResponse.md) + - [OpenIdConnectContext](docs/OpenIdConnectContext.md) - [RawMessage](docs/RawMessage.md) - - [SwaggerAcceptConsentRequest](docs/SwaggerAcceptConsentRequest.md) + - [RejectRequest](docs/RejectRequest.md) - [SwaggerFlushInactiveAccessTokens](docs/SwaggerFlushInactiveAccessTokens.md) - [SwaggerJsonWebKeyQuery](docs/SwaggerJsonWebKeyQuery.md) - [SwaggerJwkCreateSet](docs/SwaggerJwkCreateSet.md) - [SwaggerJwkSetQuery](docs/SwaggerJwkSetQuery.md) - [SwaggerJwkUpdateSet](docs/SwaggerJwkUpdateSet.md) - [SwaggerJwkUpdateSetKey](docs/SwaggerJwkUpdateSetKey.md) - - [SwaggerOAuthConsentRequestPayload](docs/SwaggerOAuthConsentRequestPayload.md) - [SwaggerOAuthIntrospectionRequest](docs/SwaggerOAuthIntrospectionRequest.md) - - [SwaggerRejectConsentRequest](docs/SwaggerRejectConsentRequest.md) - [SwaggerRevokeOAuth2TokenParameters](docs/SwaggerRevokeOAuth2TokenParameters.md) - [UserinfoResponse](docs/UserinfoResponse.md) - [WellKnown](docs/WellKnown.md) diff --git a/sdk/go/hydra/swagger/accept_consent_request.go b/sdk/go/hydra/swagger/accept_consent_request.go new file mode 100644 index 00000000000..e041301f7e2 --- /dev/null +++ b/sdk/go/hydra/swagger/accept_consent_request.go @@ -0,0 +1,25 @@ +/* + * ORY Hydra - Cloud Native OAuth 2.0 and OpenID Connect Server + * + * Welcome to the ORY Hydra HTTP API documentation. You will find documentation for all HTTP APIs here. Keep in mind that this document reflects the latest branch, always. Support for versioned documentation is coming in the future. + * + * OpenAPI spec version: Latest + * Contact: hi@ory.am + * Generated by: https://github.com/swagger-api/swagger-codegen.git + */ + +package swagger + +type AcceptConsentRequest struct { + + // GrantScope sets the scope the user authorized the client to use. Should be a subset of `requested_scope` + GrantScope []string `json:"grant_scope,omitempty"` + + // Remember, if set to true, tells ORY Hydra to remember this consent authorization and reuse it if the same client asks the same user for the same, or a subset of, scope. + Remember bool `json:"remember,omitempty"` + + // RememberFor sets how long the consent authorization should be remembered for in seconds. If set to `0`, the authorization will be remembered indefinitely. + RememberFor int64 `json:"remember_for,omitempty"` + + Session ConsentRequestSession `json:"session,omitempty"` +} diff --git a/sdk/go/hydra/swagger/accept_login_request.go b/sdk/go/hydra/swagger/accept_login_request.go new file mode 100644 index 00000000000..2c61ddca071 --- /dev/null +++ b/sdk/go/hydra/swagger/accept_login_request.go @@ -0,0 +1,26 @@ +/* + * ORY Hydra - Cloud Native OAuth 2.0 and OpenID Connect Server + * + * Welcome to the ORY Hydra HTTP API documentation. You will find documentation for all HTTP APIs here. Keep in mind that this document reflects the latest branch, always. Support for versioned documentation is coming in the future. + * + * OpenAPI spec version: Latest + * Contact: hi@ory.am + * Generated by: https://github.com/swagger-api/swagger-codegen.git + */ + +package swagger + +type AcceptLoginRequest struct { + + // ACR sets the Authentication AuthorizationContext Class Reference value for this authentication session. You can use it to express that, for example, a user authenticated using two factor authentication. + Acr string `json:"acr,omitempty"` + + // Remember, if set to true, tells ORY Hydra to remember this user by telling the user agent (browser) to store a cookie with authentication data. If the same user performs another OAuth 2.0 Authorization Request, he/she will not be asked to log in again. + Remember bool `json:"remember,omitempty"` + + // RememberFor sets how long the authentication should be remembered for in seconds. If set to `0`, the authorization will be remembered indefinitely. + RememberFor int64 `json:"remember_for,omitempty"` + + // Subject is the user ID of the end-user that authenticated. + Subject string `json:"subject,omitempty"` +} diff --git a/sdk/go/hydra/swagger/swagger_o_auth_consent_request_payload.go b/sdk/go/hydra/swagger/authentication_session.go similarity index 69% rename from sdk/go/hydra/swagger/swagger_o_auth_consent_request_payload.go rename to sdk/go/hydra/swagger/authentication_session.go index 3c761f9b208..6e927ef86d6 100644 --- a/sdk/go/hydra/swagger/swagger_o_auth_consent_request_payload.go +++ b/sdk/go/hydra/swagger/authentication_session.go @@ -10,8 +10,14 @@ package swagger -type SwaggerOAuthConsentRequestPayload struct { +import ( + "time" +) - // The id of the OAuth 2.0 Consent Request. - Id string `json:"id"` +type AuthenticationSession struct { + AuthenticatedAt time.Time `json:"AuthenticatedAt,omitempty"` + + ID string `json:"ID,omitempty"` + + Subject string `json:"Subject,omitempty"` } diff --git a/sdk/go/hydra/swagger/consent_request_rejection.go b/sdk/go/hydra/swagger/completed_request.go similarity index 70% rename from sdk/go/hydra/swagger/consent_request_rejection.go rename to sdk/go/hydra/swagger/completed_request.go index 307dd53d657..1deaa198614 100644 --- a/sdk/go/hydra/swagger/consent_request_rejection.go +++ b/sdk/go/hydra/swagger/completed_request.go @@ -10,8 +10,8 @@ package swagger -type ConsentRequestRejection struct { +type CompletedRequest struct { - // Reason represents the reason why the user rejected the consent request. - Reason string `json:"reason,omitempty"` + // RedirectURL is the URL which you should redirect the user to once the authentication process is completed. + RedirectTo string `json:"redirect_to,omitempty"` } diff --git a/sdk/go/hydra/swagger/consent_request.go b/sdk/go/hydra/swagger/consent_request.go index ac2e9b0138c..7e6e295765a 100644 --- a/sdk/go/hydra/swagger/consent_request.go +++ b/sdk/go/hydra/swagger/consent_request.go @@ -10,24 +10,24 @@ package swagger -import ( - "time" -) - type ConsentRequest struct { - // ClientID is the client id that initiated the OAuth2 request. - ClientId string `json:"clientId,omitempty"` + // Challenge is the identifier (\"authorization challenge\") of the consent authorization request. It is used to identify the session. + Challenge string `json:"challenge,omitempty"` + + Client OAuth2Client `json:"client,omitempty"` + + OidcContext OpenIdConnectContext `json:"oidc_context,omitempty"` - // ExpiresAt is the time where the access request will expire. - ExpiresAt time.Time `json:"expiresAt,omitempty"` + // RequestURL is the original OAuth 2.0 Authorization URL requested by the OAuth 2.0 client. It is the URL which initiates the OAuth 2.0 Authorization Code or OAuth 2.0 Implicit flow. This URL is typically not needed, but might come in handy if you want to deal with additional request parameters. + RequestUrl string `json:"request_url,omitempty"` - // ID is the id of this consent request. - Id string `json:"id,omitempty"` + // RequestedScope contains all scopes requested by the OAuth 2.0 client. + RequestedScope []string `json:"requested_scope,omitempty"` - // Redirect URL is the URL where the user agent should be redirected to after the consent has been accepted or rejected. - RedirectUrl string `json:"redirectUrl,omitempty"` + // Skip, if true, implies that the client has requested the same scopes from the same user previously. If true, you must not ask the user to grant the requested scopes. You must however either allow or deny the consent request using the usual API call. + Skip bool `json:"skip,omitempty"` - // RequestedScopes represents a list of scopes that have been requested by the OAuth2 request initiator. - RequestedScopes []string `json:"requestedScopes,omitempty"` + // Subject is the user ID of the end-user that authenticated. Now, that end user needs to grant or deny the scope requested by the OAuth 2.0 client. + Subject string `json:"subject,omitempty"` } diff --git a/sdk/go/hydra/swagger/consent_request_acceptance.go b/sdk/go/hydra/swagger/consent_request_acceptance.go deleted file mode 100644 index 00d30fffcb0..00000000000 --- a/sdk/go/hydra/swagger/consent_request_acceptance.go +++ /dev/null @@ -1,26 +0,0 @@ -/* - * ORY Hydra - Cloud Native OAuth 2.0 and OpenID Connect Server - * - * Welcome to the ORY Hydra HTTP API documentation. You will find documentation for all HTTP APIs here. Keep in mind that this document reflects the latest branch, always. Support for versioned documentation is coming in the future. - * - * OpenAPI spec version: Latest - * Contact: hi@ory.am - * Generated by: https://github.com/swagger-api/swagger-codegen.git - */ - -package swagger - -type ConsentRequestAcceptance struct { - - // AccessTokenExtra represents arbitrary data that will be added to the access token and that will be returned on introspection and warden requests. - AccessTokenExtra map[string]interface{} `json:"accessTokenExtra,omitempty"` - - // A list of scopes that the user agreed to grant. It should be a subset of requestedScopes from the consent request. - GrantScopes []string `json:"grantScopes,omitempty"` - - // IDTokenExtra represents arbitrary data that will be added to the ID token. The ID token will only be issued if the user agrees to it and if the client requested an ID token. - IdTokenExtra map[string]interface{} `json:"idTokenExtra,omitempty"` - - // Subject represents a unique identifier of the user (or service, or legal entity, ...) that accepted the OAuth2 request. - Subject string `json:"subject,omitempty"` -} diff --git a/sdk/go/hydra/swagger/consent_request_manager.go b/sdk/go/hydra/swagger/consent_request_manager.go deleted file mode 100644 index 13f39a2df0c..00000000000 --- a/sdk/go/hydra/swagger/consent_request_manager.go +++ /dev/null @@ -1,14 +0,0 @@ -/* - * ORY Hydra - Cloud Native OAuth 2.0 and OpenID Connect Server - * - * Welcome to the ORY Hydra HTTP API documentation. You will find documentation for all HTTP APIs here. Keep in mind that this document reflects the latest branch, always. Support for versioned documentation is coming in the future. - * - * OpenAPI spec version: Latest - * Contact: hi@ory.am - * Generated by: https://github.com/swagger-api/swagger-codegen.git - */ - -package swagger - -type ConsentRequestManager struct { -} diff --git a/sdk/go/hydra/swagger/consent_request_session.go b/sdk/go/hydra/swagger/consent_request_session.go new file mode 100644 index 00000000000..1db40806c46 --- /dev/null +++ b/sdk/go/hydra/swagger/consent_request_session.go @@ -0,0 +1,20 @@ +/* + * ORY Hydra - Cloud Native OAuth 2.0 and OpenID Connect Server + * + * Welcome to the ORY Hydra HTTP API documentation. You will find documentation for all HTTP APIs here. Keep in mind that this document reflects the latest branch, always. Support for versioned documentation is coming in the future. + * + * OpenAPI spec version: Latest + * Contact: hi@ory.am + * Generated by: https://github.com/swagger-api/swagger-codegen.git + */ + +package swagger + +type ConsentRequestSession struct { + + // AccessToken sets session data for the access and refresh token, as well as any future tokens issued by the refresh grant. Keep in mind that this data will be available to anyone performing OAuth 2.0 Challenge Introspection. If only your services can perform OAuth 2.0 Challenge Introspection, this is usually fine. But if third parties can access that endpoint as well, sensitive data from the session might be exposed to them. Use with care! + AccessToken map[string]interface{} `json:"access_token,omitempty"` + + // IDToken sets session data for the OpenID Connect ID token. Keep in mind that the session'id payloads are readable by anyone that has access to the ID Challenge. Use with care! + IdToken map[string]interface{} `json:"id_token,omitempty"` +} diff --git a/sdk/go/hydra/swagger/docs/AcceptConsentRequest.md b/sdk/go/hydra/swagger/docs/AcceptConsentRequest.md new file mode 100644 index 00000000000..23fbe0dfb76 --- /dev/null +++ b/sdk/go/hydra/swagger/docs/AcceptConsentRequest.md @@ -0,0 +1,13 @@ +# AcceptConsentRequest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**GrantScope** | **[]string** | GrantScope sets the scope the user authorized the client to use. Should be a subset of `requested_scope` | [optional] [default to null] +**Remember** | **bool** | Remember, if set to true, tells ORY Hydra to remember this consent authorization and reuse it if the same client asks the same user for the same, or a subset of, scope. | [optional] [default to null] +**RememberFor** | **int64** | RememberFor sets how long the consent authorization should be remembered for in seconds. If set to `0`, the authorization will be remembered indefinitely. | [optional] [default to null] +**Session** | [**ConsentRequestSession**](consentRequestSession.md) | | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/sdk/go/hydra/swagger/docs/AcceptLoginRequest.md b/sdk/go/hydra/swagger/docs/AcceptLoginRequest.md new file mode 100644 index 00000000000..aa8171fcf83 --- /dev/null +++ b/sdk/go/hydra/swagger/docs/AcceptLoginRequest.md @@ -0,0 +1,13 @@ +# AcceptLoginRequest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Acr** | **string** | ACR sets the Authentication AuthorizationContext Class Reference value for this authentication session. You can use it to express that, for example, a user authenticated using two factor authentication. | [optional] [default to null] +**Remember** | **bool** | Remember, if set to true, tells ORY Hydra to remember this user by telling the user agent (browser) to store a cookie with authentication data. If the same user performs another OAuth 2.0 Authorization Request, he/she will not be asked to log in again. | [optional] [default to null] +**RememberFor** | **int64** | RememberFor sets how long the authentication should be remembered for in seconds. If set to `0`, the authorization will be remembered indefinitely. | [optional] [default to null] +**Subject** | **string** | Subject is the user ID of the end-user that authenticated. | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/sdk/go/hydra/swagger/docs/SwaggerOAuthConsentRequestPayload.md b/sdk/go/hydra/swagger/docs/AuthenticationSession.md similarity index 55% rename from sdk/go/hydra/swagger/docs/SwaggerOAuthConsentRequestPayload.md rename to sdk/go/hydra/swagger/docs/AuthenticationSession.md index f92a341f9f2..e95f5d47908 100644 --- a/sdk/go/hydra/swagger/docs/SwaggerOAuthConsentRequestPayload.md +++ b/sdk/go/hydra/swagger/docs/AuthenticationSession.md @@ -1,9 +1,11 @@ -# SwaggerOAuthConsentRequestPayload +# AuthenticationSession ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**Id** | **string** | The id of the OAuth 2.0 Consent Request. | [default to null] +**AuthenticatedAt** | [**time.Time**](time.Time.md) | | [optional] [default to null] +**ID** | **string** | | [optional] [default to null] +**Subject** | **string** | | [optional] [default to null] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/sdk/go/hydra/swagger/docs/SwaggerAcceptConsentRequest.md b/sdk/go/hydra/swagger/docs/CompletedRequest.md similarity index 59% rename from sdk/go/hydra/swagger/docs/SwaggerAcceptConsentRequest.md rename to sdk/go/hydra/swagger/docs/CompletedRequest.md index 623403ed998..bfaa5368970 100644 --- a/sdk/go/hydra/swagger/docs/SwaggerAcceptConsentRequest.md +++ b/sdk/go/hydra/swagger/docs/CompletedRequest.md @@ -1,10 +1,9 @@ -# SwaggerAcceptConsentRequest +# CompletedRequest ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**Body** | [**ConsentRequestAcceptance**](consentRequestAcceptance.md) | | [default to null] -**Id** | **string** | in: path | [default to null] +**RedirectTo** | **string** | RedirectURL is the URL which you should redirect the user to once the authentication process is completed. | [optional] [default to null] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/sdk/go/hydra/swagger/docs/ConsentRequest.md b/sdk/go/hydra/swagger/docs/ConsentRequest.md index 6db855d26e3..2c02bd4709b 100644 --- a/sdk/go/hydra/swagger/docs/ConsentRequest.md +++ b/sdk/go/hydra/swagger/docs/ConsentRequest.md @@ -3,11 +3,13 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**ClientId** | **string** | ClientID is the client id that initiated the OAuth2 request. | [optional] [default to null] -**ExpiresAt** | [**time.Time**](time.Time.md) | ExpiresAt is the time where the access request will expire. | [optional] [default to null] -**Id** | **string** | ID is the id of this consent request. | [optional] [default to null] -**RedirectUrl** | **string** | Redirect URL is the URL where the user agent should be redirected to after the consent has been accepted or rejected. | [optional] [default to null] -**RequestedScopes** | **[]string** | RequestedScopes represents a list of scopes that have been requested by the OAuth2 request initiator. | [optional] [default to null] +**Challenge** | **string** | Challenge is the identifier (\"authorization challenge\") of the consent authorization request. It is used to identify the session. | [optional] [default to null] +**Client** | [**OAuth2Client**](oAuth2Client.md) | | [optional] [default to null] +**OidcContext** | [**OpenIdConnectContext**](openIDConnectContext.md) | | [optional] [default to null] +**RequestUrl** | **string** | RequestURL is the original OAuth 2.0 Authorization URL requested by the OAuth 2.0 client. It is the URL which initiates the OAuth 2.0 Authorization Code or OAuth 2.0 Implicit flow. This URL is typically not needed, but might come in handy if you want to deal with additional request parameters. | [optional] [default to null] +**RequestedScope** | **[]string** | RequestedScope contains all scopes requested by the OAuth 2.0 client. | [optional] [default to null] +**Skip** | **bool** | Skip, if true, implies that the client has requested the same scopes from the same user previously. If true, you must not ask the user to grant the requested scopes. You must however either allow or deny the consent request using the usual API call. | [optional] [default to null] +**Subject** | **string** | Subject is the user ID of the end-user that authenticated. Now, that end user needs to grant or deny the scope requested by the OAuth 2.0 client. | [optional] [default to null] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/sdk/go/hydra/swagger/docs/ConsentRequestAcceptance.md b/sdk/go/hydra/swagger/docs/ConsentRequestAcceptance.md deleted file mode 100644 index 7226d7802cc..00000000000 --- a/sdk/go/hydra/swagger/docs/ConsentRequestAcceptance.md +++ /dev/null @@ -1,13 +0,0 @@ -# ConsentRequestAcceptance - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**AccessTokenExtra** | [**map[string]interface{}**](interface{}.md) | AccessTokenExtra represents arbitrary data that will be added to the access token and that will be returned on introspection and warden requests. | [optional] [default to null] -**GrantScopes** | **[]string** | A list of scopes that the user agreed to grant. It should be a subset of requestedScopes from the consent request. | [optional] [default to null] -**IdTokenExtra** | [**map[string]interface{}**](interface{}.md) | IDTokenExtra represents arbitrary data that will be added to the ID token. The ID token will only be issued if the user agrees to it and if the client requested an ID token. | [optional] [default to null] -**Subject** | **string** | Subject represents a unique identifier of the user (or service, or legal entity, ...) that accepted the OAuth2 request. | [optional] [default to null] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/sdk/go/hydra/swagger/docs/ConsentRequestManager.md b/sdk/go/hydra/swagger/docs/ConsentRequestManager.md deleted file mode 100644 index 26f451f4d3a..00000000000 --- a/sdk/go/hydra/swagger/docs/ConsentRequestManager.md +++ /dev/null @@ -1,9 +0,0 @@ -# ConsentRequestManager - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/sdk/go/hydra/swagger/docs/ConsentRequestSession.md b/sdk/go/hydra/swagger/docs/ConsentRequestSession.md new file mode 100644 index 00000000000..90be014d056 --- /dev/null +++ b/sdk/go/hydra/swagger/docs/ConsentRequestSession.md @@ -0,0 +1,11 @@ +# ConsentRequestSession + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**AccessToken** | [**map[string]interface{}**](interface{}.md) | AccessToken sets session data for the access and refresh token, as well as any future tokens issued by the refresh grant. Keep in mind that this data will be available to anyone performing OAuth 2.0 Challenge Introspection. If only your services can perform OAuth 2.0 Challenge Introspection, this is usually fine. But if third parties can access that endpoint as well, sensitive data from the session might be exposed to them. Use with care! | [optional] [default to null] +**IdToken** | [**map[string]interface{}**](interface{}.md) | IDToken sets session data for the OpenID Connect ID token. Keep in mind that the session'id payloads are readable by anyone that has access to the ID Challenge. Use with care! | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/sdk/go/hydra/swagger/docs/Handler.md b/sdk/go/hydra/swagger/docs/Handler.md index ca567d81e79..4fa50a2413c 100644 --- a/sdk/go/hydra/swagger/docs/Handler.md +++ b/sdk/go/hydra/swagger/docs/Handler.md @@ -3,6 +3,7 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- +**Generators** | [**map[string]KeyGenerator**](KeyGenerator.md) | | [optional] [default to null] **H** | [**Writer**](Writer.md) | | [optional] [default to null] **Manager** | [**Manager**](Manager.md) | | [optional] [default to null] **ResourcePrefix** | **string** | | [optional] [default to null] diff --git a/sdk/go/hydra/swagger/docs/LoginRequest.md b/sdk/go/hydra/swagger/docs/LoginRequest.md new file mode 100644 index 00000000000..7a5b18fae7a --- /dev/null +++ b/sdk/go/hydra/swagger/docs/LoginRequest.md @@ -0,0 +1,16 @@ +# LoginRequest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Challenge** | **string** | Challenge is the identifier (\"authentication challenge\") of the consent authentication request. It is used to identify the session. | [optional] [default to null] +**Client** | [**OAuth2Client**](oAuth2Client.md) | | [optional] [default to null] +**OidcContext** | [**OpenIdConnectContext**](openIDConnectContext.md) | | [optional] [default to null] +**RequestUrl** | **string** | RequestURL is the original OAuth 2.0 Authorization URL requested by the OAuth 2.0 client. It is the URL which initiates the OAuth 2.0 Authorization Code or OAuth 2.0 Implicit flow. This URL is typically not needed, but might come in handy if you want to deal with additional request parameters. | [optional] [default to null] +**RequestedScope** | **[]string** | RequestedScope contains all scopes requested by the OAuth 2.0 client. | [optional] [default to null] +**Skip** | **bool** | Skip, if true, implies that the client has requested the same scopes from the same user previously. If true, you can skip asking the user to grant the requested scopes, and simply forward the user to the redirect URL. This feature allows you to update / set session information. | [optional] [default to null] +**Subject** | **string** | Subject is the user ID of the end-user that authenticated. Now, that end user needs to grant or deny the scope requested by the OAuth 2.0 client. | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/sdk/go/hydra/swagger/docs/OAuth2Api.md b/sdk/go/hydra/swagger/docs/OAuth2Api.md index 0c9e2b38eb0..f7d1429193f 100644 --- a/sdk/go/hydra/swagger/docs/OAuth2Api.md +++ b/sdk/go/hydra/swagger/docs/OAuth2Api.md @@ -4,42 +4,75 @@ All URIs are relative to *http://localhost* Method | HTTP request | Description ------------- | ------------- | ------------- -[**AcceptOAuth2ConsentRequest**](OAuth2Api.md#AcceptOAuth2ConsentRequest) | **Patch** /oauth2/consent/requests/{id}/accept | Accept a consent request +[**AcceptConsentRequest**](OAuth2Api.md#AcceptConsentRequest) | **Put** /oauth2/auth/requests/consent/{challenge}/accept | Accept an consent request +[**AcceptLoginRequest**](OAuth2Api.md#AcceptLoginRequest) | **Put** /oauth2/auth/requests/login/{challenge}/accept | Accept an login request [**CreateOAuth2Client**](OAuth2Api.md#CreateOAuth2Client) | **Post** /clients | Create an OAuth 2.0 client [**DeleteOAuth2Client**](OAuth2Api.md#DeleteOAuth2Client) | **Delete** /clients/{id} | Deletes an OAuth 2.0 Client [**FlushInactiveOAuth2Tokens**](OAuth2Api.md#FlushInactiveOAuth2Tokens) | **Post** /oauth2/flush | Flush Expired OAuth2 Access Tokens +[**GetConsentRequest**](OAuth2Api.md#GetConsentRequest) | **Get** /oauth2/auth/requests/consent/{challenge} | Get consent request information +[**GetLoginRequest**](OAuth2Api.md#GetLoginRequest) | **Get** /oauth2/auth/requests/login/{challenge} | Get an login request [**GetOAuth2Client**](OAuth2Api.md#GetOAuth2Client) | **Get** /clients/{id} | Get an OAuth 2.0 Client. -[**GetOAuth2ConsentRequest**](OAuth2Api.md#GetOAuth2ConsentRequest) | **Get** /oauth2/consent/requests/{id} | Receive consent request information [**GetWellKnown**](OAuth2Api.md#GetWellKnown) | **Get** /.well-known/openid-configuration | Server well known configuration [**IntrospectOAuth2Token**](OAuth2Api.md#IntrospectOAuth2Token) | **Post** /oauth2/introspect | Introspect OAuth2 tokens [**ListOAuth2Clients**](OAuth2Api.md#ListOAuth2Clients) | **Get** /clients | List OAuth 2.0 Clients [**OauthAuth**](OAuth2Api.md#OauthAuth) | **Get** /oauth2/auth | The OAuth 2.0 authorize endpoint [**OauthToken**](OAuth2Api.md#OauthToken) | **Post** /oauth2/token | The OAuth 2.0 token endpoint -[**RejectOAuth2ConsentRequest**](OAuth2Api.md#RejectOAuth2ConsentRequest) | **Patch** /oauth2/consent/requests/{id}/reject | Reject a consent request +[**RejectConsentRequest**](OAuth2Api.md#RejectConsentRequest) | **Put** /oauth2/auth/requests/consent/{challenge}/reject | Reject an consent request +[**RejectLoginRequest**](OAuth2Api.md#RejectLoginRequest) | **Put** /oauth2/auth/requests/login/{challenge}/reject | Reject an logout request [**RevokeOAuth2Token**](OAuth2Api.md#RevokeOAuth2Token) | **Post** /oauth2/revoke | Revoke OAuth2 tokens [**UpdateOAuth2Client**](OAuth2Api.md#UpdateOAuth2Client) | **Put** /clients/{id} | Update an OAuth 2.0 Client [**Userinfo**](OAuth2Api.md#Userinfo) | **Post** /userinfo | OpenID Connect Userinfo [**WellKnown**](OAuth2Api.md#WellKnown) | **Get** /.well-known/jwks.json | Get Well-Known JSON Web Keys -# **AcceptOAuth2ConsentRequest** -> AcceptOAuth2ConsentRequest($id, $body) +# **AcceptConsentRequest** +> CompletedRequest AcceptConsentRequest($challenge, $body) -Accept a consent request +Accept an consent request -Call this endpoint to accept a consent request. This usually happens when a user agrees to give access rights to an application. The consent request id is usually transmitted via the URL query `consent`. For example: `http://consent-app.mydomain.com/?consent=1234abcd` +When an authorization code, hybrid, or implicit OAuth 2.0 Flow is initiated, ORY Hydra asks the login provider to authenticate the user and then tell ORY Hydra now about it. If the user authenticated, he/she must now be asked if the OAuth 2.0 Client which initiated the flow should be allowed to access the resources on the user's behalf. The consent provider which handles this request and is a web app implemented and hosted by you. It shows a user interface which asks the user to grant or deny the client access to the requested scope (\"Application my-dropbox-app wants write access to all your private files\"). The consent challenge is appended to the consent provider's URL to which the user's user-agent (browser) is redirected to. The consent provider uses that challenge to fetch information on the OAuth2 request and then tells ORY Hydra if the user accepted or rejected the request. This endpoint tells ORY Hydra that the user has authorized the OAuth 2.0 client to access resources on his/her behalf. The consent provider includes additional information, such as session data for access and ID tokens, and if the consent request should be used as basis for future requests. The response contains a redirect URL which the consent provider should redirect the user-agent to. ### Parameters Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **id** | **string**| | - **body** | [**ConsentRequestAcceptance**](ConsentRequestAcceptance.md)| | + **challenge** | **string**| | + **body** | [**AcceptConsentRequest**](AcceptConsentRequest.md)| | [optional] ### Return type -void (empty response body) +[**CompletedRequest**](completedRequest.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **AcceptLoginRequest** +> CompletedRequest AcceptLoginRequest($challenge, $body) + +Accept an login request + +When an authorization code, hybrid, or implicit OAuth 2.0 Flow is initiated, ORY Hydra asks the login provider (sometimes called \"identity provider\") to authenticate the user and then tell ORY Hydra now about it. The login provider is an web-app you write and host, and it must be able to authenticate (\"show the user a login screen\") a user (in OAuth2 the proper name for user is \"resource owner\"). The authentication challenge is appended to the login provider URL to which the user's user-agent (browser) is redirected to. The login provider uses that challenge to fetch information on the OAuth2 request and then accept or reject the requested authentication process. This endpoint tells ORY Hydra that the user has successfully authenticated and includes additional information such as the user's ID and if ORY Hydra should remember the user's user agent for future authentication attempts by setting a cookie. The response contains a redirect URL which the login provider should redirect the user-agent to. + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **challenge** | **string**| | + **body** | [**AcceptLoginRequest**](AcceptLoginRequest.md)| | [optional] + +### Return type + +[**CompletedRequest**](completedRequest.md) ### Authorization @@ -139,23 +172,23 @@ No authorization required [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) -# **GetOAuth2Client** -> OAuth2Client GetOAuth2Client($id) +# **GetConsentRequest** +> ConsentRequest GetConsentRequest($challenge) -Get an OAuth 2.0 Client. +Get consent request information -Get an OAUth 2.0 client by its ID. This endpoint never returns passwords. OAuth 2.0 clients are used to perform OAuth 2.0 and OpenID Connect flows. Usually, OAuth 2.0 clients are generated for applications which want to consume your OAuth 2.0 or OpenID Connect capabilities. To manage ORY Hydra, you will need an OAuth 2.0 Client as well. Make sure that this endpoint is well protected and only callable by first-party components. +When an authorization code, hybrid, or implicit OAuth 2.0 Flow is initiated, ORY Hydra asks the login provider to authenticate the user and then tell ORY Hydra now about it. If the user authenticated, he/she must now be asked if the OAuth 2.0 Client which initiated the flow should be allowed to access the resources on the user's behalf. The consent provider which handles this request and is a web app implemented and hosted by you. It shows a user interface which asks the user to grant or deny the client access to the requested scope (\"Application my-dropbox-app wants write access to all your private files\"). The consent challenge is appended to the consent provider's URL to which the user's user-agent (browser) is redirected to. The consent provider uses that challenge to fetch information on the OAuth2 request and then tells ORY Hydra if the user accepted or rejected the request. ### Parameters Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **id** | **string**| The id of the OAuth 2.0 Client. | + **challenge** | **string**| | ### Return type -[**OAuth2Client**](oAuth2Client.md) +[**ConsentRequest**](consentRequest.md) ### Authorization @@ -168,23 +201,52 @@ No authorization required [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) -# **GetOAuth2ConsentRequest** -> OAuth2ConsentRequest GetOAuth2ConsentRequest($id) +# **GetLoginRequest** +> LoginRequest GetLoginRequest($challenge) -Receive consent request information +Get an login request -Call this endpoint to receive information on consent requests. The consent request id is usually transmitted via the URL query `consent`. For example: `http://consent-app.mydomain.com/?consent=1234abcd` +When an authorization code, hybrid, or implicit OAuth 2.0 Flow is initiated, ORY Hydra asks the login provider (sometimes called \"identity provider\") to authenticate the user and then tell ORY Hydra now about it. The login provider is an web-app you write and host, and it must be able to authenticate (\"show the user a login screen\") a user (in OAuth2 the proper name for user is \"resource owner\"). The authentication challenge is appended to the login provider URL to which the user's user-agent (browser) is redirected to. The login provider uses that challenge to fetch information on the OAuth2 request and then accept or reject the requested authentication process. ### Parameters Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **id** | **string**| The id of the OAuth 2.0 Consent Request. | + **challenge** | **string**| | ### Return type -[**OAuth2ConsentRequest**](oAuth2ConsentRequest.md) +[**LoginRequest**](loginRequest.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **GetOAuth2Client** +> OAuth2Client GetOAuth2Client($id) + +Get an OAuth 2.0 Client. + +Get an OAUth 2.0 client by its ID. This endpoint never returns passwords. OAuth 2.0 clients are used to perform OAuth 2.0 and OpenID Connect flows. Usually, OAuth 2.0 clients are generated for applications which want to consume your OAuth 2.0 or OpenID Connect capabilities. To manage ORY Hydra, you will need an OAuth 2.0 Client as well. Make sure that this endpoint is well protected and only callable by first-party components. + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **id** | **string**| The id of the OAuth 2.0 Client. | + +### Return type + +[**OAuth2Client**](oAuth2Client.md) ### Authorization @@ -335,24 +397,54 @@ This endpoint does not need any parameter. [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) -# **RejectOAuth2ConsentRequest** -> RejectOAuth2ConsentRequest($id, $body) +# **RejectConsentRequest** +> CompletedRequest RejectConsentRequest($challenge, $body) -Reject a consent request +Reject an consent request -Call this endpoint to reject a consent request. This usually happens when a user denies access rights to an application. The consent request id is usually transmitted via the URL query `consent`. For example: `http://consent-app.mydomain.com/?consent=1234abcd` +When an authorization code, hybrid, or implicit OAuth 2.0 Flow is initiated, ORY Hydra asks the login provider to authenticate the user and then tell ORY Hydra now about it. If the user authenticated, he/she must now be asked if the OAuth 2.0 Client which initiated the flow should be allowed to access the resources on the user's behalf. The consent provider which handles this request and is a web app implemented and hosted by you. It shows a user interface which asks the user to grant or deny the client access to the requested scope (\"Application my-dropbox-app wants write access to all your private files\"). The consent challenge is appended to the consent provider's URL to which the user's user-agent (browser) is redirected to. The consent provider uses that challenge to fetch information on the OAuth2 request and then tells ORY Hydra if the user accepted or rejected the request. This endpoint tells ORY Hydra that the user has not authorized the OAuth 2.0 client to access resources on his/her behalf. The consent provider must include a reason why the consent was not granted. The response contains a redirect URL which the consent provider should redirect the user-agent to. ### Parameters Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **id** | **string**| | - **body** | [**ConsentRequestRejection**](ConsentRequestRejection.md)| | + **challenge** | **string**| | + **body** | [**RejectRequest**](RejectRequest.md)| | [optional] ### Return type -void (empty response body) +[**CompletedRequest**](completedRequest.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **RejectLoginRequest** +> CompletedRequest RejectLoginRequest($challenge, $body) + +Reject an logout request + +When an authorization code, hybrid, or implicit OAuth 2.0 Flow is initiated, ORY Hydra asks the login provider (sometimes called \"identity provider\") to authenticate the user and then tell ORY Hydra now about it. The login provider is an web-app you write and host, and it must be able to authenticate (\"show the user a login screen\") a user (in OAuth2 the proper name for user is \"resource owner\"). The authentication challenge is appended to the login provider URL to which the user's user-agent (browser) is redirected to. The login provider uses that challenge to fetch information on the OAuth2 request and then accept or reject the requested authentication process. This endpoint tells ORY Hydra that the user has not authenticated and includes a reason why the authentication was be denied. The response contains a redirect URL which the login provider should redirect the user-agent to. + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **challenge** | **string**| | + **body** | [**RejectRequest**](RejectRequest.md)| | [optional] + +### Return type + +[**CompletedRequest**](completedRequest.md) ### Authorization diff --git a/sdk/go/hydra/swagger/docs/OAuth2consentRequest.md b/sdk/go/hydra/swagger/docs/OAuth2consentRequest.md deleted file mode 100644 index faa4a7aac1d..00000000000 --- a/sdk/go/hydra/swagger/docs/OAuth2consentRequest.md +++ /dev/null @@ -1,14 +0,0 @@ -# OAuth2ConsentRequest - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**ClientId** | **string** | ClientID is the client id that initiated the OAuth2 request. | [optional] [default to null] -**ExpiresAt** | **string** | ExpiresAt is the time where the access request will expire. | [optional] [default to null] -**Id** | **string** | ID is the id of this consent request. | [optional] [default to null] -**RedirectUrl** | **string** | Redirect URL is the URL where the user agent should be redirected to after the consent has been accepted or rejected. | [optional] [default to null] -**RequestedScopes** | **[]string** | RequestedScopes represents a list of scopes that have been requested by the OAuth2 request initiator. | [optional] [default to null] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/sdk/go/hydra/swagger/docs/OpenIdConnectContext.md b/sdk/go/hydra/swagger/docs/OpenIdConnectContext.md new file mode 100644 index 00000000000..86ffa8a3802 --- /dev/null +++ b/sdk/go/hydra/swagger/docs/OpenIdConnectContext.md @@ -0,0 +1,12 @@ +# OpenIdConnectContext + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**AcrValues** | **[]string** | ACRValues is the Authentication AuthorizationContext Class Reference requested in the OAuth 2.0 Authorization request. It is a parameter defined by OpenID Connect and expresses which level of authentication (e.g. 2FA) is required. OpenID Connect defines it as follows: > Requested Authentication AuthorizationContext Class Reference values. Space-separated string that specifies the acr values that the Authorization Server is being requested to use for processing this Authentication Request, with the values appearing in order of preference. The Authentication AuthorizationContext Class satisfied by the authentication performed is returned as the acr Claim Value, as specified in Section 2. The acr Claim is requested as a Voluntary Claim by this parameter. | [optional] [default to null] +**Display** | **string** | Display is a string value that specifies how the Authorization Server displays the authentication and consent user interface pages to the End-User. The defined values are: page: The Authorization Server SHOULD display the authentication and consent UI consistent with a full User Agent page view. If the display parameter is not specified, this is the default display mode. popup: The Authorization Server SHOULD display the authentication and consent UI consistent with a popup User Agent window. The popup User Agent window should be of an appropriate size for a login-focused dialog and should not obscure the entire window that it is popping up over. touch: The Authorization Server SHOULD display the authentication and consent UI consistent with a device that leverages a touch interface. wap: The Authorization Server SHOULD display the authentication and consent UI consistent with a \"feature phone\" type display. The Authorization Server MAY also attempt to detect the capabilities of the User Agent and present an appropriate display. | [optional] [default to null] +**UiLocales** | **[]string** | UILocales is the End-User'id preferred languages and scripts for the user interface, represented as a space-separated list of BCP47 [RFC5646] language tag values, ordered by preference. For instance, the value \"fr-CA fr en\" represents a preference for French as spoken in Canada, then French (without a region designation), followed by English (without a region designation). An error SHOULD NOT result if some or all of the requested locales are not supported by the OpenID Provider. | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/sdk/go/hydra/swagger/docs/RejectRequest.md b/sdk/go/hydra/swagger/docs/RejectRequest.md new file mode 100644 index 00000000000..db1d9f39d51 --- /dev/null +++ b/sdk/go/hydra/swagger/docs/RejectRequest.md @@ -0,0 +1,14 @@ +# RejectRequest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Error_** | **string** | | [optional] [default to null] +**ErrorDebug** | **string** | | [optional] [default to null] +**ErrorDescription** | **string** | | [optional] [default to null] +**ErrorHint** | **string** | | [optional] [default to null] +**StatusCode** | **int64** | | [optional] [default to null] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/sdk/go/hydra/swagger/handler.go b/sdk/go/hydra/swagger/handler.go index 2448bc88256..af6c1a6bb42 100644 --- a/sdk/go/hydra/swagger/handler.go +++ b/sdk/go/hydra/swagger/handler.go @@ -11,6 +11,8 @@ package swagger type Handler struct { + Generators map[string]KeyGenerator `json:"Generators,omitempty"` + H Writer `json:"H,omitempty"` Manager Manager `json:"Manager,omitempty"` diff --git a/sdk/go/hydra/swagger/login_request.go b/sdk/go/hydra/swagger/login_request.go new file mode 100644 index 00000000000..772434f965f --- /dev/null +++ b/sdk/go/hydra/swagger/login_request.go @@ -0,0 +1,33 @@ +/* + * ORY Hydra - Cloud Native OAuth 2.0 and OpenID Connect Server + * + * Welcome to the ORY Hydra HTTP API documentation. You will find documentation for all HTTP APIs here. Keep in mind that this document reflects the latest branch, always. Support for versioned documentation is coming in the future. + * + * OpenAPI spec version: Latest + * Contact: hi@ory.am + * Generated by: https://github.com/swagger-api/swagger-codegen.git + */ + +package swagger + +type LoginRequest struct { + + // Challenge is the identifier (\"authentication challenge\") of the consent authentication request. It is used to identify the session. + Challenge string `json:"challenge,omitempty"` + + Client OAuth2Client `json:"client,omitempty"` + + OidcContext OpenIdConnectContext `json:"oidc_context,omitempty"` + + // RequestURL is the original OAuth 2.0 Authorization URL requested by the OAuth 2.0 client. It is the URL which initiates the OAuth 2.0 Authorization Code or OAuth 2.0 Implicit flow. This URL is typically not needed, but might come in handy if you want to deal with additional request parameters. + RequestUrl string `json:"request_url,omitempty"` + + // RequestedScope contains all scopes requested by the OAuth 2.0 client. + RequestedScope []string `json:"requested_scope,omitempty"` + + // Skip, if true, implies that the client has requested the same scopes from the same user previously. If true, you can skip asking the user to grant the requested scopes, and simply forward the user to the redirect URL. This feature allows you to update / set session information. + Skip bool `json:"skip,omitempty"` + + // Subject is the user ID of the end-user that authenticated. Now, that end user needs to grant or deny the scope requested by the OAuth 2.0 client. + Subject string `json:"subject,omitempty"` +} diff --git a/sdk/go/hydra/swagger/o_auth2_api.go b/sdk/go/hydra/swagger/o_auth2_api.go index 88621e3ca3a..20e01139a74 100644 --- a/sdk/go/hydra/swagger/o_auth2_api.go +++ b/sdk/go/hydra/swagger/o_auth2_api.go @@ -38,19 +38,19 @@ func NewOAuth2ApiWithBasePath(basePath string) *OAuth2Api { } /** - * Accept a consent request - * Call this endpoint to accept a consent request. This usually happens when a user agrees to give access rights to an application. The consent request id is usually transmitted via the URL query `consent`. For example: `http://consent-app.mydomain.com/?consent=1234abcd` + * Accept an consent request + * When an authorization code, hybrid, or implicit OAuth 2.0 Flow is initiated, ORY Hydra asks the login provider to authenticate the user and then tell ORY Hydra now about it. If the user authenticated, he/she must now be asked if the OAuth 2.0 Client which initiated the flow should be allowed to access the resources on the user's behalf. The consent provider which handles this request and is a web app implemented and hosted by you. It shows a user interface which asks the user to grant or deny the client access to the requested scope (\"Application my-dropbox-app wants write access to all your private files\"). The consent challenge is appended to the consent provider's URL to which the user's user-agent (browser) is redirected to. The consent provider uses that challenge to fetch information on the OAuth2 request and then tells ORY Hydra if the user accepted or rejected the request. This endpoint tells ORY Hydra that the user has authorized the OAuth 2.0 client to access resources on his/her behalf. The consent provider includes additional information, such as session data for access and ID tokens, and if the consent request should be used as basis for future requests. The response contains a redirect URL which the consent provider should redirect the user-agent to. * - * @param id + * @param challenge * @param body - * @return void + * @return *CompletedRequest */ -func (a OAuth2Api) AcceptOAuth2ConsentRequest(id string, body ConsentRequestAcceptance) (*APIResponse, error) { +func (a OAuth2Api) AcceptConsentRequest(challenge string, body AcceptConsentRequest) (*CompletedRequest, *APIResponse, error) { - var localVarHttpMethod = strings.ToUpper("Patch") + var localVarHttpMethod = strings.ToUpper("Put") // create path and map variables - localVarPath := a.Configuration.BasePath + "/oauth2/consent/requests/{id}/accept" - localVarPath = strings.Replace(localVarPath, "{"+"id"+"}", fmt.Sprintf("%v", id), -1) + localVarPath := a.Configuration.BasePath + "/oauth2/auth/requests/consent/{challenge}/accept" + localVarPath = strings.Replace(localVarPath, "{"+"challenge"+"}", fmt.Sprintf("%v", challenge), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} @@ -83,20 +83,86 @@ func (a OAuth2Api) AcceptOAuth2ConsentRequest(id string, body ConsentRequestAcce } // body params localVarPostBody = &body + var successPayload = new(CompletedRequest) localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) var localVarURL, _ = url.Parse(localVarPath) localVarURL.RawQuery = localVarQueryParams.Encode() - var localVarAPIResponse = &APIResponse{Operation: "AcceptOAuth2ConsentRequest", Method: localVarHttpMethod, RequestURL: localVarURL.String()} + var localVarAPIResponse = &APIResponse{Operation: "AcceptConsentRequest", Method: localVarHttpMethod, RequestURL: localVarURL.String()} if localVarHttpResponse != nil { localVarAPIResponse.Response = localVarHttpResponse.RawResponse localVarAPIResponse.Payload = localVarHttpResponse.Body() } if err != nil { - return localVarAPIResponse, err + return successPayload, localVarAPIResponse, err } - return localVarAPIResponse, err + err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload) + return successPayload, localVarAPIResponse, err +} + +/** + * Accept an login request + * When an authorization code, hybrid, or implicit OAuth 2.0 Flow is initiated, ORY Hydra asks the login provider (sometimes called \"identity provider\") to authenticate the user and then tell ORY Hydra now about it. The login provider is an web-app you write and host, and it must be able to authenticate (\"show the user a login screen\") a user (in OAuth2 the proper name for user is \"resource owner\"). The authentication challenge is appended to the login provider URL to which the user's user-agent (browser) is redirected to. The login provider uses that challenge to fetch information on the OAuth2 request and then accept or reject the requested authentication process. This endpoint tells ORY Hydra that the user has successfully authenticated and includes additional information such as the user's ID and if ORY Hydra should remember the user's user agent for future authentication attempts by setting a cookie. The response contains a redirect URL which the login provider should redirect the user-agent to. + * + * @param challenge + * @param body + * @return *CompletedRequest + */ +func (a OAuth2Api) AcceptLoginRequest(challenge string, body AcceptLoginRequest) (*CompletedRequest, *APIResponse, error) { + + var localVarHttpMethod = strings.ToUpper("Put") + // create path and map variables + localVarPath := a.Configuration.BasePath + "/oauth2/auth/requests/login/{challenge}/accept" + localVarPath = strings.Replace(localVarPath, "{"+"challenge"+"}", fmt.Sprintf("%v", challenge), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := make(map[string]string) + var localVarPostBody interface{} + var localVarFileName string + var localVarFileBytes []byte + // add default headers if any + for key := range a.Configuration.DefaultHeader { + localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] + } + + // to determine the Content-Type header + localVarHttpContentTypes := []string{"application/json"} + + // set Content-Type header + localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) + if localVarHttpContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHttpContentType + } + // to determine the Accept header + localVarHttpHeaderAccepts := []string{ + "application/json", + } + + // set Accept header + localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) + if localVarHttpHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHttpHeaderAccept + } + // body params + localVarPostBody = &body + var successPayload = new(CompletedRequest) + localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + + var localVarURL, _ = url.Parse(localVarPath) + localVarURL.RawQuery = localVarQueryParams.Encode() + var localVarAPIResponse = &APIResponse{Operation: "AcceptLoginRequest", Method: localVarHttpMethod, RequestURL: localVarURL.String()} + if localVarHttpResponse != nil { + localVarAPIResponse.Response = localVarHttpResponse.RawResponse + localVarAPIResponse.Payload = localVarHttpResponse.Body() + } + + if err != nil { + return successPayload, localVarAPIResponse, err + } + err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload) + return successPayload, localVarAPIResponse, err } /** @@ -281,18 +347,18 @@ func (a OAuth2Api) FlushInactiveOAuth2Tokens(body FlushInactiveOAuth2TokensReque } /** - * Get an OAuth 2.0 Client. - * Get an OAUth 2.0 client by its ID. This endpoint never returns passwords. OAuth 2.0 clients are used to perform OAuth 2.0 and OpenID Connect flows. Usually, OAuth 2.0 clients are generated for applications which want to consume your OAuth 2.0 or OpenID Connect capabilities. To manage ORY Hydra, you will need an OAuth 2.0 Client as well. Make sure that this endpoint is well protected and only callable by first-party components. + * Get consent request information + * When an authorization code, hybrid, or implicit OAuth 2.0 Flow is initiated, ORY Hydra asks the login provider to authenticate the user and then tell ORY Hydra now about it. If the user authenticated, he/she must now be asked if the OAuth 2.0 Client which initiated the flow should be allowed to access the resources on the user's behalf. The consent provider which handles this request and is a web app implemented and hosted by you. It shows a user interface which asks the user to grant or deny the client access to the requested scope (\"Application my-dropbox-app wants write access to all your private files\"). The consent challenge is appended to the consent provider's URL to which the user's user-agent (browser) is redirected to. The consent provider uses that challenge to fetch information on the OAuth2 request and then tells ORY Hydra if the user accepted or rejected the request. * - * @param id The id of the OAuth 2.0 Client. - * @return *OAuth2Client + * @param challenge + * @return *ConsentRequest */ -func (a OAuth2Api) GetOAuth2Client(id string) (*OAuth2Client, *APIResponse, error) { +func (a OAuth2Api) GetConsentRequest(challenge string) (*ConsentRequest, *APIResponse, error) { var localVarHttpMethod = strings.ToUpper("Get") // create path and map variables - localVarPath := a.Configuration.BasePath + "/clients/{id}" - localVarPath = strings.Replace(localVarPath, "{"+"id"+"}", fmt.Sprintf("%v", id), -1) + localVarPath := a.Configuration.BasePath + "/oauth2/auth/requests/consent/{challenge}" + localVarPath = strings.Replace(localVarPath, "{"+"challenge"+"}", fmt.Sprintf("%v", challenge), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} @@ -323,12 +389,73 @@ func (a OAuth2Api) GetOAuth2Client(id string) (*OAuth2Client, *APIResponse, erro if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } - var successPayload = new(OAuth2Client) + var successPayload = new(ConsentRequest) localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) var localVarURL, _ = url.Parse(localVarPath) localVarURL.RawQuery = localVarQueryParams.Encode() - var localVarAPIResponse = &APIResponse{Operation: "GetOAuth2Client", Method: localVarHttpMethod, RequestURL: localVarURL.String()} + var localVarAPIResponse = &APIResponse{Operation: "GetConsentRequest", Method: localVarHttpMethod, RequestURL: localVarURL.String()} + if localVarHttpResponse != nil { + localVarAPIResponse.Response = localVarHttpResponse.RawResponse + localVarAPIResponse.Payload = localVarHttpResponse.Body() + } + + if err != nil { + return successPayload, localVarAPIResponse, err + } + err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload) + return successPayload, localVarAPIResponse, err +} + +/** + * Get an login request + * When an authorization code, hybrid, or implicit OAuth 2.0 Flow is initiated, ORY Hydra asks the login provider (sometimes called \"identity provider\") to authenticate the user and then tell ORY Hydra now about it. The login provider is an web-app you write and host, and it must be able to authenticate (\"show the user a login screen\") a user (in OAuth2 the proper name for user is \"resource owner\"). The authentication challenge is appended to the login provider URL to which the user's user-agent (browser) is redirected to. The login provider uses that challenge to fetch information on the OAuth2 request and then accept or reject the requested authentication process. + * + * @param challenge + * @return *LoginRequest + */ +func (a OAuth2Api) GetLoginRequest(challenge string) (*LoginRequest, *APIResponse, error) { + + var localVarHttpMethod = strings.ToUpper("Get") + // create path and map variables + localVarPath := a.Configuration.BasePath + "/oauth2/auth/requests/login/{challenge}" + localVarPath = strings.Replace(localVarPath, "{"+"challenge"+"}", fmt.Sprintf("%v", challenge), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := make(map[string]string) + var localVarPostBody interface{} + var localVarFileName string + var localVarFileBytes []byte + // add default headers if any + for key := range a.Configuration.DefaultHeader { + localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] + } + + // to determine the Content-Type header + localVarHttpContentTypes := []string{"application/json"} + + // set Content-Type header + localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) + if localVarHttpContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHttpContentType + } + // to determine the Accept header + localVarHttpHeaderAccepts := []string{ + "application/json", + } + + // set Accept header + localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) + if localVarHttpHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHttpHeaderAccept + } + var successPayload = new(LoginRequest) + localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + + var localVarURL, _ = url.Parse(localVarPath) + localVarURL.RawQuery = localVarQueryParams.Encode() + var localVarAPIResponse = &APIResponse{Operation: "GetLoginRequest", Method: localVarHttpMethod, RequestURL: localVarURL.String()} if localVarHttpResponse != nil { localVarAPIResponse.Response = localVarHttpResponse.RawResponse localVarAPIResponse.Payload = localVarHttpResponse.Body() @@ -342,17 +469,17 @@ func (a OAuth2Api) GetOAuth2Client(id string) (*OAuth2Client, *APIResponse, erro } /** - * Receive consent request information - * Call this endpoint to receive information on consent requests. The consent request id is usually transmitted via the URL query `consent`. For example: `http://consent-app.mydomain.com/?consent=1234abcd` + * Get an OAuth 2.0 Client. + * Get an OAUth 2.0 client by its ID. This endpoint never returns passwords. OAuth 2.0 clients are used to perform OAuth 2.0 and OpenID Connect flows. Usually, OAuth 2.0 clients are generated for applications which want to consume your OAuth 2.0 or OpenID Connect capabilities. To manage ORY Hydra, you will need an OAuth 2.0 Client as well. Make sure that this endpoint is well protected and only callable by first-party components. * - * @param id The id of the OAuth 2.0 Consent Request. - * @return *OAuth2ConsentRequest + * @param id The id of the OAuth 2.0 Client. + * @return *OAuth2Client */ -func (a OAuth2Api) GetOAuth2ConsentRequest(id string) (*OAuth2ConsentRequest, *APIResponse, error) { +func (a OAuth2Api) GetOAuth2Client(id string) (*OAuth2Client, *APIResponse, error) { var localVarHttpMethod = strings.ToUpper("Get") // create path and map variables - localVarPath := a.Configuration.BasePath + "/oauth2/consent/requests/{id}" + localVarPath := a.Configuration.BasePath + "/clients/{id}" localVarPath = strings.Replace(localVarPath, "{"+"id"+"}", fmt.Sprintf("%v", id), -1) localVarHeaderParams := make(map[string]string) @@ -384,12 +511,12 @@ func (a OAuth2Api) GetOAuth2ConsentRequest(id string) (*OAuth2ConsentRequest, *A if localVarHttpHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHttpHeaderAccept } - var successPayload = new(OAuth2ConsentRequest) + var successPayload = new(OAuth2Client) localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) var localVarURL, _ = url.Parse(localVarPath) localVarURL.RawQuery = localVarQueryParams.Encode() - var localVarAPIResponse = &APIResponse{Operation: "GetOAuth2ConsentRequest", Method: localVarHttpMethod, RequestURL: localVarURL.String()} + var localVarAPIResponse = &APIResponse{Operation: "GetOAuth2Client", Method: localVarHttpMethod, RequestURL: localVarURL.String()} if localVarHttpResponse != nil { localVarAPIResponse.Response = localVarHttpResponse.RawResponse localVarAPIResponse.Payload = localVarHttpResponse.Body() @@ -491,7 +618,6 @@ func (a OAuth2Api) IntrospectOAuth2Token(token string, scope string) (*OAuth2Tok if a.Configuration.AccessToken != "" { localVarHeaderParams["Authorization"] = "Bearer " + a.Configuration.AccessToken } - // add default headers if any for key := range a.Configuration.DefaultHeader { localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] @@ -725,19 +851,19 @@ func (a OAuth2Api) OauthToken() (*OauthTokenResponse, *APIResponse, error) { } /** - * Reject a consent request - * Call this endpoint to reject a consent request. This usually happens when a user denies access rights to an application. The consent request id is usually transmitted via the URL query `consent`. For example: `http://consent-app.mydomain.com/?consent=1234abcd` + * Reject an consent request + * When an authorization code, hybrid, or implicit OAuth 2.0 Flow is initiated, ORY Hydra asks the login provider to authenticate the user and then tell ORY Hydra now about it. If the user authenticated, he/she must now be asked if the OAuth 2.0 Client which initiated the flow should be allowed to access the resources on the user's behalf. The consent provider which handles this request and is a web app implemented and hosted by you. It shows a user interface which asks the user to grant or deny the client access to the requested scope (\"Application my-dropbox-app wants write access to all your private files\"). The consent challenge is appended to the consent provider's URL to which the user's user-agent (browser) is redirected to. The consent provider uses that challenge to fetch information on the OAuth2 request and then tells ORY Hydra if the user accepted or rejected the request. This endpoint tells ORY Hydra that the user has not authorized the OAuth 2.0 client to access resources on his/her behalf. The consent provider must include a reason why the consent was not granted. The response contains a redirect URL which the consent provider should redirect the user-agent to. * - * @param id + * @param challenge * @param body - * @return void + * @return *CompletedRequest */ -func (a OAuth2Api) RejectOAuth2ConsentRequest(id string, body ConsentRequestRejection) (*APIResponse, error) { +func (a OAuth2Api) RejectConsentRequest(challenge string, body RejectRequest) (*CompletedRequest, *APIResponse, error) { - var localVarHttpMethod = strings.ToUpper("Patch") + var localVarHttpMethod = strings.ToUpper("Put") // create path and map variables - localVarPath := a.Configuration.BasePath + "/oauth2/consent/requests/{id}/reject" - localVarPath = strings.Replace(localVarPath, "{"+"id"+"}", fmt.Sprintf("%v", id), -1) + localVarPath := a.Configuration.BasePath + "/oauth2/auth/requests/consent/{challenge}/reject" + localVarPath = strings.Replace(localVarPath, "{"+"challenge"+"}", fmt.Sprintf("%v", challenge), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} @@ -770,20 +896,86 @@ func (a OAuth2Api) RejectOAuth2ConsentRequest(id string, body ConsentRequestReje } // body params localVarPostBody = &body + var successPayload = new(CompletedRequest) localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) var localVarURL, _ = url.Parse(localVarPath) localVarURL.RawQuery = localVarQueryParams.Encode() - var localVarAPIResponse = &APIResponse{Operation: "RejectOAuth2ConsentRequest", Method: localVarHttpMethod, RequestURL: localVarURL.String()} + var localVarAPIResponse = &APIResponse{Operation: "RejectConsentRequest", Method: localVarHttpMethod, RequestURL: localVarURL.String()} if localVarHttpResponse != nil { localVarAPIResponse.Response = localVarHttpResponse.RawResponse localVarAPIResponse.Payload = localVarHttpResponse.Body() } if err != nil { - return localVarAPIResponse, err + return successPayload, localVarAPIResponse, err } - return localVarAPIResponse, err + err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload) + return successPayload, localVarAPIResponse, err +} + +/** + * Reject an logout request + * When an authorization code, hybrid, or implicit OAuth 2.0 Flow is initiated, ORY Hydra asks the login provider (sometimes called \"identity provider\") to authenticate the user and then tell ORY Hydra now about it. The login provider is an web-app you write and host, and it must be able to authenticate (\"show the user a login screen\") a user (in OAuth2 the proper name for user is \"resource owner\"). The authentication challenge is appended to the login provider URL to which the user's user-agent (browser) is redirected to. The login provider uses that challenge to fetch information on the OAuth2 request and then accept or reject the requested authentication process. This endpoint tells ORY Hydra that the user has not authenticated and includes a reason why the authentication was be denied. The response contains a redirect URL which the login provider should redirect the user-agent to. + * + * @param challenge + * @param body + * @return *CompletedRequest + */ +func (a OAuth2Api) RejectLoginRequest(challenge string, body RejectRequest) (*CompletedRequest, *APIResponse, error) { + + var localVarHttpMethod = strings.ToUpper("Put") + // create path and map variables + localVarPath := a.Configuration.BasePath + "/oauth2/auth/requests/login/{challenge}/reject" + localVarPath = strings.Replace(localVarPath, "{"+"challenge"+"}", fmt.Sprintf("%v", challenge), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := make(map[string]string) + var localVarPostBody interface{} + var localVarFileName string + var localVarFileBytes []byte + // add default headers if any + for key := range a.Configuration.DefaultHeader { + localVarHeaderParams[key] = a.Configuration.DefaultHeader[key] + } + + // to determine the Content-Type header + localVarHttpContentTypes := []string{"application/json"} + + // set Content-Type header + localVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes) + if localVarHttpContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHttpContentType + } + // to determine the Accept header + localVarHttpHeaderAccepts := []string{ + "application/json", + } + + // set Accept header + localVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts) + if localVarHttpHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHttpHeaderAccept + } + // body params + localVarPostBody = &body + var successPayload = new(CompletedRequest) + localVarHttpResponse, err := a.Configuration.APIClient.CallAPI(localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + + var localVarURL, _ = url.Parse(localVarPath) + localVarURL.RawQuery = localVarQueryParams.Encode() + var localVarAPIResponse = &APIResponse{Operation: "RejectLoginRequest", Method: localVarHttpMethod, RequestURL: localVarURL.String()} + if localVarHttpResponse != nil { + localVarAPIResponse.Response = localVarHttpResponse.RawResponse + localVarAPIResponse.Payload = localVarHttpResponse.Body() + } + + if err != nil { + return successPayload, localVarAPIResponse, err + } + err = json.Unmarshal(localVarHttpResponse.Body(), &successPayload) + return successPayload, localVarAPIResponse, err } /** diff --git a/sdk/go/hydra/swagger/o_auth2_consent_request.go b/sdk/go/hydra/swagger/o_auth2_consent_request.go deleted file mode 100644 index 26e81c840ea..00000000000 --- a/sdk/go/hydra/swagger/o_auth2_consent_request.go +++ /dev/null @@ -1,29 +0,0 @@ -/* - * ORY Hydra - Cloud Native OAuth 2.0 and OpenID Connect Server - * - * Welcome to the ORY Hydra HTTP API documentation. You will find documentation for all HTTP APIs here. Keep in mind that this document reflects the latest branch, always. Support for versioned documentation is coming in the future. - * - * OpenAPI spec version: Latest - * Contact: hi@ory.am - * Generated by: https://github.com/swagger-api/swagger-codegen.git - */ - -package swagger - -type OAuth2ConsentRequest struct { - - // ClientID is the client id that initiated the OAuth2 request. - ClientId string `json:"clientId,omitempty"` - - // ExpiresAt is the time where the access request will expire. - ExpiresAt string `json:"expiresAt,omitempty"` - - // ID is the id of this consent request. - Id string `json:"id,omitempty"` - - // Redirect URL is the URL where the user agent should be redirected to after the consent has been accepted or rejected. - RedirectUrl string `json:"redirectUrl,omitempty"` - - // RequestedScopes represents a list of scopes that have been requested by the OAuth2 request initiator. - RequestedScopes []string `json:"requestedScopes,omitempty"` -} diff --git a/sdk/go/hydra/swagger/open_id_connect_context.go b/sdk/go/hydra/swagger/open_id_connect_context.go new file mode 100644 index 00000000000..7922b287844 --- /dev/null +++ b/sdk/go/hydra/swagger/open_id_connect_context.go @@ -0,0 +1,23 @@ +/* + * ORY Hydra - Cloud Native OAuth 2.0 and OpenID Connect Server + * + * Welcome to the ORY Hydra HTTP API documentation. You will find documentation for all HTTP APIs here. Keep in mind that this document reflects the latest branch, always. Support for versioned documentation is coming in the future. + * + * OpenAPI spec version: Latest + * Contact: hi@ory.am + * Generated by: https://github.com/swagger-api/swagger-codegen.git + */ + +package swagger + +type OpenIdConnectContext struct { + + // ACRValues is the Authentication AuthorizationContext Class Reference requested in the OAuth 2.0 Authorization request. It is a parameter defined by OpenID Connect and expresses which level of authentication (e.g. 2FA) is required. OpenID Connect defines it as follows: > Requested Authentication AuthorizationContext Class Reference values. Space-separated string that specifies the acr values that the Authorization Server is being requested to use for processing this Authentication Request, with the values appearing in order of preference. The Authentication AuthorizationContext Class satisfied by the authentication performed is returned as the acr Claim Value, as specified in Section 2. The acr Claim is requested as a Voluntary Claim by this parameter. + AcrValues []string `json:"acr_values,omitempty"` + + // Display is a string value that specifies how the Authorization Server displays the authentication and consent user interface pages to the End-User. The defined values are: page: The Authorization Server SHOULD display the authentication and consent UI consistent with a full User Agent page view. If the display parameter is not specified, this is the default display mode. popup: The Authorization Server SHOULD display the authentication and consent UI consistent with a popup User Agent window. The popup User Agent window should be of an appropriate size for a login-focused dialog and should not obscure the entire window that it is popping up over. touch: The Authorization Server SHOULD display the authentication and consent UI consistent with a device that leverages a touch interface. wap: The Authorization Server SHOULD display the authentication and consent UI consistent with a \"feature phone\" type display. The Authorization Server MAY also attempt to detect the capabilities of the User Agent and present an appropriate display. + Display string `json:"display,omitempty"` + + // UILocales is the End-User'id preferred languages and scripts for the user interface, represented as a space-separated list of BCP47 [RFC5646] language tag values, ordered by preference. For instance, the value \"fr-CA fr en\" represents a preference for French as spoken in Canada, then French (without a region designation), followed by English (without a region designation). An error SHOULD NOT result if some or all of the requested locales are not supported by the OpenID Provider. + UiLocales []string `json:"ui_locales,omitempty"` +} diff --git a/sdk/go/hydra/swagger/swagger_accept_consent_request.go b/sdk/go/hydra/swagger/reject_request.go similarity index 61% rename from sdk/go/hydra/swagger/swagger_accept_consent_request.go rename to sdk/go/hydra/swagger/reject_request.go index dac833b5ba7..31c9539606f 100644 --- a/sdk/go/hydra/swagger/swagger_accept_consent_request.go +++ b/sdk/go/hydra/swagger/reject_request.go @@ -10,9 +10,14 @@ package swagger -type SwaggerAcceptConsentRequest struct { - Body ConsentRequestAcceptance `json:"Body"` +type RejectRequest struct { + Error_ string `json:"error,omitempty"` - // in: path - Id string `json:"id"` + ErrorDebug string `json:"error_debug,omitempty"` + + ErrorDescription string `json:"error_description,omitempty"` + + ErrorHint string `json:"error_hint,omitempty"` + + StatusCode int64 `json:"status_code,omitempty"` } diff --git a/sdk/go/hydra/swagger/swagger_reject_consent_request.go b/sdk/go/hydra/swagger/swagger_reject_consent_request.go deleted file mode 100644 index 795343a93f7..00000000000 --- a/sdk/go/hydra/swagger/swagger_reject_consent_request.go +++ /dev/null @@ -1,18 +0,0 @@ -/* - * ORY Hydra - Cloud Native OAuth 2.0 and OpenID Connect Server - * - * Welcome to the ORY Hydra HTTP API documentation. You will find documentation for all HTTP APIs here. Keep in mind that this document reflects the latest branch, always. Support for versioned documentation is coming in the future. - * - * OpenAPI spec version: Latest - * Contact: hi@ory.am - * Generated by: https://github.com/swagger-api/swagger-codegen.git - */ - -package swagger - -type SwaggerRejectConsentRequest struct { - Body ConsentRequestRejection `json:"Body"` - - // in: path - Id string `json:"id"` -} diff --git a/sdk/js/swagger/README.md b/sdk/js/swagger/README.md index 481c2a34647..409e1f01643 100644 --- a/sdk/js/swagger/README.md +++ b/sdk/js/swagger/README.md @@ -123,18 +123,21 @@ Class | Method | HTTP request | Description *OryHydraCloudNativeOAuth20AndOpenIdConnectServer.JsonWebKeyApi* | [**getJsonWebKeySet**](docs/JsonWebKeyApi.md#getJsonWebKeySet) | **GET** /keys/{set} | Retrieve a JSON Web Key Set *OryHydraCloudNativeOAuth20AndOpenIdConnectServer.JsonWebKeyApi* | [**updateJsonWebKey**](docs/JsonWebKeyApi.md#updateJsonWebKey) | **PUT** /keys/{set}/{kid} | Update a JSON Web Key *OryHydraCloudNativeOAuth20AndOpenIdConnectServer.JsonWebKeyApi* | [**updateJsonWebKeySet**](docs/JsonWebKeyApi.md#updateJsonWebKeySet) | **PUT** /keys/{set} | Update a JSON Web Key Set -*OryHydraCloudNativeOAuth20AndOpenIdConnectServer.OAuth2Api* | [**acceptOAuth2ConsentRequest**](docs/OAuth2Api.md#acceptOAuth2ConsentRequest) | **PATCH** /oauth2/consent/requests/{id}/accept | Accept a consent request +*OryHydraCloudNativeOAuth20AndOpenIdConnectServer.OAuth2Api* | [**acceptConsentRequest**](docs/OAuth2Api.md#acceptConsentRequest) | **PUT** /oauth2/auth/requests/consent/{challenge}/accept | Accept an consent request +*OryHydraCloudNativeOAuth20AndOpenIdConnectServer.OAuth2Api* | [**acceptLoginRequest**](docs/OAuth2Api.md#acceptLoginRequest) | **PUT** /oauth2/auth/requests/login/{challenge}/accept | Accept an login request *OryHydraCloudNativeOAuth20AndOpenIdConnectServer.OAuth2Api* | [**createOAuth2Client**](docs/OAuth2Api.md#createOAuth2Client) | **POST** /clients | Create an OAuth 2.0 client *OryHydraCloudNativeOAuth20AndOpenIdConnectServer.OAuth2Api* | [**deleteOAuth2Client**](docs/OAuth2Api.md#deleteOAuth2Client) | **DELETE** /clients/{id} | Deletes an OAuth 2.0 Client *OryHydraCloudNativeOAuth20AndOpenIdConnectServer.OAuth2Api* | [**flushInactiveOAuth2Tokens**](docs/OAuth2Api.md#flushInactiveOAuth2Tokens) | **POST** /oauth2/flush | Flush Expired OAuth2 Access Tokens +*OryHydraCloudNativeOAuth20AndOpenIdConnectServer.OAuth2Api* | [**getConsentRequest**](docs/OAuth2Api.md#getConsentRequest) | **GET** /oauth2/auth/requests/consent/{challenge} | Get consent request information +*OryHydraCloudNativeOAuth20AndOpenIdConnectServer.OAuth2Api* | [**getLoginRequest**](docs/OAuth2Api.md#getLoginRequest) | **GET** /oauth2/auth/requests/login/{challenge} | Get an login request *OryHydraCloudNativeOAuth20AndOpenIdConnectServer.OAuth2Api* | [**getOAuth2Client**](docs/OAuth2Api.md#getOAuth2Client) | **GET** /clients/{id} | Get an OAuth 2.0 Client. -*OryHydraCloudNativeOAuth20AndOpenIdConnectServer.OAuth2Api* | [**getOAuth2ConsentRequest**](docs/OAuth2Api.md#getOAuth2ConsentRequest) | **GET** /oauth2/consent/requests/{id} | Receive consent request information *OryHydraCloudNativeOAuth20AndOpenIdConnectServer.OAuth2Api* | [**getWellKnown**](docs/OAuth2Api.md#getWellKnown) | **GET** /.well-known/openid-configuration | Server well known configuration *OryHydraCloudNativeOAuth20AndOpenIdConnectServer.OAuth2Api* | [**introspectOAuth2Token**](docs/OAuth2Api.md#introspectOAuth2Token) | **POST** /oauth2/introspect | Introspect OAuth2 tokens *OryHydraCloudNativeOAuth20AndOpenIdConnectServer.OAuth2Api* | [**listOAuth2Clients**](docs/OAuth2Api.md#listOAuth2Clients) | **GET** /clients | List OAuth 2.0 Clients *OryHydraCloudNativeOAuth20AndOpenIdConnectServer.OAuth2Api* | [**oauthAuth**](docs/OAuth2Api.md#oauthAuth) | **GET** /oauth2/auth | The OAuth 2.0 authorize endpoint *OryHydraCloudNativeOAuth20AndOpenIdConnectServer.OAuth2Api* | [**oauthToken**](docs/OAuth2Api.md#oauthToken) | **POST** /oauth2/token | The OAuth 2.0 token endpoint -*OryHydraCloudNativeOAuth20AndOpenIdConnectServer.OAuth2Api* | [**rejectOAuth2ConsentRequest**](docs/OAuth2Api.md#rejectOAuth2ConsentRequest) | **PATCH** /oauth2/consent/requests/{id}/reject | Reject a consent request +*OryHydraCloudNativeOAuth20AndOpenIdConnectServer.OAuth2Api* | [**rejectConsentRequest**](docs/OAuth2Api.md#rejectConsentRequest) | **PUT** /oauth2/auth/requests/consent/{challenge}/reject | Reject an consent request +*OryHydraCloudNativeOAuth20AndOpenIdConnectServer.OAuth2Api* | [**rejectLoginRequest**](docs/OAuth2Api.md#rejectLoginRequest) | **PUT** /oauth2/auth/requests/login/{challenge}/reject | Reject an logout request *OryHydraCloudNativeOAuth20AndOpenIdConnectServer.OAuth2Api* | [**revokeOAuth2Token**](docs/OAuth2Api.md#revokeOAuth2Token) | **POST** /oauth2/revoke | Revoke OAuth2 tokens *OryHydraCloudNativeOAuth20AndOpenIdConnectServer.OAuth2Api* | [**updateOAuth2Client**](docs/OAuth2Api.md#updateOAuth2Client) | **PUT** /clients/{id} | Update an OAuth 2.0 Client *OryHydraCloudNativeOAuth20AndOpenIdConnectServer.OAuth2Api* | [**userinfo**](docs/OAuth2Api.md#userinfo) | **POST** /userinfo | OpenID Connect Userinfo @@ -143,10 +146,12 @@ Class | Method | HTTP request | Description ## Documentation for Models + - [OryHydraCloudNativeOAuth20AndOpenIdConnectServer.AcceptConsentRequest](docs/AcceptConsentRequest.md) + - [OryHydraCloudNativeOAuth20AndOpenIdConnectServer.AcceptLoginRequest](docs/AcceptLoginRequest.md) + - [OryHydraCloudNativeOAuth20AndOpenIdConnectServer.AuthenticationSession](docs/AuthenticationSession.md) + - [OryHydraCloudNativeOAuth20AndOpenIdConnectServer.CompletedRequest](docs/CompletedRequest.md) - [OryHydraCloudNativeOAuth20AndOpenIdConnectServer.ConsentRequest](docs/ConsentRequest.md) - - [OryHydraCloudNativeOAuth20AndOpenIdConnectServer.ConsentRequestAcceptance](docs/ConsentRequestAcceptance.md) - - [OryHydraCloudNativeOAuth20AndOpenIdConnectServer.ConsentRequestManager](docs/ConsentRequestManager.md) - - [OryHydraCloudNativeOAuth20AndOpenIdConnectServer.ConsentRequestRejection](docs/ConsentRequestRejection.md) + - [OryHydraCloudNativeOAuth20AndOpenIdConnectServer.ConsentRequestSession](docs/ConsentRequestSession.md) - [OryHydraCloudNativeOAuth20AndOpenIdConnectServer.FlushInactiveOAuth2TokensRequest](docs/FlushInactiveOAuth2TokensRequest.md) - [OryHydraCloudNativeOAuth20AndOpenIdConnectServer.Handler](docs/Handler.md) - [OryHydraCloudNativeOAuth20AndOpenIdConnectServer.InlineResponse200](docs/InlineResponse200.md) @@ -156,22 +161,21 @@ Class | Method | HTTP request | Description - [OryHydraCloudNativeOAuth20AndOpenIdConnectServer.JsonWebKeySet](docs/JsonWebKeySet.md) - [OryHydraCloudNativeOAuth20AndOpenIdConnectServer.JsonWebKeySetGeneratorRequest](docs/JsonWebKeySetGeneratorRequest.md) - [OryHydraCloudNativeOAuth20AndOpenIdConnectServer.KeyGenerator](docs/KeyGenerator.md) + - [OryHydraCloudNativeOAuth20AndOpenIdConnectServer.LoginRequest](docs/LoginRequest.md) - [OryHydraCloudNativeOAuth20AndOpenIdConnectServer.Manager](docs/Manager.md) - [OryHydraCloudNativeOAuth20AndOpenIdConnectServer.OAuth2Client](docs/OAuth2Client.md) - - [OryHydraCloudNativeOAuth20AndOpenIdConnectServer.OAuth2ConsentRequest](docs/OAuth2ConsentRequest.md) - [OryHydraCloudNativeOAuth20AndOpenIdConnectServer.OAuth2TokenIntrospection](docs/OAuth2TokenIntrospection.md) - [OryHydraCloudNativeOAuth20AndOpenIdConnectServer.OauthTokenResponse](docs/OauthTokenResponse.md) + - [OryHydraCloudNativeOAuth20AndOpenIdConnectServer.OpenIDConnectContext](docs/OpenIDConnectContext.md) - [OryHydraCloudNativeOAuth20AndOpenIdConnectServer.RawMessage](docs/RawMessage.md) - - [OryHydraCloudNativeOAuth20AndOpenIdConnectServer.SwaggerAcceptConsentRequest](docs/SwaggerAcceptConsentRequest.md) + - [OryHydraCloudNativeOAuth20AndOpenIdConnectServer.RejectRequest](docs/RejectRequest.md) - [OryHydraCloudNativeOAuth20AndOpenIdConnectServer.SwaggerFlushInactiveAccessTokens](docs/SwaggerFlushInactiveAccessTokens.md) - [OryHydraCloudNativeOAuth20AndOpenIdConnectServer.SwaggerJsonWebKeyQuery](docs/SwaggerJsonWebKeyQuery.md) - [OryHydraCloudNativeOAuth20AndOpenIdConnectServer.SwaggerJwkCreateSet](docs/SwaggerJwkCreateSet.md) - [OryHydraCloudNativeOAuth20AndOpenIdConnectServer.SwaggerJwkSetQuery](docs/SwaggerJwkSetQuery.md) - [OryHydraCloudNativeOAuth20AndOpenIdConnectServer.SwaggerJwkUpdateSet](docs/SwaggerJwkUpdateSet.md) - [OryHydraCloudNativeOAuth20AndOpenIdConnectServer.SwaggerJwkUpdateSetKey](docs/SwaggerJwkUpdateSetKey.md) - - [OryHydraCloudNativeOAuth20AndOpenIdConnectServer.SwaggerOAuthConsentRequestPayload](docs/SwaggerOAuthConsentRequestPayload.md) - [OryHydraCloudNativeOAuth20AndOpenIdConnectServer.SwaggerOAuthIntrospectionRequest](docs/SwaggerOAuthIntrospectionRequest.md) - - [OryHydraCloudNativeOAuth20AndOpenIdConnectServer.SwaggerRejectConsentRequest](docs/SwaggerRejectConsentRequest.md) - [OryHydraCloudNativeOAuth20AndOpenIdConnectServer.SwaggerRevokeOAuth2TokenParameters](docs/SwaggerRevokeOAuth2TokenParameters.md) - [OryHydraCloudNativeOAuth20AndOpenIdConnectServer.UserinfoResponse](docs/UserinfoResponse.md) - [OryHydraCloudNativeOAuth20AndOpenIdConnectServer.WellKnown](docs/WellKnown.md) diff --git a/sdk/js/swagger/docs/AcceptConsentRequest.md b/sdk/js/swagger/docs/AcceptConsentRequest.md new file mode 100644 index 00000000000..0518d325f37 --- /dev/null +++ b/sdk/js/swagger/docs/AcceptConsentRequest.md @@ -0,0 +1,11 @@ +# OryHydraCloudNativeOAuth20AndOpenIdConnectServer.AcceptConsentRequest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**grantScope** | **[String]** | GrantScope sets the scope the user authorized the client to use. Should be a subset of `requested_scope` | [optional] +**remember** | **Boolean** | Remember, if set to true, tells ORY Hydra to remember this consent authorization and reuse it if the same client asks the same user for the same, or a subset of, scope. | [optional] +**rememberFor** | **Number** | RememberFor sets how long the consent authorization should be remembered for in seconds. If set to `0`, the authorization will be remembered indefinitely. | [optional] +**session** | [**ConsentRequestSession**](ConsentRequestSession.md) | | [optional] + + diff --git a/sdk/js/swagger/docs/AcceptLoginRequest.md b/sdk/js/swagger/docs/AcceptLoginRequest.md new file mode 100644 index 00000000000..ea93435328f --- /dev/null +++ b/sdk/js/swagger/docs/AcceptLoginRequest.md @@ -0,0 +1,11 @@ +# OryHydraCloudNativeOAuth20AndOpenIdConnectServer.AcceptLoginRequest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**acr** | **String** | ACR sets the Authentication AuthorizationContext Class Reference value for this authentication session. You can use it to express that, for example, a user authenticated using two factor authentication. | [optional] +**remember** | **Boolean** | Remember, if set to true, tells ORY Hydra to remember this user by telling the user agent (browser) to store a cookie with authentication data. If the same user performs another OAuth 2.0 Authorization Request, he/she will not be asked to log in again. | [optional] +**rememberFor** | **Number** | RememberFor sets how long the authentication should be remembered for in seconds. If set to `0`, the authorization will be remembered indefinitely. | [optional] +**subject** | **String** | Subject is the user ID of the end-user that authenticated. | [optional] + + diff --git a/sdk/js/swagger/docs/AuthenticationSession.md b/sdk/js/swagger/docs/AuthenticationSession.md new file mode 100644 index 00000000000..a7527f6de20 --- /dev/null +++ b/sdk/js/swagger/docs/AuthenticationSession.md @@ -0,0 +1,10 @@ +# OryHydraCloudNativeOAuth20AndOpenIdConnectServer.AuthenticationSession + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**authenticatedAt** | **Date** | | [optional] +**ID** | **String** | | [optional] +**subject** | **String** | | [optional] + + diff --git a/sdk/js/swagger/docs/CompletedRequest.md b/sdk/js/swagger/docs/CompletedRequest.md new file mode 100644 index 00000000000..ee9776cd743 --- /dev/null +++ b/sdk/js/swagger/docs/CompletedRequest.md @@ -0,0 +1,8 @@ +# OryHydraCloudNativeOAuth20AndOpenIdConnectServer.CompletedRequest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**redirectTo** | **String** | RedirectURL is the URL which you should redirect the user to once the authentication process is completed. | [optional] + + diff --git a/sdk/js/swagger/docs/ConsentRequest.md b/sdk/js/swagger/docs/ConsentRequest.md index 9b63c966a7b..51e023b5479 100644 --- a/sdk/js/swagger/docs/ConsentRequest.md +++ b/sdk/js/swagger/docs/ConsentRequest.md @@ -3,10 +3,12 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**clientId** | **String** | ClientID is the client id that initiated the OAuth2 request. | [optional] -**expiresAt** | **Date** | ExpiresAt is the time where the access request will expire. | [optional] -**id** | **String** | ID is the id of this consent request. | [optional] -**redirectUrl** | **String** | Redirect URL is the URL where the user agent should be redirected to after the consent has been accepted or rejected. | [optional] -**requestedScopes** | **[String]** | RequestedScopes represents a list of scopes that have been requested by the OAuth2 request initiator. | [optional] +**challenge** | **String** | Challenge is the identifier (\"authorization challenge\") of the consent authorization request. It is used to identify the session. | [optional] +**client** | [**OAuth2Client**](OAuth2Client.md) | | [optional] +**oidcContext** | [**OpenIDConnectContext**](OpenIDConnectContext.md) | | [optional] +**requestUrl** | **String** | RequestURL is the original OAuth 2.0 Authorization URL requested by the OAuth 2.0 client. It is the URL which initiates the OAuth 2.0 Authorization Code or OAuth 2.0 Implicit flow. This URL is typically not needed, but might come in handy if you want to deal with additional request parameters. | [optional] +**requestedScope** | **[String]** | RequestedScope contains all scopes requested by the OAuth 2.0 client. | [optional] +**skip** | **Boolean** | Skip, if true, implies that the client has requested the same scopes from the same user previously. If true, you must not ask the user to grant the requested scopes. You must however either allow or deny the consent request using the usual API call. | [optional] +**subject** | **String** | Subject is the user ID of the end-user that authenticated. Now, that end user needs to grant or deny the scope requested by the OAuth 2.0 client. | [optional] diff --git a/sdk/js/swagger/docs/ConsentRequestAcceptance.md b/sdk/js/swagger/docs/ConsentRequestAcceptance.md deleted file mode 100644 index 087b0e2842b..00000000000 --- a/sdk/js/swagger/docs/ConsentRequestAcceptance.md +++ /dev/null @@ -1,11 +0,0 @@ -# OryHydraCloudNativeOAuth20AndOpenIdConnectServer.ConsentRequestAcceptance - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**accessTokenExtra** | **{String: Object}** | AccessTokenExtra represents arbitrary data that will be added to the access token and that will be returned on introspection and warden requests. | [optional] -**grantScopes** | **[String]** | A list of scopes that the user agreed to grant. It should be a subset of requestedScopes from the consent request. | [optional] -**idTokenExtra** | **{String: Object}** | IDTokenExtra represents arbitrary data that will be added to the ID token. The ID token will only be issued if the user agrees to it and if the client requested an ID token. | [optional] -**subject** | **String** | Subject represents a unique identifier of the user (or service, or legal entity, ...) that accepted the OAuth2 request. | [optional] - - diff --git a/sdk/js/swagger/docs/ConsentRequestManager.md b/sdk/js/swagger/docs/ConsentRequestManager.md deleted file mode 100644 index 60822ad928c..00000000000 --- a/sdk/js/swagger/docs/ConsentRequestManager.md +++ /dev/null @@ -1,7 +0,0 @@ -# OryHydraCloudNativeOAuth20AndOpenIdConnectServer.ConsentRequestManager - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - - diff --git a/sdk/js/swagger/docs/ConsentRequestRejection.md b/sdk/js/swagger/docs/ConsentRequestRejection.md deleted file mode 100644 index 6ff18e1595d..00000000000 --- a/sdk/js/swagger/docs/ConsentRequestRejection.md +++ /dev/null @@ -1,8 +0,0 @@ -# OryHydraCloudNativeOAuth20AndOpenIdConnectServer.ConsentRequestRejection - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**reason** | **String** | Reason represents the reason why the user rejected the consent request. | [optional] - - diff --git a/sdk/js/swagger/docs/ConsentRequestSession.md b/sdk/js/swagger/docs/ConsentRequestSession.md new file mode 100644 index 00000000000..d2c62ca6cf7 --- /dev/null +++ b/sdk/js/swagger/docs/ConsentRequestSession.md @@ -0,0 +1,9 @@ +# OryHydraCloudNativeOAuth20AndOpenIdConnectServer.ConsentRequestSession + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**accessToken** | **{String: Object}** | AccessToken sets session data for the access and refresh token, as well as any future tokens issued by the refresh grant. Keep in mind that this data will be available to anyone performing OAuth 2.0 Challenge Introspection. If only your services can perform OAuth 2.0 Challenge Introspection, this is usually fine. But if third parties can access that endpoint as well, sensitive data from the session might be exposed to them. Use with care! | [optional] +**idToken** | **{String: Object}** | IDToken sets session data for the OpenID Connect ID token. Keep in mind that the session'id payloads are readable by anyone that has access to the ID Challenge. Use with care! | [optional] + + diff --git a/sdk/js/swagger/docs/Handler.md b/sdk/js/swagger/docs/Handler.md index 91171a00453..20d8712f2a4 100644 --- a/sdk/js/swagger/docs/Handler.md +++ b/sdk/js/swagger/docs/Handler.md @@ -3,6 +3,7 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- +**generators** | [**{String: KeyGenerator}**](KeyGenerator.md) | | [optional] **H** | [**Writer**](Writer.md) | | [optional] **manager** | [**Manager**](Manager.md) | | [optional] **resourcePrefix** | **String** | | [optional] diff --git a/sdk/js/swagger/docs/LoginRequest.md b/sdk/js/swagger/docs/LoginRequest.md new file mode 100644 index 00000000000..b42bb0c2ef7 --- /dev/null +++ b/sdk/js/swagger/docs/LoginRequest.md @@ -0,0 +1,14 @@ +# OryHydraCloudNativeOAuth20AndOpenIdConnectServer.LoginRequest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**challenge** | **String** | Challenge is the identifier (\"authentication challenge\") of the consent authentication request. It is used to identify the session. | [optional] +**client** | [**OAuth2Client**](OAuth2Client.md) | | [optional] +**oidcContext** | [**OpenIDConnectContext**](OpenIDConnectContext.md) | | [optional] +**requestUrl** | **String** | RequestURL is the original OAuth 2.0 Authorization URL requested by the OAuth 2.0 client. It is the URL which initiates the OAuth 2.0 Authorization Code or OAuth 2.0 Implicit flow. This URL is typically not needed, but might come in handy if you want to deal with additional request parameters. | [optional] +**requestedScope** | **[String]** | RequestedScope contains all scopes requested by the OAuth 2.0 client. | [optional] +**skip** | **Boolean** | Skip, if true, implies that the client has requested the same scopes from the same user previously. If true, you can skip asking the user to grant the requested scopes, and simply forward the user to the redirect URL. This feature allows you to update / set session information. | [optional] +**subject** | **String** | Subject is the user ID of the end-user that authenticated. Now, that end user needs to grant or deny the scope requested by the OAuth 2.0 client. | [optional] + + diff --git a/sdk/js/swagger/docs/OAuth2Api.md b/sdk/js/swagger/docs/OAuth2Api.md index cd1b014aa7c..be3677735ea 100644 --- a/sdk/js/swagger/docs/OAuth2Api.md +++ b/sdk/js/swagger/docs/OAuth2Api.md @@ -4,31 +4,34 @@ All URIs are relative to *http://localhost* Method | HTTP request | Description ------------- | ------------- | ------------- -[**acceptOAuth2ConsentRequest**](OAuth2Api.md#acceptOAuth2ConsentRequest) | **PATCH** /oauth2/consent/requests/{id}/accept | Accept a consent request +[**acceptConsentRequest**](OAuth2Api.md#acceptConsentRequest) | **PUT** /oauth2/auth/requests/consent/{challenge}/accept | Accept an consent request +[**acceptLoginRequest**](OAuth2Api.md#acceptLoginRequest) | **PUT** /oauth2/auth/requests/login/{challenge}/accept | Accept an login request [**createOAuth2Client**](OAuth2Api.md#createOAuth2Client) | **POST** /clients | Create an OAuth 2.0 client [**deleteOAuth2Client**](OAuth2Api.md#deleteOAuth2Client) | **DELETE** /clients/{id} | Deletes an OAuth 2.0 Client [**flushInactiveOAuth2Tokens**](OAuth2Api.md#flushInactiveOAuth2Tokens) | **POST** /oauth2/flush | Flush Expired OAuth2 Access Tokens +[**getConsentRequest**](OAuth2Api.md#getConsentRequest) | **GET** /oauth2/auth/requests/consent/{challenge} | Get consent request information +[**getLoginRequest**](OAuth2Api.md#getLoginRequest) | **GET** /oauth2/auth/requests/login/{challenge} | Get an login request [**getOAuth2Client**](OAuth2Api.md#getOAuth2Client) | **GET** /clients/{id} | Get an OAuth 2.0 Client. -[**getOAuth2ConsentRequest**](OAuth2Api.md#getOAuth2ConsentRequest) | **GET** /oauth2/consent/requests/{id} | Receive consent request information [**getWellKnown**](OAuth2Api.md#getWellKnown) | **GET** /.well-known/openid-configuration | Server well known configuration [**introspectOAuth2Token**](OAuth2Api.md#introspectOAuth2Token) | **POST** /oauth2/introspect | Introspect OAuth2 tokens [**listOAuth2Clients**](OAuth2Api.md#listOAuth2Clients) | **GET** /clients | List OAuth 2.0 Clients [**oauthAuth**](OAuth2Api.md#oauthAuth) | **GET** /oauth2/auth | The OAuth 2.0 authorize endpoint [**oauthToken**](OAuth2Api.md#oauthToken) | **POST** /oauth2/token | The OAuth 2.0 token endpoint -[**rejectOAuth2ConsentRequest**](OAuth2Api.md#rejectOAuth2ConsentRequest) | **PATCH** /oauth2/consent/requests/{id}/reject | Reject a consent request +[**rejectConsentRequest**](OAuth2Api.md#rejectConsentRequest) | **PUT** /oauth2/auth/requests/consent/{challenge}/reject | Reject an consent request +[**rejectLoginRequest**](OAuth2Api.md#rejectLoginRequest) | **PUT** /oauth2/auth/requests/login/{challenge}/reject | Reject an logout request [**revokeOAuth2Token**](OAuth2Api.md#revokeOAuth2Token) | **POST** /oauth2/revoke | Revoke OAuth2 tokens [**updateOAuth2Client**](OAuth2Api.md#updateOAuth2Client) | **PUT** /clients/{id} | Update an OAuth 2.0 Client [**userinfo**](OAuth2Api.md#userinfo) | **POST** /userinfo | OpenID Connect Userinfo [**wellKnown**](OAuth2Api.md#wellKnown) | **GET** /.well-known/jwks.json | Get Well-Known JSON Web Keys - -# **acceptOAuth2ConsentRequest** -> acceptOAuth2ConsentRequest(id, body) + +# **acceptConsentRequest** +> CompletedRequest acceptConsentRequest(challenge, opts) -Accept a consent request +Accept an consent request -Call this endpoint to accept a consent request. This usually happens when a user agrees to give access rights to an application. The consent request id is usually transmitted via the URL query `consent`. For example: `http://consent-app.mydomain.com/?consent=1234abcd` +When an authorization code, hybrid, or implicit OAuth 2.0 Flow is initiated, ORY Hydra asks the login provider to authenticate the user and then tell ORY Hydra now about it. If the user authenticated, he/she must now be asked if the OAuth 2.0 Client which initiated the flow should be allowed to access the resources on the user's behalf. The consent provider which handles this request and is a web app implemented and hosted by you. It shows a user interface which asks the user to grant or deny the client access to the requested scope (\"Application my-dropbox-app wants write access to all your private files\"). The consent challenge is appended to the consent provider's URL to which the user's user-agent (browser) is redirected to. The consent provider uses that challenge to fetch information on the OAuth2 request and then tells ORY Hydra if the user accepted or rejected the request. This endpoint tells ORY Hydra that the user has authorized the OAuth 2.0 client to access resources on his/her behalf. The consent provider includes additional information, such as session data for access and ID tokens, and if the consent request should be used as basis for future requests. The response contains a redirect URL which the consent provider should redirect the user-agent to. ### Example ```javascript @@ -36,31 +39,82 @@ var OryHydraCloudNativeOAuth20AndOpenIdConnectServer = require('ory_hydra___clou var apiInstance = new OryHydraCloudNativeOAuth20AndOpenIdConnectServer.OAuth2Api(); -var id = "id_example"; // String | +var challenge = "challenge_example"; // String | -var body = new OryHydraCloudNativeOAuth20AndOpenIdConnectServer.ConsentRequestAcceptance(); // ConsentRequestAcceptance | +var opts = { + 'body': new OryHydraCloudNativeOAuth20AndOpenIdConnectServer.AcceptConsentRequest() // AcceptConsentRequest | +}; + +var callback = function(error, data, response) { + if (error) { + console.error(error); + } else { + console.log('API called successfully. Returned data: ' + data); + } +}; +apiInstance.acceptConsentRequest(challenge, opts, callback); +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **challenge** | **String**| | + **body** | [**AcceptConsentRequest**](AcceptConsentRequest.md)| | [optional] + +### Return type +[**CompletedRequest**](CompletedRequest.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + + +# **acceptLoginRequest** +> CompletedRequest acceptLoginRequest(challenge, opts) + +Accept an login request + +When an authorization code, hybrid, or implicit OAuth 2.0 Flow is initiated, ORY Hydra asks the login provider (sometimes called \"identity provider\") to authenticate the user and then tell ORY Hydra now about it. The login provider is an web-app you write and host, and it must be able to authenticate (\"show the user a login screen\") a user (in OAuth2 the proper name for user is \"resource owner\"). The authentication challenge is appended to the login provider URL to which the user's user-agent (browser) is redirected to. The login provider uses that challenge to fetch information on the OAuth2 request and then accept or reject the requested authentication process. This endpoint tells ORY Hydra that the user has successfully authenticated and includes additional information such as the user's ID and if ORY Hydra should remember the user's user agent for future authentication attempts by setting a cookie. The response contains a redirect URL which the login provider should redirect the user-agent to. + +### Example +```javascript +var OryHydraCloudNativeOAuth20AndOpenIdConnectServer = require('ory_hydra___cloud_native_o_auth_20_and_open_id_connect_server'); + +var apiInstance = new OryHydraCloudNativeOAuth20AndOpenIdConnectServer.OAuth2Api(); + +var challenge = "challenge_example"; // String | + +var opts = { + 'body': new OryHydraCloudNativeOAuth20AndOpenIdConnectServer.AcceptLoginRequest() // AcceptLoginRequest | +}; var callback = function(error, data, response) { if (error) { console.error(error); } else { - console.log('API called successfully.'); + console.log('API called successfully. Returned data: ' + data); } }; -apiInstance.acceptOAuth2ConsentRequest(id, body, callback); +apiInstance.acceptLoginRequest(challenge, opts, callback); ``` ### Parameters Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **id** | **String**| | - **body** | [**ConsentRequestAcceptance**](ConsentRequestAcceptance.md)| | + **challenge** | **String**| | + **body** | [**AcceptLoginRequest**](AcceptLoginRequest.md)| | [optional] ### Return type -null (empty response body) +[**CompletedRequest**](CompletedRequest.md) ### Authorization @@ -210,13 +264,13 @@ No authorization required - **Content-Type**: application/json - **Accept**: application/json - -# **getOAuth2Client** -> OAuth2Client getOAuth2Client(id) + +# **getConsentRequest** +> ConsentRequest getConsentRequest(challenge) -Get an OAuth 2.0 Client. +Get consent request information -Get an OAUth 2.0 client by its ID. This endpoint never returns passwords. OAuth 2.0 clients are used to perform OAuth 2.0 and OpenID Connect flows. Usually, OAuth 2.0 clients are generated for applications which want to consume your OAuth 2.0 or OpenID Connect capabilities. To manage ORY Hydra, you will need an OAuth 2.0 Client as well. Make sure that this endpoint is well protected and only callable by first-party components. +When an authorization code, hybrid, or implicit OAuth 2.0 Flow is initiated, ORY Hydra asks the login provider to authenticate the user and then tell ORY Hydra now about it. If the user authenticated, he/she must now be asked if the OAuth 2.0 Client which initiated the flow should be allowed to access the resources on the user's behalf. The consent provider which handles this request and is a web app implemented and hosted by you. It shows a user interface which asks the user to grant or deny the client access to the requested scope (\"Application my-dropbox-app wants write access to all your private files\"). The consent challenge is appended to the consent provider's URL to which the user's user-agent (browser) is redirected to. The consent provider uses that challenge to fetch information on the OAuth2 request and then tells ORY Hydra if the user accepted or rejected the request. ### Example ```javascript @@ -224,7 +278,7 @@ var OryHydraCloudNativeOAuth20AndOpenIdConnectServer = require('ory_hydra___clou var apiInstance = new OryHydraCloudNativeOAuth20AndOpenIdConnectServer.OAuth2Api(); -var id = "id_example"; // String | The id of the OAuth 2.0 Client. +var challenge = "challenge_example"; // String | var callback = function(error, data, response) { @@ -234,18 +288,18 @@ var callback = function(error, data, response) { console.log('API called successfully. Returned data: ' + data); } }; -apiInstance.getOAuth2Client(id, callback); +apiInstance.getConsentRequest(challenge, callback); ``` ### Parameters Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **id** | **String**| The id of the OAuth 2.0 Client. | + **challenge** | **String**| | ### Return type -[**OAuth2Client**](OAuth2Client.md) +[**ConsentRequest**](ConsentRequest.md) ### Authorization @@ -256,13 +310,13 @@ No authorization required - **Content-Type**: application/json - **Accept**: application/json - -# **getOAuth2ConsentRequest** -> OAuth2ConsentRequest getOAuth2ConsentRequest(id) + +# **getLoginRequest** +> LoginRequest getLoginRequest(challenge) -Receive consent request information +Get an login request -Call this endpoint to receive information on consent requests. The consent request id is usually transmitted via the URL query `consent`. For example: `http://consent-app.mydomain.com/?consent=1234abcd` +When an authorization code, hybrid, or implicit OAuth 2.0 Flow is initiated, ORY Hydra asks the login provider (sometimes called \"identity provider\") to authenticate the user and then tell ORY Hydra now about it. The login provider is an web-app you write and host, and it must be able to authenticate (\"show the user a login screen\") a user (in OAuth2 the proper name for user is \"resource owner\"). The authentication challenge is appended to the login provider URL to which the user's user-agent (browser) is redirected to. The login provider uses that challenge to fetch information on the OAuth2 request and then accept or reject the requested authentication process. ### Example ```javascript @@ -270,7 +324,7 @@ var OryHydraCloudNativeOAuth20AndOpenIdConnectServer = require('ory_hydra___clou var apiInstance = new OryHydraCloudNativeOAuth20AndOpenIdConnectServer.OAuth2Api(); -var id = "id_example"; // String | The id of the OAuth 2.0 Consent Request. +var challenge = "challenge_example"; // String | var callback = function(error, data, response) { @@ -280,18 +334,64 @@ var callback = function(error, data, response) { console.log('API called successfully. Returned data: ' + data); } }; -apiInstance.getOAuth2ConsentRequest(id, callback); +apiInstance.getLoginRequest(challenge, callback); ``` ### Parameters Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **id** | **String**| The id of the OAuth 2.0 Consent Request. | + **challenge** | **String**| | ### Return type -[**OAuth2ConsentRequest**](OAuth2ConsentRequest.md) +[**LoginRequest**](LoginRequest.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + + +# **getOAuth2Client** +> OAuth2Client getOAuth2Client(id) + +Get an OAuth 2.0 Client. + +Get an OAUth 2.0 client by its ID. This endpoint never returns passwords. OAuth 2.0 clients are used to perform OAuth 2.0 and OpenID Connect flows. Usually, OAuth 2.0 clients are generated for applications which want to consume your OAuth 2.0 or OpenID Connect capabilities. To manage ORY Hydra, you will need an OAuth 2.0 Client as well. Make sure that this endpoint is well protected and only callable by first-party components. + +### Example +```javascript +var OryHydraCloudNativeOAuth20AndOpenIdConnectServer = require('ory_hydra___cloud_native_o_auth_20_and_open_id_connect_server'); + +var apiInstance = new OryHydraCloudNativeOAuth20AndOpenIdConnectServer.OAuth2Api(); + +var id = "id_example"; // String | The id of the OAuth 2.0 Client. + + +var callback = function(error, data, response) { + if (error) { + console.error(error); + } else { + console.log('API called successfully. Returned data: ' + data); + } +}; +apiInstance.getOAuth2Client(id, callback); +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **id** | **String**| The id of the OAuth 2.0 Client. | + +### Return type + +[**OAuth2Client**](OAuth2Client.md) ### Authorization @@ -541,13 +641,13 @@ This endpoint does not need any parameter. - **Content-Type**: application/x-www-form-urlencoded - **Accept**: application/json - -# **rejectOAuth2ConsentRequest** -> rejectOAuth2ConsentRequest(id, body) + +# **rejectConsentRequest** +> CompletedRequest rejectConsentRequest(challenge, opts) -Reject a consent request +Reject an consent request -Call this endpoint to reject a consent request. This usually happens when a user denies access rights to an application. The consent request id is usually transmitted via the URL query `consent`. For example: `http://consent-app.mydomain.com/?consent=1234abcd` +When an authorization code, hybrid, or implicit OAuth 2.0 Flow is initiated, ORY Hydra asks the login provider to authenticate the user and then tell ORY Hydra now about it. If the user authenticated, he/she must now be asked if the OAuth 2.0 Client which initiated the flow should be allowed to access the resources on the user's behalf. The consent provider which handles this request and is a web app implemented and hosted by you. It shows a user interface which asks the user to grant or deny the client access to the requested scope (\"Application my-dropbox-app wants write access to all your private files\"). The consent challenge is appended to the consent provider's URL to which the user's user-agent (browser) is redirected to. The consent provider uses that challenge to fetch information on the OAuth2 request and then tells ORY Hydra if the user accepted or rejected the request. This endpoint tells ORY Hydra that the user has not authorized the OAuth 2.0 client to access resources on his/her behalf. The consent provider must include a reason why the consent was not granted. The response contains a redirect URL which the consent provider should redirect the user-agent to. ### Example ```javascript @@ -555,31 +655,82 @@ var OryHydraCloudNativeOAuth20AndOpenIdConnectServer = require('ory_hydra___clou var apiInstance = new OryHydraCloudNativeOAuth20AndOpenIdConnectServer.OAuth2Api(); -var id = "id_example"; // String | +var challenge = "challenge_example"; // String | + +var opts = { + 'body': new OryHydraCloudNativeOAuth20AndOpenIdConnectServer.RejectRequest() // RejectRequest | +}; + +var callback = function(error, data, response) { + if (error) { + console.error(error); + } else { + console.log('API called successfully. Returned data: ' + data); + } +}; +apiInstance.rejectConsentRequest(challenge, opts, callback); +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **challenge** | **String**| | + **body** | [**RejectRequest**](RejectRequest.md)| | [optional] + +### Return type + +[**CompletedRequest**](CompletedRequest.md) + +### Authorization + +No authorization required + +### HTTP request headers -var body = new OryHydraCloudNativeOAuth20AndOpenIdConnectServer.ConsentRequestRejection(); // ConsentRequestRejection | + - **Content-Type**: application/json + - **Accept**: application/json + + +# **rejectLoginRequest** +> CompletedRequest rejectLoginRequest(challenge, opts) + +Reject an logout request + +When an authorization code, hybrid, or implicit OAuth 2.0 Flow is initiated, ORY Hydra asks the login provider (sometimes called \"identity provider\") to authenticate the user and then tell ORY Hydra now about it. The login provider is an web-app you write and host, and it must be able to authenticate (\"show the user a login screen\") a user (in OAuth2 the proper name for user is \"resource owner\"). The authentication challenge is appended to the login provider URL to which the user's user-agent (browser) is redirected to. The login provider uses that challenge to fetch information on the OAuth2 request and then accept or reject the requested authentication process. This endpoint tells ORY Hydra that the user has not authenticated and includes a reason why the authentication was be denied. The response contains a redirect URL which the login provider should redirect the user-agent to. + +### Example +```javascript +var OryHydraCloudNativeOAuth20AndOpenIdConnectServer = require('ory_hydra___cloud_native_o_auth_20_and_open_id_connect_server'); +var apiInstance = new OryHydraCloudNativeOAuth20AndOpenIdConnectServer.OAuth2Api(); + +var challenge = "challenge_example"; // String | + +var opts = { + 'body': new OryHydraCloudNativeOAuth20AndOpenIdConnectServer.RejectRequest() // RejectRequest | +}; var callback = function(error, data, response) { if (error) { console.error(error); } else { - console.log('API called successfully.'); + console.log('API called successfully. Returned data: ' + data); } }; -apiInstance.rejectOAuth2ConsentRequest(id, body, callback); +apiInstance.rejectLoginRequest(challenge, opts, callback); ``` ### Parameters Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **id** | **String**| | - **body** | [**ConsentRequestRejection**](ConsentRequestRejection.md)| | + **challenge** | **String**| | + **body** | [**RejectRequest**](RejectRequest.md)| | [optional] ### Return type -null (empty response body) +[**CompletedRequest**](CompletedRequest.md) ### Authorization diff --git a/sdk/js/swagger/docs/OAuth2consentRequest.md b/sdk/js/swagger/docs/OAuth2consentRequest.md deleted file mode 100644 index 8ce404e65cd..00000000000 --- a/sdk/js/swagger/docs/OAuth2consentRequest.md +++ /dev/null @@ -1,12 +0,0 @@ -# OryHydraCloudNativeOAuth20AndOpenIdConnectServer.OAuth2ConsentRequest - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**clientId** | **String** | ClientID is the client id that initiated the OAuth2 request. | [optional] -**expiresAt** | **String** | ExpiresAt is the time where the access request will expire. | [optional] -**id** | **String** | ID is the id of this consent request. | [optional] -**redirectUrl** | **String** | Redirect URL is the URL where the user agent should be redirected to after the consent has been accepted or rejected. | [optional] -**requestedScopes** | **[String]** | RequestedScopes represents a list of scopes that have been requested by the OAuth2 request initiator. | [optional] - - diff --git a/sdk/js/swagger/docs/OpenIDConnectContext.md b/sdk/js/swagger/docs/OpenIDConnectContext.md new file mode 100644 index 00000000000..881cfab5773 --- /dev/null +++ b/sdk/js/swagger/docs/OpenIDConnectContext.md @@ -0,0 +1,10 @@ +# OryHydraCloudNativeOAuth20AndOpenIdConnectServer.OpenIDConnectContext + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**acrValues** | **[String]** | ACRValues is the Authentication AuthorizationContext Class Reference requested in the OAuth 2.0 Authorization request. It is a parameter defined by OpenID Connect and expresses which level of authentication (e.g. 2FA) is required. OpenID Connect defines it as follows: > Requested Authentication AuthorizationContext Class Reference values. Space-separated string that specifies the acr values that the Authorization Server is being requested to use for processing this Authentication Request, with the values appearing in order of preference. The Authentication AuthorizationContext Class satisfied by the authentication performed is returned as the acr Claim Value, as specified in Section 2. The acr Claim is requested as a Voluntary Claim by this parameter. | [optional] +**display** | **String** | Display is a string value that specifies how the Authorization Server displays the authentication and consent user interface pages to the End-User. The defined values are: page: The Authorization Server SHOULD display the authentication and consent UI consistent with a full User Agent page view. If the display parameter is not specified, this is the default display mode. popup: The Authorization Server SHOULD display the authentication and consent UI consistent with a popup User Agent window. The popup User Agent window should be of an appropriate size for a login-focused dialog and should not obscure the entire window that it is popping up over. touch: The Authorization Server SHOULD display the authentication and consent UI consistent with a device that leverages a touch interface. wap: The Authorization Server SHOULD display the authentication and consent UI consistent with a \"feature phone\" type display. The Authorization Server MAY also attempt to detect the capabilities of the User Agent and present an appropriate display. | [optional] +**uiLocales** | **[String]** | UILocales is the End-User'id preferred languages and scripts for the user interface, represented as a space-separated list of BCP47 [RFC5646] language tag values, ordered by preference. For instance, the value \"fr-CA fr en\" represents a preference for French as spoken in Canada, then French (without a region designation), followed by English (without a region designation). An error SHOULD NOT result if some or all of the requested locales are not supported by the OpenID Provider. | [optional] + + diff --git a/sdk/js/swagger/docs/RejectRequest.md b/sdk/js/swagger/docs/RejectRequest.md new file mode 100644 index 00000000000..973b8ead7a4 --- /dev/null +++ b/sdk/js/swagger/docs/RejectRequest.md @@ -0,0 +1,12 @@ +# OryHydraCloudNativeOAuth20AndOpenIdConnectServer.RejectRequest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**error** | **String** | | [optional] +**errorDebug** | **String** | | [optional] +**errorDescription** | **String** | | [optional] +**errorHint** | **String** | | [optional] +**statusCode** | **Number** | | [optional] + + diff --git a/sdk/js/swagger/docs/SwaggerAcceptConsentRequest.md b/sdk/js/swagger/docs/SwaggerAcceptConsentRequest.md deleted file mode 100644 index 0670b18346b..00000000000 --- a/sdk/js/swagger/docs/SwaggerAcceptConsentRequest.md +++ /dev/null @@ -1,9 +0,0 @@ -# OryHydraCloudNativeOAuth20AndOpenIdConnectServer.SwaggerAcceptConsentRequest - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**body** | [**ConsentRequestAcceptance**](ConsentRequestAcceptance.md) | | -**id** | **String** | in: path | - - diff --git a/sdk/js/swagger/docs/SwaggerOAuthConsentRequestPayload.md b/sdk/js/swagger/docs/SwaggerOAuthConsentRequestPayload.md deleted file mode 100644 index e516e28e1e5..00000000000 --- a/sdk/js/swagger/docs/SwaggerOAuthConsentRequestPayload.md +++ /dev/null @@ -1,8 +0,0 @@ -# OryHydraCloudNativeOAuth20AndOpenIdConnectServer.SwaggerOAuthConsentRequestPayload - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**id** | **String** | The id of the OAuth 2.0 Consent Request. | - - diff --git a/sdk/js/swagger/docs/SwaggerRejectConsentRequest.md b/sdk/js/swagger/docs/SwaggerRejectConsentRequest.md deleted file mode 100644 index 21c58b6e2b6..00000000000 --- a/sdk/js/swagger/docs/SwaggerRejectConsentRequest.md +++ /dev/null @@ -1,9 +0,0 @@ -# OryHydraCloudNativeOAuth20AndOpenIdConnectServer.SwaggerRejectConsentRequest - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**body** | [**ConsentRequestRejection**](ConsentRequestRejection.md) | | -**id** | **String** | in: path | - - diff --git a/sdk/js/swagger/src/api/OAuth2Api.js b/sdk/js/swagger/src/api/OAuth2Api.js index 76a5bce422a..bbb76b8b017 100644 --- a/sdk/js/swagger/src/api/OAuth2Api.js +++ b/sdk/js/swagger/src/api/OAuth2Api.js @@ -20,15 +20,18 @@ define( [ 'ApiClient', - 'model/ConsentRequestAcceptance', - 'model/ConsentRequestRejection', + 'model/AcceptConsentRequest', + 'model/AcceptLoginRequest', + 'model/CompletedRequest', + 'model/ConsentRequest', 'model/FlushInactiveOAuth2TokensRequest', 'model/InlineResponse401', 'model/JsonWebKeySet', + 'model/LoginRequest', 'model/OAuth2Client', - 'model/OAuth2ConsentRequest', 'model/OAuth2TokenIntrospection', 'model/OauthTokenResponse', + 'model/RejectRequest', 'model/UserinfoResponse', 'model/WellKnown' ], @@ -38,15 +41,18 @@ // CommonJS-like environments that support module.exports, like Node. module.exports = factory( require('../ApiClient'), - require('../model/ConsentRequestAcceptance'), - require('../model/ConsentRequestRejection'), + require('../model/AcceptConsentRequest'), + require('../model/AcceptLoginRequest'), + require('../model/CompletedRequest'), + require('../model/ConsentRequest'), require('../model/FlushInactiveOAuth2TokensRequest'), require('../model/InlineResponse401'), require('../model/JsonWebKeySet'), + require('../model/LoginRequest'), require('../model/OAuth2Client'), - require('../model/OAuth2ConsentRequest'), require('../model/OAuth2TokenIntrospection'), require('../model/OauthTokenResponse'), + require('../model/RejectRequest'), require('../model/UserinfoResponse'), require('../model/WellKnown') ) @@ -58,34 +64,38 @@ root.OryHydraCloudNativeOAuth20AndOpenIdConnectServer.OAuth2Api = factory( root.OryHydraCloudNativeOAuth20AndOpenIdConnectServer.ApiClient, root.OryHydraCloudNativeOAuth20AndOpenIdConnectServer - .ConsentRequestAcceptance, - root.OryHydraCloudNativeOAuth20AndOpenIdConnectServer - .ConsentRequestRejection, + .AcceptConsentRequest, + root.OryHydraCloudNativeOAuth20AndOpenIdConnectServer.AcceptLoginRequest, + root.OryHydraCloudNativeOAuth20AndOpenIdConnectServer.CompletedRequest, + root.OryHydraCloudNativeOAuth20AndOpenIdConnectServer.ConsentRequest, root.OryHydraCloudNativeOAuth20AndOpenIdConnectServer .FlushInactiveOAuth2TokensRequest, root.OryHydraCloudNativeOAuth20AndOpenIdConnectServer.InlineResponse401, root.OryHydraCloudNativeOAuth20AndOpenIdConnectServer.JsonWebKeySet, + root.OryHydraCloudNativeOAuth20AndOpenIdConnectServer.LoginRequest, root.OryHydraCloudNativeOAuth20AndOpenIdConnectServer.OAuth2Client, - root.OryHydraCloudNativeOAuth20AndOpenIdConnectServer - .OAuth2ConsentRequest, root.OryHydraCloudNativeOAuth20AndOpenIdConnectServer .OAuth2TokenIntrospection, root.OryHydraCloudNativeOAuth20AndOpenIdConnectServer.OauthTokenResponse, + root.OryHydraCloudNativeOAuth20AndOpenIdConnectServer.RejectRequest, root.OryHydraCloudNativeOAuth20AndOpenIdConnectServer.UserinfoResponse, root.OryHydraCloudNativeOAuth20AndOpenIdConnectServer.WellKnown ) } })(this, function( ApiClient, - ConsentRequestAcceptance, - ConsentRequestRejection, + AcceptConsentRequest, + AcceptLoginRequest, + CompletedRequest, + ConsentRequest, FlushInactiveOAuth2TokensRequest, InlineResponse401, JsonWebKeySet, + LoginRequest, OAuth2Client, - OAuth2ConsentRequest, OAuth2TokenIntrospection, OauthTokenResponse, + RejectRequest, UserinfoResponse, WellKnown ) { @@ -108,39 +118,91 @@ this.apiClient = apiClient || ApiClient.instance /** - * Callback function to receive the result of the acceptOAuth2ConsentRequest operation. - * @callback module:api/OAuth2Api~acceptOAuth2ConsentRequestCallback + * Callback function to receive the result of the acceptConsentRequest operation. + * @callback module:api/OAuth2Api~acceptConsentRequestCallback * @param {String} error Error message, if any. - * @param data This operation does not return a value. + * @param {module:model/CompletedRequest} data The data returned by the service call. * @param {String} response The complete HTTP response. */ /** - * Accept a consent request - * Call this endpoint to accept a consent request. This usually happens when a user agrees to give access rights to an application. The consent request id is usually transmitted via the URL query `consent`. For example: `http://consent-app.mydomain.com/?consent=1234abcd` - * @param {String} id - * @param {module:model/ConsentRequestAcceptance} body - * @param {module:api/OAuth2Api~acceptOAuth2ConsentRequestCallback} callback The callback function, accepting three arguments: error, data, response + * Accept an consent request + * When an authorization code, hybrid, or implicit OAuth 2.0 Flow is initiated, ORY Hydra asks the login provider to authenticate the user and then tell ORY Hydra now about it. If the user authenticated, he/she must now be asked if the OAuth 2.0 Client which initiated the flow should be allowed to access the resources on the user's behalf. The consent provider which handles this request and is a web app implemented and hosted by you. It shows a user interface which asks the user to grant or deny the client access to the requested scope (\"Application my-dropbox-app wants write access to all your private files\"). The consent challenge is appended to the consent provider's URL to which the user's user-agent (browser) is redirected to. The consent provider uses that challenge to fetch information on the OAuth2 request and then tells ORY Hydra if the user accepted or rejected the request. This endpoint tells ORY Hydra that the user has authorized the OAuth 2.0 client to access resources on his/her behalf. The consent provider includes additional information, such as session data for access and ID tokens, and if the consent request should be used as basis for future requests. The response contains a redirect URL which the consent provider should redirect the user-agent to. + * @param {String} challenge + * @param {Object} opts Optional parameters + * @param {module:model/AcceptConsentRequest} opts.body + * @param {module:api/OAuth2Api~acceptConsentRequestCallback} callback The callback function, accepting three arguments: error, data, response + * data is of type: {@link module:model/CompletedRequest} */ - this.acceptOAuth2ConsentRequest = function(id, body, callback) { - var postBody = body + this.acceptConsentRequest = function(challenge, opts, callback) { + opts = opts || {} + var postBody = opts['body'] - // verify the required parameter 'id' is set - if (id === undefined || id === null) { + // verify the required parameter 'challenge' is set + if (challenge === undefined || challenge === null) { throw new Error( - "Missing the required parameter 'id' when calling acceptOAuth2ConsentRequest" + "Missing the required parameter 'challenge' when calling acceptConsentRequest" ) } - // verify the required parameter 'body' is set - if (body === undefined || body === null) { + var pathParams = { + challenge: challenge + } + var queryParams = {} + var headerParams = {} + var formParams = {} + + var authNames = [] + var contentTypes = ['application/json'] + var accepts = ['application/json'] + var returnType = CompletedRequest + + return this.apiClient.callApi( + '/oauth2/auth/requests/consent/{challenge}/accept', + 'PUT', + pathParams, + queryParams, + headerParams, + formParams, + postBody, + authNames, + contentTypes, + accepts, + returnType, + callback + ) + } + + /** + * Callback function to receive the result of the acceptLoginRequest operation. + * @callback module:api/OAuth2Api~acceptLoginRequestCallback + * @param {String} error Error message, if any. + * @param {module:model/CompletedRequest} data The data returned by the service call. + * @param {String} response The complete HTTP response. + */ + + /** + * Accept an login request + * When an authorization code, hybrid, or implicit OAuth 2.0 Flow is initiated, ORY Hydra asks the login provider (sometimes called \"identity provider\") to authenticate the user and then tell ORY Hydra now about it. The login provider is an web-app you write and host, and it must be able to authenticate (\"show the user a login screen\") a user (in OAuth2 the proper name for user is \"resource owner\"). The authentication challenge is appended to the login provider URL to which the user's user-agent (browser) is redirected to. The login provider uses that challenge to fetch information on the OAuth2 request and then accept or reject the requested authentication process. This endpoint tells ORY Hydra that the user has successfully authenticated and includes additional information such as the user's ID and if ORY Hydra should remember the user's user agent for future authentication attempts by setting a cookie. The response contains a redirect URL which the login provider should redirect the user-agent to. + * @param {String} challenge + * @param {Object} opts Optional parameters + * @param {module:model/AcceptLoginRequest} opts.body + * @param {module:api/OAuth2Api~acceptLoginRequestCallback} callback The callback function, accepting three arguments: error, data, response + * data is of type: {@link module:model/CompletedRequest} + */ + this.acceptLoginRequest = function(challenge, opts, callback) { + opts = opts || {} + var postBody = opts['body'] + + // verify the required parameter 'challenge' is set + if (challenge === undefined || challenge === null) { throw new Error( - "Missing the required parameter 'body' when calling acceptOAuth2ConsentRequest" + "Missing the required parameter 'challenge' when calling acceptLoginRequest" ) } var pathParams = { - id: id + challenge: challenge } var queryParams = {} var headerParams = {} @@ -149,11 +211,11 @@ var authNames = [] var contentTypes = ['application/json'] var accepts = ['application/json'] - var returnType = null + var returnType = CompletedRequest return this.apiClient.callApi( - '/oauth2/consent/requests/{id}/accept', - 'PATCH', + '/oauth2/auth/requests/login/{challenge}/accept', + 'PUT', pathParams, queryParams, headerParams, @@ -316,32 +378,32 @@ } /** - * Callback function to receive the result of the getOAuth2Client operation. - * @callback module:api/OAuth2Api~getOAuth2ClientCallback + * Callback function to receive the result of the getConsentRequest operation. + * @callback module:api/OAuth2Api~getConsentRequestCallback * @param {String} error Error message, if any. - * @param {module:model/OAuth2Client} data The data returned by the service call. + * @param {module:model/ConsentRequest} data The data returned by the service call. * @param {String} response The complete HTTP response. */ /** - * Get an OAuth 2.0 Client. - * Get an OAUth 2.0 client by its ID. This endpoint never returns passwords. OAuth 2.0 clients are used to perform OAuth 2.0 and OpenID Connect flows. Usually, OAuth 2.0 clients are generated for applications which want to consume your OAuth 2.0 or OpenID Connect capabilities. To manage ORY Hydra, you will need an OAuth 2.0 Client as well. Make sure that this endpoint is well protected and only callable by first-party components. - * @param {String} id The id of the OAuth 2.0 Client. - * @param {module:api/OAuth2Api~getOAuth2ClientCallback} callback The callback function, accepting three arguments: error, data, response - * data is of type: {@link module:model/OAuth2Client} + * Get consent request information + * When an authorization code, hybrid, or implicit OAuth 2.0 Flow is initiated, ORY Hydra asks the login provider to authenticate the user and then tell ORY Hydra now about it. If the user authenticated, he/she must now be asked if the OAuth 2.0 Client which initiated the flow should be allowed to access the resources on the user's behalf. The consent provider which handles this request and is a web app implemented and hosted by you. It shows a user interface which asks the user to grant or deny the client access to the requested scope (\"Application my-dropbox-app wants write access to all your private files\"). The consent challenge is appended to the consent provider's URL to which the user's user-agent (browser) is redirected to. The consent provider uses that challenge to fetch information on the OAuth2 request and then tells ORY Hydra if the user accepted or rejected the request. + * @param {String} challenge + * @param {module:api/OAuth2Api~getConsentRequestCallback} callback The callback function, accepting three arguments: error, data, response + * data is of type: {@link module:model/ConsentRequest} */ - this.getOAuth2Client = function(id, callback) { + this.getConsentRequest = function(challenge, callback) { var postBody = null - // verify the required parameter 'id' is set - if (id === undefined || id === null) { + // verify the required parameter 'challenge' is set + if (challenge === undefined || challenge === null) { throw new Error( - "Missing the required parameter 'id' when calling getOAuth2Client" + "Missing the required parameter 'challenge' when calling getConsentRequest" ) } var pathParams = { - id: id + challenge: challenge } var queryParams = {} var headerParams = {} @@ -350,10 +412,10 @@ var authNames = [] var contentTypes = ['application/json'] var accepts = ['application/json'] - var returnType = OAuth2Client + var returnType = ConsentRequest return this.apiClient.callApi( - '/clients/{id}', + '/oauth2/auth/requests/consent/{challenge}', 'GET', pathParams, queryParams, @@ -369,27 +431,80 @@ } /** - * Callback function to receive the result of the getOAuth2ConsentRequest operation. - * @callback module:api/OAuth2Api~getOAuth2ConsentRequestCallback + * Callback function to receive the result of the getLoginRequest operation. + * @callback module:api/OAuth2Api~getLoginRequestCallback * @param {String} error Error message, if any. - * @param {module:model/OAuth2ConsentRequest} data The data returned by the service call. + * @param {module:model/LoginRequest} data The data returned by the service call. * @param {String} response The complete HTTP response. */ /** - * Receive consent request information - * Call this endpoint to receive information on consent requests. The consent request id is usually transmitted via the URL query `consent`. For example: `http://consent-app.mydomain.com/?consent=1234abcd` - * @param {String} id The id of the OAuth 2.0 Consent Request. - * @param {module:api/OAuth2Api~getOAuth2ConsentRequestCallback} callback The callback function, accepting three arguments: error, data, response - * data is of type: {@link module:model/OAuth2ConsentRequest} + * Get an login request + * When an authorization code, hybrid, or implicit OAuth 2.0 Flow is initiated, ORY Hydra asks the login provider (sometimes called \"identity provider\") to authenticate the user and then tell ORY Hydra now about it. The login provider is an web-app you write and host, and it must be able to authenticate (\"show the user a login screen\") a user (in OAuth2 the proper name for user is \"resource owner\"). The authentication challenge is appended to the login provider URL to which the user's user-agent (browser) is redirected to. The login provider uses that challenge to fetch information on the OAuth2 request and then accept or reject the requested authentication process. + * @param {String} challenge + * @param {module:api/OAuth2Api~getLoginRequestCallback} callback The callback function, accepting three arguments: error, data, response + * data is of type: {@link module:model/LoginRequest} */ - this.getOAuth2ConsentRequest = function(id, callback) { + this.getLoginRequest = function(challenge, callback) { + var postBody = null + + // verify the required parameter 'challenge' is set + if (challenge === undefined || challenge === null) { + throw new Error( + "Missing the required parameter 'challenge' when calling getLoginRequest" + ) + } + + var pathParams = { + challenge: challenge + } + var queryParams = {} + var headerParams = {} + var formParams = {} + + var authNames = [] + var contentTypes = ['application/json'] + var accepts = ['application/json'] + var returnType = LoginRequest + + return this.apiClient.callApi( + '/oauth2/auth/requests/login/{challenge}', + 'GET', + pathParams, + queryParams, + headerParams, + formParams, + postBody, + authNames, + contentTypes, + accepts, + returnType, + callback + ) + } + + /** + * Callback function to receive the result of the getOAuth2Client operation. + * @callback module:api/OAuth2Api~getOAuth2ClientCallback + * @param {String} error Error message, if any. + * @param {module:model/OAuth2Client} data The data returned by the service call. + * @param {String} response The complete HTTP response. + */ + + /** + * Get an OAuth 2.0 Client. + * Get an OAUth 2.0 client by its ID. This endpoint never returns passwords. OAuth 2.0 clients are used to perform OAuth 2.0 and OpenID Connect flows. Usually, OAuth 2.0 clients are generated for applications which want to consume your OAuth 2.0 or OpenID Connect capabilities. To manage ORY Hydra, you will need an OAuth 2.0 Client as well. Make sure that this endpoint is well protected and only callable by first-party components. + * @param {String} id The id of the OAuth 2.0 Client. + * @param {module:api/OAuth2Api~getOAuth2ClientCallback} callback The callback function, accepting three arguments: error, data, response + * data is of type: {@link module:model/OAuth2Client} + */ + this.getOAuth2Client = function(id, callback) { var postBody = null // verify the required parameter 'id' is set if (id === undefined || id === null) { throw new Error( - "Missing the required parameter 'id' when calling getOAuth2ConsentRequest" + "Missing the required parameter 'id' when calling getOAuth2Client" ) } @@ -403,10 +518,10 @@ var authNames = [] var contentTypes = ['application/json'] var accepts = ['application/json'] - var returnType = OAuth2ConsentRequest + var returnType = OAuth2Client return this.apiClient.callApi( - '/oauth2/consent/requests/{id}', + '/clients/{id}', 'GET', pathParams, queryParams, @@ -660,39 +775,91 @@ } /** - * Callback function to receive the result of the rejectOAuth2ConsentRequest operation. - * @callback module:api/OAuth2Api~rejectOAuth2ConsentRequestCallback + * Callback function to receive the result of the rejectConsentRequest operation. + * @callback module:api/OAuth2Api~rejectConsentRequestCallback * @param {String} error Error message, if any. - * @param data This operation does not return a value. + * @param {module:model/CompletedRequest} data The data returned by the service call. * @param {String} response The complete HTTP response. */ /** - * Reject a consent request - * Call this endpoint to reject a consent request. This usually happens when a user denies access rights to an application. The consent request id is usually transmitted via the URL query `consent`. For example: `http://consent-app.mydomain.com/?consent=1234abcd` - * @param {String} id - * @param {module:model/ConsentRequestRejection} body - * @param {module:api/OAuth2Api~rejectOAuth2ConsentRequestCallback} callback The callback function, accepting three arguments: error, data, response + * Reject an consent request + * When an authorization code, hybrid, or implicit OAuth 2.0 Flow is initiated, ORY Hydra asks the login provider to authenticate the user and then tell ORY Hydra now about it. If the user authenticated, he/she must now be asked if the OAuth 2.0 Client which initiated the flow should be allowed to access the resources on the user's behalf. The consent provider which handles this request and is a web app implemented and hosted by you. It shows a user interface which asks the user to grant or deny the client access to the requested scope (\"Application my-dropbox-app wants write access to all your private files\"). The consent challenge is appended to the consent provider's URL to which the user's user-agent (browser) is redirected to. The consent provider uses that challenge to fetch information on the OAuth2 request and then tells ORY Hydra if the user accepted or rejected the request. This endpoint tells ORY Hydra that the user has not authorized the OAuth 2.0 client to access resources on his/her behalf. The consent provider must include a reason why the consent was not granted. The response contains a redirect URL which the consent provider should redirect the user-agent to. + * @param {String} challenge + * @param {Object} opts Optional parameters + * @param {module:model/RejectRequest} opts.body + * @param {module:api/OAuth2Api~rejectConsentRequestCallback} callback The callback function, accepting three arguments: error, data, response + * data is of type: {@link module:model/CompletedRequest} */ - this.rejectOAuth2ConsentRequest = function(id, body, callback) { - var postBody = body + this.rejectConsentRequest = function(challenge, opts, callback) { + opts = opts || {} + var postBody = opts['body'] - // verify the required parameter 'id' is set - if (id === undefined || id === null) { + // verify the required parameter 'challenge' is set + if (challenge === undefined || challenge === null) { throw new Error( - "Missing the required parameter 'id' when calling rejectOAuth2ConsentRequest" + "Missing the required parameter 'challenge' when calling rejectConsentRequest" ) } - // verify the required parameter 'body' is set - if (body === undefined || body === null) { + var pathParams = { + challenge: challenge + } + var queryParams = {} + var headerParams = {} + var formParams = {} + + var authNames = [] + var contentTypes = ['application/json'] + var accepts = ['application/json'] + var returnType = CompletedRequest + + return this.apiClient.callApi( + '/oauth2/auth/requests/consent/{challenge}/reject', + 'PUT', + pathParams, + queryParams, + headerParams, + formParams, + postBody, + authNames, + contentTypes, + accepts, + returnType, + callback + ) + } + + /** + * Callback function to receive the result of the rejectLoginRequest operation. + * @callback module:api/OAuth2Api~rejectLoginRequestCallback + * @param {String} error Error message, if any. + * @param {module:model/CompletedRequest} data The data returned by the service call. + * @param {String} response The complete HTTP response. + */ + + /** + * Reject an logout request + * When an authorization code, hybrid, or implicit OAuth 2.0 Flow is initiated, ORY Hydra asks the login provider (sometimes called \"identity provider\") to authenticate the user and then tell ORY Hydra now about it. The login provider is an web-app you write and host, and it must be able to authenticate (\"show the user a login screen\") a user (in OAuth2 the proper name for user is \"resource owner\"). The authentication challenge is appended to the login provider URL to which the user's user-agent (browser) is redirected to. The login provider uses that challenge to fetch information on the OAuth2 request and then accept or reject the requested authentication process. This endpoint tells ORY Hydra that the user has not authenticated and includes a reason why the authentication was be denied. The response contains a redirect URL which the login provider should redirect the user-agent to. + * @param {String} challenge + * @param {Object} opts Optional parameters + * @param {module:model/RejectRequest} opts.body + * @param {module:api/OAuth2Api~rejectLoginRequestCallback} callback The callback function, accepting three arguments: error, data, response + * data is of type: {@link module:model/CompletedRequest} + */ + this.rejectLoginRequest = function(challenge, opts, callback) { + opts = opts || {} + var postBody = opts['body'] + + // verify the required parameter 'challenge' is set + if (challenge === undefined || challenge === null) { throw new Error( - "Missing the required parameter 'body' when calling rejectOAuth2ConsentRequest" + "Missing the required parameter 'challenge' when calling rejectLoginRequest" ) } var pathParams = { - id: id + challenge: challenge } var queryParams = {} var headerParams = {} @@ -701,11 +868,11 @@ var authNames = [] var contentTypes = ['application/json'] var accepts = ['application/json'] - var returnType = null + var returnType = CompletedRequest return this.apiClient.callApi( - '/oauth2/consent/requests/{id}/reject', - 'PATCH', + '/oauth2/auth/requests/login/{challenge}/reject', + 'PUT', pathParams, queryParams, headerParams, diff --git a/sdk/js/swagger/src/index.js b/sdk/js/swagger/src/index.js index 87da8d40dfc..9e3389f6304 100644 --- a/sdk/js/swagger/src/index.js +++ b/sdk/js/swagger/src/index.js @@ -20,10 +20,12 @@ define( [ 'ApiClient', + 'model/AcceptConsentRequest', + 'model/AcceptLoginRequest', + 'model/AuthenticationSession', + 'model/CompletedRequest', 'model/ConsentRequest', - 'model/ConsentRequestAcceptance', - 'model/ConsentRequestManager', - 'model/ConsentRequestRejection', + 'model/ConsentRequestSession', 'model/FlushInactiveOAuth2TokensRequest', 'model/Handler', 'model/InlineResponse200', @@ -33,22 +35,21 @@ 'model/JsonWebKeySet', 'model/JsonWebKeySetGeneratorRequest', 'model/KeyGenerator', + 'model/LoginRequest', 'model/Manager', 'model/OAuth2Client', - 'model/OAuth2ConsentRequest', 'model/OAuth2TokenIntrospection', 'model/OauthTokenResponse', + 'model/OpenIDConnectContext', 'model/RawMessage', - 'model/SwaggerAcceptConsentRequest', + 'model/RejectRequest', 'model/SwaggerFlushInactiveAccessTokens', 'model/SwaggerJsonWebKeyQuery', 'model/SwaggerJwkCreateSet', 'model/SwaggerJwkSetQuery', 'model/SwaggerJwkUpdateSet', 'model/SwaggerJwkUpdateSetKey', - 'model/SwaggerOAuthConsentRequestPayload', 'model/SwaggerOAuthIntrospectionRequest', - 'model/SwaggerRejectConsentRequest', 'model/SwaggerRevokeOAuth2TokenParameters', 'model/UserinfoResponse', 'model/WellKnown', @@ -63,10 +64,12 @@ // CommonJS-like environments that support module.exports, like Node. module.exports = factory( require('./ApiClient'), + require('./model/AcceptConsentRequest'), + require('./model/AcceptLoginRequest'), + require('./model/AuthenticationSession'), + require('./model/CompletedRequest'), require('./model/ConsentRequest'), - require('./model/ConsentRequestAcceptance'), - require('./model/ConsentRequestManager'), - require('./model/ConsentRequestRejection'), + require('./model/ConsentRequestSession'), require('./model/FlushInactiveOAuth2TokensRequest'), require('./model/Handler'), require('./model/InlineResponse200'), @@ -76,22 +79,21 @@ require('./model/JsonWebKeySet'), require('./model/JsonWebKeySetGeneratorRequest'), require('./model/KeyGenerator'), + require('./model/LoginRequest'), require('./model/Manager'), require('./model/OAuth2Client'), - require('./model/OAuth2ConsentRequest'), require('./model/OAuth2TokenIntrospection'), require('./model/OauthTokenResponse'), + require('./model/OpenIDConnectContext'), require('./model/RawMessage'), - require('./model/SwaggerAcceptConsentRequest'), + require('./model/RejectRequest'), require('./model/SwaggerFlushInactiveAccessTokens'), require('./model/SwaggerJsonWebKeyQuery'), require('./model/SwaggerJwkCreateSet'), require('./model/SwaggerJwkSetQuery'), require('./model/SwaggerJwkUpdateSet'), require('./model/SwaggerJwkUpdateSetKey'), - require('./model/SwaggerOAuthConsentRequestPayload'), require('./model/SwaggerOAuthIntrospectionRequest'), - require('./model/SwaggerRejectConsentRequest'), require('./model/SwaggerRevokeOAuth2TokenParameters'), require('./model/UserinfoResponse'), require('./model/WellKnown'), @@ -103,10 +105,12 @@ } })(function( ApiClient, + AcceptConsentRequest, + AcceptLoginRequest, + AuthenticationSession, + CompletedRequest, ConsentRequest, - ConsentRequestAcceptance, - ConsentRequestManager, - ConsentRequestRejection, + ConsentRequestSession, FlushInactiveOAuth2TokensRequest, Handler, InlineResponse200, @@ -116,22 +120,21 @@ JsonWebKeySet, JsonWebKeySetGeneratorRequest, KeyGenerator, + LoginRequest, Manager, OAuth2Client, - OAuth2ConsentRequest, OAuth2TokenIntrospection, OauthTokenResponse, + OpenIDConnectContext, RawMessage, - SwaggerAcceptConsentRequest, + RejectRequest, SwaggerFlushInactiveAccessTokens, SwaggerJsonWebKeyQuery, SwaggerJwkCreateSet, SwaggerJwkSetQuery, SwaggerJwkUpdateSet, SwaggerJwkUpdateSetKey, - SwaggerOAuthConsentRequestPayload, SwaggerOAuthIntrospectionRequest, - SwaggerRejectConsentRequest, SwaggerRevokeOAuth2TokenParameters, UserinfoResponse, WellKnown, @@ -180,25 +183,35 @@ */ ApiClient: ApiClient, /** - * The ConsentRequest model constructor. - * @property {module:model/ConsentRequest} + * The AcceptConsentRequest model constructor. + * @property {module:model/AcceptConsentRequest} */ - ConsentRequest: ConsentRequest, + AcceptConsentRequest: AcceptConsentRequest, + /** + * The AcceptLoginRequest model constructor. + * @property {module:model/AcceptLoginRequest} + */ + AcceptLoginRequest: AcceptLoginRequest, /** - * The ConsentRequestAcceptance model constructor. - * @property {module:model/ConsentRequestAcceptance} + * The AuthenticationSession model constructor. + * @property {module:model/AuthenticationSession} */ - ConsentRequestAcceptance: ConsentRequestAcceptance, + AuthenticationSession: AuthenticationSession, /** - * The ConsentRequestManager model constructor. - * @property {module:model/ConsentRequestManager} + * The CompletedRequest model constructor. + * @property {module:model/CompletedRequest} */ - ConsentRequestManager: ConsentRequestManager, + CompletedRequest: CompletedRequest, + /** + * The ConsentRequest model constructor. + * @property {module:model/ConsentRequest} + */ + ConsentRequest: ConsentRequest, /** - * The ConsentRequestRejection model constructor. - * @property {module:model/ConsentRequestRejection} + * The ConsentRequestSession model constructor. + * @property {module:model/ConsentRequestSession} */ - ConsentRequestRejection: ConsentRequestRejection, + ConsentRequestSession: ConsentRequestSession, /** * The FlushInactiveOAuth2TokensRequest model constructor. * @property {module:model/FlushInactiveOAuth2TokensRequest} @@ -244,6 +257,11 @@ * @property {module:model/KeyGenerator} */ KeyGenerator: KeyGenerator, + /** + * The LoginRequest model constructor. + * @property {module:model/LoginRequest} + */ + LoginRequest: LoginRequest, /** * The Manager model constructor. * @property {module:model/Manager} @@ -254,11 +272,6 @@ * @property {module:model/OAuth2Client} */ OAuth2Client: OAuth2Client, - /** - * The OAuth2ConsentRequest model constructor. - * @property {module:model/OAuth2ConsentRequest} - */ - OAuth2ConsentRequest: OAuth2ConsentRequest, /** * The OAuth2TokenIntrospection model constructor. * @property {module:model/OAuth2TokenIntrospection} @@ -269,16 +282,21 @@ * @property {module:model/OauthTokenResponse} */ OauthTokenResponse: OauthTokenResponse, + /** + * The OpenIDConnectContext model constructor. + * @property {module:model/OpenIDConnectContext} + */ + OpenIDConnectContext: OpenIDConnectContext, /** * The RawMessage model constructor. * @property {module:model/RawMessage} */ RawMessage: RawMessage, /** - * The SwaggerAcceptConsentRequest model constructor. - * @property {module:model/SwaggerAcceptConsentRequest} + * The RejectRequest model constructor. + * @property {module:model/RejectRequest} */ - SwaggerAcceptConsentRequest: SwaggerAcceptConsentRequest, + RejectRequest: RejectRequest, /** * The SwaggerFlushInactiveAccessTokens model constructor. * @property {module:model/SwaggerFlushInactiveAccessTokens} @@ -309,21 +327,11 @@ * @property {module:model/SwaggerJwkUpdateSetKey} */ SwaggerJwkUpdateSetKey: SwaggerJwkUpdateSetKey, - /** - * The SwaggerOAuthConsentRequestPayload model constructor. - * @property {module:model/SwaggerOAuthConsentRequestPayload} - */ - SwaggerOAuthConsentRequestPayload: SwaggerOAuthConsentRequestPayload, /** * The SwaggerOAuthIntrospectionRequest model constructor. * @property {module:model/SwaggerOAuthIntrospectionRequest} */ SwaggerOAuthIntrospectionRequest: SwaggerOAuthIntrospectionRequest, - /** - * The SwaggerRejectConsentRequest model constructor. - * @property {module:model/SwaggerRejectConsentRequest} - */ - SwaggerRejectConsentRequest: SwaggerRejectConsentRequest, /** * The SwaggerRevokeOAuth2TokenParameters model constructor. * @property {module:model/SwaggerRevokeOAuth2TokenParameters} diff --git a/sdk/js/swagger/src/model/AcceptConsentRequest.js b/sdk/js/swagger/src/model/AcceptConsentRequest.js new file mode 100644 index 00000000000..f7dbc79d29b --- /dev/null +++ b/sdk/js/swagger/src/model/AcceptConsentRequest.js @@ -0,0 +1,111 @@ +/** + * ORY Hydra - Cloud Native OAuth 2.0 and OpenID Connect Server + * Welcome to the ORY Hydra HTTP API documentation. You will find documentation for all HTTP APIs here. Keep in mind that this document reflects the latest branch, always. Support for versioned documentation is coming in the future. + * + * OpenAPI spec version: Latest + * Contact: hi@ory.am + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * + * Swagger Codegen version: 2.2.3 + * + * Do not edit the class manually. + * + */ + +;(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(['ApiClient', 'model/ConsentRequestSession'], factory) + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + module.exports = factory( + require('../ApiClient'), + require('./ConsentRequestSession') + ) + } else { + // Browser globals (root is window) + if (!root.OryHydraCloudNativeOAuth20AndOpenIdConnectServer) { + root.OryHydraCloudNativeOAuth20AndOpenIdConnectServer = {} + } + root.OryHydraCloudNativeOAuth20AndOpenIdConnectServer.AcceptConsentRequest = factory( + root.OryHydraCloudNativeOAuth20AndOpenIdConnectServer.ApiClient, + root.OryHydraCloudNativeOAuth20AndOpenIdConnectServer + .ConsentRequestSession + ) + } +})(this, function(ApiClient, ConsentRequestSession) { + 'use strict' + + /** + * The AcceptConsentRequest model module. + * @module model/AcceptConsentRequest + * @version Latest + */ + + /** + * Constructs a new AcceptConsentRequest. + * @alias module:model/AcceptConsentRequest + * @class + */ + var exports = function() { + var _this = this + } + + /** + * Constructs a AcceptConsentRequest from a plain JavaScript object, optionally creating a new instance. + * Copies all relevant properties from data to obj if supplied or a new instance if not. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @param {module:model/AcceptConsentRequest} obj Optional instance to populate. + * @return {module:model/AcceptConsentRequest} The populated AcceptConsentRequest instance. + */ + exports.constructFromObject = function(data, obj) { + if (data) { + obj = obj || new exports() + + if (data.hasOwnProperty('grant_scope')) { + obj['grant_scope'] = ApiClient.convertToType(data['grant_scope'], [ + 'String' + ]) + } + if (data.hasOwnProperty('remember')) { + obj['remember'] = ApiClient.convertToType(data['remember'], 'Boolean') + } + if (data.hasOwnProperty('remember_for')) { + obj['remember_for'] = ApiClient.convertToType( + data['remember_for'], + 'Number' + ) + } + if (data.hasOwnProperty('session')) { + obj['session'] = ConsentRequestSession.constructFromObject( + data['session'] + ) + } + } + return obj + } + + /** + * GrantScope sets the scope the user authorized the client to use. Should be a subset of `requested_scope` + * @member {Array.} grant_scope + */ + exports.prototype['grant_scope'] = undefined + /** + * Remember, if set to true, tells ORY Hydra to remember this consent authorization and reuse it if the same client asks the same user for the same, or a subset of, scope. + * @member {Boolean} remember + */ + exports.prototype['remember'] = undefined + /** + * RememberFor sets how long the consent authorization should be remembered for in seconds. If set to `0`, the authorization will be remembered indefinitely. + * @member {Number} remember_for + */ + exports.prototype['remember_for'] = undefined + /** + * @member {module:model/ConsentRequestSession} session + */ + exports.prototype['session'] = undefined + + return exports +}) diff --git a/sdk/js/swagger/src/model/ConsentRequestAcceptance.js b/sdk/js/swagger/src/model/AcceptLoginRequest.js similarity index 50% rename from sdk/js/swagger/src/model/ConsentRequestAcceptance.js rename to sdk/js/swagger/src/model/AcceptLoginRequest.js index 36a9fe61a15..f9b3c510905 100644 --- a/sdk/js/swagger/src/model/ConsentRequestAcceptance.js +++ b/sdk/js/swagger/src/model/AcceptLoginRequest.js @@ -26,7 +26,7 @@ if (!root.OryHydraCloudNativeOAuth20AndOpenIdConnectServer) { root.OryHydraCloudNativeOAuth20AndOpenIdConnectServer = {} } - root.OryHydraCloudNativeOAuth20AndOpenIdConnectServer.ConsentRequestAcceptance = factory( + root.OryHydraCloudNativeOAuth20AndOpenIdConnectServer.AcceptLoginRequest = factory( root.OryHydraCloudNativeOAuth20AndOpenIdConnectServer.ApiClient ) } @@ -34,14 +34,14 @@ 'use strict' /** - * The ConsentRequestAcceptance model module. - * @module model/ConsentRequestAcceptance + * The AcceptLoginRequest model module. + * @module model/AcceptLoginRequest * @version Latest */ /** - * Constructs a new ConsentRequestAcceptance. - * @alias module:model/ConsentRequestAcceptance + * Constructs a new AcceptLoginRequest. + * @alias module:model/AcceptLoginRequest * @class */ var exports = function() { @@ -49,31 +49,27 @@ } /** - * Constructs a ConsentRequestAcceptance from a plain JavaScript object, optionally creating a new instance. + * Constructs a AcceptLoginRequest from a plain JavaScript object, optionally creating a new instance. * Copies all relevant properties from data to obj if supplied or a new instance if not. * @param {Object} data The plain JavaScript object bearing properties of interest. - * @param {module:model/ConsentRequestAcceptance} obj Optional instance to populate. - * @return {module:model/ConsentRequestAcceptance} The populated ConsentRequestAcceptance instance. + * @param {module:model/AcceptLoginRequest} obj Optional instance to populate. + * @return {module:model/AcceptLoginRequest} The populated AcceptLoginRequest instance. */ exports.constructFromObject = function(data, obj) { if (data) { obj = obj || new exports() - if (data.hasOwnProperty('accessTokenExtra')) { - obj['accessTokenExtra'] = ApiClient.convertToType( - data['accessTokenExtra'], - { String: Object } - ) + if (data.hasOwnProperty('acr')) { + obj['acr'] = ApiClient.convertToType(data['acr'], 'String') } - if (data.hasOwnProperty('grantScopes')) { - obj['grantScopes'] = ApiClient.convertToType(data['grantScopes'], [ - 'String' - ]) + if (data.hasOwnProperty('remember')) { + obj['remember'] = ApiClient.convertToType(data['remember'], 'Boolean') } - if (data.hasOwnProperty('idTokenExtra')) { - obj['idTokenExtra'] = ApiClient.convertToType(data['idTokenExtra'], { - String: Object - }) + if (data.hasOwnProperty('remember_for')) { + obj['remember_for'] = ApiClient.convertToType( + data['remember_for'], + 'Number' + ) } if (data.hasOwnProperty('subject')) { obj['subject'] = ApiClient.convertToType(data['subject'], 'String') @@ -83,22 +79,22 @@ } /** - * AccessTokenExtra represents arbitrary data that will be added to the access token and that will be returned on introspection and warden requests. - * @member {Object.} accessTokenExtra + * ACR sets the Authentication AuthorizationContext Class Reference value for this authentication session. You can use it to express that, for example, a user authenticated using two factor authentication. + * @member {String} acr */ - exports.prototype['accessTokenExtra'] = undefined + exports.prototype['acr'] = undefined /** - * A list of scopes that the user agreed to grant. It should be a subset of requestedScopes from the consent request. - * @member {Array.} grantScopes + * Remember, if set to true, tells ORY Hydra to remember this user by telling the user agent (browser) to store a cookie with authentication data. If the same user performs another OAuth 2.0 Authorization Request, he/she will not be asked to log in again. + * @member {Boolean} remember */ - exports.prototype['grantScopes'] = undefined + exports.prototype['remember'] = undefined /** - * IDTokenExtra represents arbitrary data that will be added to the ID token. The ID token will only be issued if the user agrees to it and if the client requested an ID token. - * @member {Object.} idTokenExtra + * RememberFor sets how long the authentication should be remembered for in seconds. If set to `0`, the authorization will be remembered indefinitely. + * @member {Number} remember_for */ - exports.prototype['idTokenExtra'] = undefined + exports.prototype['remember_for'] = undefined /** - * Subject represents a unique identifier of the user (or service, or legal entity, ...) that accepted the OAuth2 request. + * Subject is the user ID of the end-user that authenticated. * @member {String} subject */ exports.prototype['subject'] = undefined diff --git a/sdk/js/swagger/src/model/ConsentRequestManager.js b/sdk/js/swagger/src/model/AuthenticationSession.js similarity index 59% rename from sdk/js/swagger/src/model/ConsentRequestManager.js rename to sdk/js/swagger/src/model/AuthenticationSession.js index fd804772b51..24dcef2b69e 100644 --- a/sdk/js/swagger/src/model/ConsentRequestManager.js +++ b/sdk/js/swagger/src/model/AuthenticationSession.js @@ -26,7 +26,7 @@ if (!root.OryHydraCloudNativeOAuth20AndOpenIdConnectServer) { root.OryHydraCloudNativeOAuth20AndOpenIdConnectServer = {} } - root.OryHydraCloudNativeOAuth20AndOpenIdConnectServer.ConsentRequestManager = factory( + root.OryHydraCloudNativeOAuth20AndOpenIdConnectServer.AuthenticationSession = factory( root.OryHydraCloudNativeOAuth20AndOpenIdConnectServer.ApiClient ) } @@ -34,14 +34,14 @@ 'use strict' /** - * The ConsentRequestManager model module. - * @module model/ConsentRequestManager + * The AuthenticationSession model module. + * @module model/AuthenticationSession * @version Latest */ /** - * Constructs a new ConsentRequestManager. - * @alias module:model/ConsentRequestManager + * Constructs a new AuthenticationSession. + * @alias module:model/AuthenticationSession * @class */ var exports = function() { @@ -49,18 +49,44 @@ } /** - * Constructs a ConsentRequestManager from a plain JavaScript object, optionally creating a new instance. + * Constructs a AuthenticationSession from a plain JavaScript object, optionally creating a new instance. * Copies all relevant properties from data to obj if supplied or a new instance if not. * @param {Object} data The plain JavaScript object bearing properties of interest. - * @param {module:model/ConsentRequestManager} obj Optional instance to populate. - * @return {module:model/ConsentRequestManager} The populated ConsentRequestManager instance. + * @param {module:model/AuthenticationSession} obj Optional instance to populate. + * @return {module:model/AuthenticationSession} The populated AuthenticationSession instance. */ exports.constructFromObject = function(data, obj) { if (data) { obj = obj || new exports() + + if (data.hasOwnProperty('AuthenticatedAt')) { + obj['AuthenticatedAt'] = ApiClient.convertToType( + data['AuthenticatedAt'], + 'Date' + ) + } + if (data.hasOwnProperty('ID')) { + obj['ID'] = ApiClient.convertToType(data['ID'], 'String') + } + if (data.hasOwnProperty('Subject')) { + obj['Subject'] = ApiClient.convertToType(data['Subject'], 'String') + } } return obj } + /** + * @member {Date} AuthenticatedAt + */ + exports.prototype['AuthenticatedAt'] = undefined + /** + * @member {String} ID + */ + exports.prototype['ID'] = undefined + /** + * @member {String} Subject + */ + exports.prototype['Subject'] = undefined + return exports }) diff --git a/sdk/js/swagger/src/model/ConsentRequestRejection.js b/sdk/js/swagger/src/model/CompletedRequest.js similarity index 65% rename from sdk/js/swagger/src/model/ConsentRequestRejection.js rename to sdk/js/swagger/src/model/CompletedRequest.js index 2ee1ec52df2..c94b3e1e80d 100644 --- a/sdk/js/swagger/src/model/ConsentRequestRejection.js +++ b/sdk/js/swagger/src/model/CompletedRequest.js @@ -26,7 +26,7 @@ if (!root.OryHydraCloudNativeOAuth20AndOpenIdConnectServer) { root.OryHydraCloudNativeOAuth20AndOpenIdConnectServer = {} } - root.OryHydraCloudNativeOAuth20AndOpenIdConnectServer.ConsentRequestRejection = factory( + root.OryHydraCloudNativeOAuth20AndOpenIdConnectServer.CompletedRequest = factory( root.OryHydraCloudNativeOAuth20AndOpenIdConnectServer.ApiClient ) } @@ -34,14 +34,14 @@ 'use strict' /** - * The ConsentRequestRejection model module. - * @module model/ConsentRequestRejection + * The CompletedRequest model module. + * @module model/CompletedRequest * @version Latest */ /** - * Constructs a new ConsentRequestRejection. - * @alias module:model/ConsentRequestRejection + * Constructs a new CompletedRequest. + * @alias module:model/CompletedRequest * @class */ var exports = function() { @@ -49,28 +49,31 @@ } /** - * Constructs a ConsentRequestRejection from a plain JavaScript object, optionally creating a new instance. + * Constructs a CompletedRequest from a plain JavaScript object, optionally creating a new instance. * Copies all relevant properties from data to obj if supplied or a new instance if not. * @param {Object} data The plain JavaScript object bearing properties of interest. - * @param {module:model/ConsentRequestRejection} obj Optional instance to populate. - * @return {module:model/ConsentRequestRejection} The populated ConsentRequestRejection instance. + * @param {module:model/CompletedRequest} obj Optional instance to populate. + * @return {module:model/CompletedRequest} The populated CompletedRequest instance. */ exports.constructFromObject = function(data, obj) { if (data) { obj = obj || new exports() - if (data.hasOwnProperty('reason')) { - obj['reason'] = ApiClient.convertToType(data['reason'], 'String') + if (data.hasOwnProperty('redirect_to')) { + obj['redirect_to'] = ApiClient.convertToType( + data['redirect_to'], + 'String' + ) } } return obj } /** - * Reason represents the reason why the user rejected the consent request. - * @member {String} reason + * RedirectURL is the URL which you should redirect the user to once the authentication process is completed. + * @member {String} redirect_to */ - exports.prototype['reason'] = undefined + exports.prototype['redirect_to'] = undefined return exports }) diff --git a/sdk/js/swagger/src/model/ConsentRequest.js b/sdk/js/swagger/src/model/ConsentRequest.js index cf0b3edf3db..6fbad0a58f8 100644 --- a/sdk/js/swagger/src/model/ConsentRequest.js +++ b/sdk/js/swagger/src/model/ConsentRequest.js @@ -17,20 +17,29 @@ ;(function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. - define(['ApiClient'], factory) + define( + ['ApiClient', 'model/OAuth2Client', 'model/OpenIDConnectContext'], + factory + ) } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. - module.exports = factory(require('../ApiClient')) + module.exports = factory( + require('../ApiClient'), + require('./OAuth2Client'), + require('./OpenIDConnectContext') + ) } else { // Browser globals (root is window) if (!root.OryHydraCloudNativeOAuth20AndOpenIdConnectServer) { root.OryHydraCloudNativeOAuth20AndOpenIdConnectServer = {} } root.OryHydraCloudNativeOAuth20AndOpenIdConnectServer.ConsentRequest = factory( - root.OryHydraCloudNativeOAuth20AndOpenIdConnectServer.ApiClient + root.OryHydraCloudNativeOAuth20AndOpenIdConnectServer.ApiClient, + root.OryHydraCloudNativeOAuth20AndOpenIdConnectServer.OAuth2Client, + root.OryHydraCloudNativeOAuth20AndOpenIdConnectServer.OpenIDConnectContext ) } -})(this, function(ApiClient) { +})(this, function(ApiClient, OAuth2Client, OpenIDConnectContext) { 'use strict' /** @@ -59,56 +68,72 @@ if (data) { obj = obj || new exports() - if (data.hasOwnProperty('clientId')) { - obj['clientId'] = ApiClient.convertToType(data['clientId'], 'String') + if (data.hasOwnProperty('challenge')) { + obj['challenge'] = ApiClient.convertToType(data['challenge'], 'String') } - if (data.hasOwnProperty('expiresAt')) { - obj['expiresAt'] = ApiClient.convertToType(data['expiresAt'], 'Date') + if (data.hasOwnProperty('client')) { + obj['client'] = OAuth2Client.constructFromObject(data['client']) } - if (data.hasOwnProperty('id')) { - obj['id'] = ApiClient.convertToType(data['id'], 'String') + if (data.hasOwnProperty('oidc_context')) { + obj['oidc_context'] = OpenIDConnectContext.constructFromObject( + data['oidc_context'] + ) } - if (data.hasOwnProperty('redirectUrl')) { - obj['redirectUrl'] = ApiClient.convertToType( - data['redirectUrl'], + if (data.hasOwnProperty('request_url')) { + obj['request_url'] = ApiClient.convertToType( + data['request_url'], 'String' ) } - if (data.hasOwnProperty('requestedScopes')) { - obj['requestedScopes'] = ApiClient.convertToType( - data['requestedScopes'], + if (data.hasOwnProperty('requested_scope')) { + obj['requested_scope'] = ApiClient.convertToType( + data['requested_scope'], ['String'] ) } + if (data.hasOwnProperty('skip')) { + obj['skip'] = ApiClient.convertToType(data['skip'], 'Boolean') + } + if (data.hasOwnProperty('subject')) { + obj['subject'] = ApiClient.convertToType(data['subject'], 'String') + } } return obj } /** - * ClientID is the client id that initiated the OAuth2 request. - * @member {String} clientId + * Challenge is the identifier (\"authorization challenge\") of the consent authorization request. It is used to identify the session. + * @member {String} challenge + */ + exports.prototype['challenge'] = undefined + /** + * @member {module:model/OAuth2Client} client + */ + exports.prototype['client'] = undefined + /** + * @member {module:model/OpenIDConnectContext} oidc_context */ - exports.prototype['clientId'] = undefined + exports.prototype['oidc_context'] = undefined /** - * ExpiresAt is the time where the access request will expire. - * @member {Date} expiresAt + * RequestURL is the original OAuth 2.0 Authorization URL requested by the OAuth 2.0 client. It is the URL which initiates the OAuth 2.0 Authorization Code or OAuth 2.0 Implicit flow. This URL is typically not needed, but might come in handy if you want to deal with additional request parameters. + * @member {String} request_url */ - exports.prototype['expiresAt'] = undefined + exports.prototype['request_url'] = undefined /** - * ID is the id of this consent request. - * @member {String} id + * RequestedScope contains all scopes requested by the OAuth 2.0 client. + * @member {Array.} requested_scope */ - exports.prototype['id'] = undefined + exports.prototype['requested_scope'] = undefined /** - * Redirect URL is the URL where the user agent should be redirected to after the consent has been accepted or rejected. - * @member {String} redirectUrl + * Skip, if true, implies that the client has requested the same scopes from the same user previously. If true, you must not ask the user to grant the requested scopes. You must however either allow or deny the consent request using the usual API call. + * @member {Boolean} skip */ - exports.prototype['redirectUrl'] = undefined + exports.prototype['skip'] = undefined /** - * RequestedScopes represents a list of scopes that have been requested by the OAuth2 request initiator. - * @member {Array.} requestedScopes + * Subject is the user ID of the end-user that authenticated. Now, that end user needs to grant or deny the scope requested by the OAuth 2.0 client. + * @member {String} subject */ - exports.prototype['requestedScopes'] = undefined + exports.prototype['subject'] = undefined return exports }) diff --git a/sdk/js/swagger/src/model/ConsentRequestSession.js b/sdk/js/swagger/src/model/ConsentRequestSession.js new file mode 100644 index 00000000000..b1486caecf0 --- /dev/null +++ b/sdk/js/swagger/src/model/ConsentRequestSession.js @@ -0,0 +1,88 @@ +/** + * ORY Hydra - Cloud Native OAuth 2.0 and OpenID Connect Server + * Welcome to the ORY Hydra HTTP API documentation. You will find documentation for all HTTP APIs here. Keep in mind that this document reflects the latest branch, always. Support for versioned documentation is coming in the future. + * + * OpenAPI spec version: Latest + * Contact: hi@ory.am + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * + * Swagger Codegen version: 2.2.3 + * + * Do not edit the class manually. + * + */ + +;(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(['ApiClient'], factory) + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + module.exports = factory(require('../ApiClient')) + } else { + // Browser globals (root is window) + if (!root.OryHydraCloudNativeOAuth20AndOpenIdConnectServer) { + root.OryHydraCloudNativeOAuth20AndOpenIdConnectServer = {} + } + root.OryHydraCloudNativeOAuth20AndOpenIdConnectServer.ConsentRequestSession = factory( + root.OryHydraCloudNativeOAuth20AndOpenIdConnectServer.ApiClient + ) + } +})(this, function(ApiClient) { + 'use strict' + + /** + * The ConsentRequestSession model module. + * @module model/ConsentRequestSession + * @version Latest + */ + + /** + * Constructs a new ConsentRequestSession. + * @alias module:model/ConsentRequestSession + * @class + */ + var exports = function() { + var _this = this + } + + /** + * Constructs a ConsentRequestSession from a plain JavaScript object, optionally creating a new instance. + * Copies all relevant properties from data to obj if supplied or a new instance if not. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @param {module:model/ConsentRequestSession} obj Optional instance to populate. + * @return {module:model/ConsentRequestSession} The populated ConsentRequestSession instance. + */ + exports.constructFromObject = function(data, obj) { + if (data) { + obj = obj || new exports() + + if (data.hasOwnProperty('access_token')) { + obj['access_token'] = ApiClient.convertToType(data['access_token'], { + String: Object + }) + } + if (data.hasOwnProperty('id_token')) { + obj['id_token'] = ApiClient.convertToType(data['id_token'], { + String: Object + }) + } + } + return obj + } + + /** + * AccessToken sets session data for the access and refresh token, as well as any future tokens issued by the refresh grant. Keep in mind that this data will be available to anyone performing OAuth 2.0 Challenge Introspection. If only your services can perform OAuth 2.0 Challenge Introspection, this is usually fine. But if third parties can access that endpoint as well, sensitive data from the session might be exposed to them. Use with care! + * @member {Object.} access_token + */ + exports.prototype['access_token'] = undefined + /** + * IDToken sets session data for the OpenID Connect ID token. Keep in mind that the session'id payloads are readable by anyone that has access to the ID Challenge. Use with care! + * @member {Object.} id_token + */ + exports.prototype['id_token'] = undefined + + return exports +}) diff --git a/sdk/js/swagger/src/model/Handler.js b/sdk/js/swagger/src/model/Handler.js index ed3d685573a..897ff149a97 100644 --- a/sdk/js/swagger/src/model/Handler.js +++ b/sdk/js/swagger/src/model/Handler.js @@ -18,14 +18,14 @@ if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. define( - ['ApiClient', 'model/Firewall', 'model/Manager', 'model/Writer'], + ['ApiClient', 'model/KeyGenerator', 'model/Manager', 'model/Writer'], factory ) } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. module.exports = factory( require('../ApiClient'), - require('./Firewall'), + require('./KeyGenerator'), require('./Manager'), require('./Writer') ) @@ -36,12 +36,12 @@ } root.OryHydraCloudNativeOAuth20AndOpenIdConnectServer.Handler = factory( root.OryHydraCloudNativeOAuth20AndOpenIdConnectServer.ApiClient, - root.OryHydraCloudNativeOAuth20AndOpenIdConnectServer.Firewall, + root.OryHydraCloudNativeOAuth20AndOpenIdConnectServer.KeyGenerator, root.OryHydraCloudNativeOAuth20AndOpenIdConnectServer.Manager, root.OryHydraCloudNativeOAuth20AndOpenIdConnectServer.Writer ) } -})(this, function(ApiClient, Firewall, Manager, Writer) { +})(this, function(ApiClient, KeyGenerator, Manager, Writer) { 'use strict' /** @@ -70,6 +70,11 @@ if (data) { obj = obj || new exports() + if (data.hasOwnProperty('Generators')) { + obj['Generators'] = ApiClient.convertToType(data['Generators'], { + String: KeyGenerator + }) + } if (data.hasOwnProperty('H')) { obj['H'] = Writer.constructFromObject(data['H']) } @@ -82,13 +87,14 @@ 'String' ) } - if (data.hasOwnProperty('W')) { - obj['W'] = Firewall.constructFromObject(data['W']) - } } return obj } + /** + * @member {Object.} Generators + */ + exports.prototype['Generators'] = undefined /** * @member {module:model/Writer} H */ @@ -101,10 +107,6 @@ * @member {String} ResourcePrefix */ exports.prototype['ResourcePrefix'] = undefined - /** - * @member {module:model/Firewall} W - */ - exports.prototype['W'] = undefined return exports }) diff --git a/sdk/js/swagger/src/model/LoginRequest.js b/sdk/js/swagger/src/model/LoginRequest.js new file mode 100644 index 00000000000..5e33f0fec11 --- /dev/null +++ b/sdk/js/swagger/src/model/LoginRequest.js @@ -0,0 +1,139 @@ +/** + * ORY Hydra - Cloud Native OAuth 2.0 and OpenID Connect Server + * Welcome to the ORY Hydra HTTP API documentation. You will find documentation for all HTTP APIs here. Keep in mind that this document reflects the latest branch, always. Support for versioned documentation is coming in the future. + * + * OpenAPI spec version: Latest + * Contact: hi@ory.am + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * + * Swagger Codegen version: 2.2.3 + * + * Do not edit the class manually. + * + */ + +;(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define( + ['ApiClient', 'model/OAuth2Client', 'model/OpenIDConnectContext'], + factory + ) + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + module.exports = factory( + require('../ApiClient'), + require('./OAuth2Client'), + require('./OpenIDConnectContext') + ) + } else { + // Browser globals (root is window) + if (!root.OryHydraCloudNativeOAuth20AndOpenIdConnectServer) { + root.OryHydraCloudNativeOAuth20AndOpenIdConnectServer = {} + } + root.OryHydraCloudNativeOAuth20AndOpenIdConnectServer.LoginRequest = factory( + root.OryHydraCloudNativeOAuth20AndOpenIdConnectServer.ApiClient, + root.OryHydraCloudNativeOAuth20AndOpenIdConnectServer.OAuth2Client, + root.OryHydraCloudNativeOAuth20AndOpenIdConnectServer.OpenIDConnectContext + ) + } +})(this, function(ApiClient, OAuth2Client, OpenIDConnectContext) { + 'use strict' + + /** + * The LoginRequest model module. + * @module model/LoginRequest + * @version Latest + */ + + /** + * Constructs a new LoginRequest. + * @alias module:model/LoginRequest + * @class + */ + var exports = function() { + var _this = this + } + + /** + * Constructs a LoginRequest from a plain JavaScript object, optionally creating a new instance. + * Copies all relevant properties from data to obj if supplied or a new instance if not. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @param {module:model/LoginRequest} obj Optional instance to populate. + * @return {module:model/LoginRequest} The populated LoginRequest instance. + */ + exports.constructFromObject = function(data, obj) { + if (data) { + obj = obj || new exports() + + if (data.hasOwnProperty('challenge')) { + obj['challenge'] = ApiClient.convertToType(data['challenge'], 'String') + } + if (data.hasOwnProperty('client')) { + obj['client'] = OAuth2Client.constructFromObject(data['client']) + } + if (data.hasOwnProperty('oidc_context')) { + obj['oidc_context'] = OpenIDConnectContext.constructFromObject( + data['oidc_context'] + ) + } + if (data.hasOwnProperty('request_url')) { + obj['request_url'] = ApiClient.convertToType( + data['request_url'], + 'String' + ) + } + if (data.hasOwnProperty('requested_scope')) { + obj['requested_scope'] = ApiClient.convertToType( + data['requested_scope'], + ['String'] + ) + } + if (data.hasOwnProperty('skip')) { + obj['skip'] = ApiClient.convertToType(data['skip'], 'Boolean') + } + if (data.hasOwnProperty('subject')) { + obj['subject'] = ApiClient.convertToType(data['subject'], 'String') + } + } + return obj + } + + /** + * Challenge is the identifier (\"authentication challenge\") of the consent authentication request. It is used to identify the session. + * @member {String} challenge + */ + exports.prototype['challenge'] = undefined + /** + * @member {module:model/OAuth2Client} client + */ + exports.prototype['client'] = undefined + /** + * @member {module:model/OpenIDConnectContext} oidc_context + */ + exports.prototype['oidc_context'] = undefined + /** + * RequestURL is the original OAuth 2.0 Authorization URL requested by the OAuth 2.0 client. It is the URL which initiates the OAuth 2.0 Authorization Code or OAuth 2.0 Implicit flow. This URL is typically not needed, but might come in handy if you want to deal with additional request parameters. + * @member {String} request_url + */ + exports.prototype['request_url'] = undefined + /** + * RequestedScope contains all scopes requested by the OAuth 2.0 client. + * @member {Array.} requested_scope + */ + exports.prototype['requested_scope'] = undefined + /** + * Skip, if true, implies that the client has requested the same scopes from the same user previously. If true, you can skip asking the user to grant the requested scopes, and simply forward the user to the redirect URL. This feature allows you to update / set session information. + * @member {Boolean} skip + */ + exports.prototype['skip'] = undefined + /** + * Subject is the user ID of the end-user that authenticated. Now, that end user needs to grant or deny the scope requested by the OAuth 2.0 client. + * @member {String} subject + */ + exports.prototype['subject'] = undefined + + return exports +}) diff --git a/sdk/js/swagger/src/model/OAuth2ConsentRequest.js b/sdk/js/swagger/src/model/OAuth2ConsentRequest.js deleted file mode 100644 index 79442e446a9..00000000000 --- a/sdk/js/swagger/src/model/OAuth2ConsentRequest.js +++ /dev/null @@ -1,114 +0,0 @@ -/** - * ORY Hydra - Cloud Native OAuth 2.0 and OpenID Connect Server - * Welcome to the ORY Hydra HTTP API documentation. You will find documentation for all HTTP APIs here. Keep in mind that this document reflects the latest branch, always. Support for versioned documentation is coming in the future. - * - * OpenAPI spec version: Latest - * Contact: hi@ory.am - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * - * Swagger Codegen version: 2.2.3 - * - * Do not edit the class manually. - * - */ - -;(function(root, factory) { - if (typeof define === 'function' && define.amd) { - // AMD. Register as an anonymous module. - define(['ApiClient'], factory) - } else if (typeof module === 'object' && module.exports) { - // CommonJS-like environments that support module.exports, like Node. - module.exports = factory(require('../ApiClient')) - } else { - // Browser globals (root is window) - if (!root.OryHydraCloudNativeOAuth20AndOpenIdConnectServer) { - root.OryHydraCloudNativeOAuth20AndOpenIdConnectServer = {} - } - root.OryHydraCloudNativeOAuth20AndOpenIdConnectServer.OAuth2ConsentRequest = factory( - root.OryHydraCloudNativeOAuth20AndOpenIdConnectServer.ApiClient - ) - } -})(this, function(ApiClient) { - 'use strict' - - /** - * The OAuth2ConsentRequest model module. - * @module model/OAuth2ConsentRequest - * @version Latest - */ - - /** - * Constructs a new OAuth2ConsentRequest. - * @alias module:model/OAuth2ConsentRequest - * @class - */ - var exports = function() { - var _this = this - } - - /** - * Constructs a OAuth2ConsentRequest from a plain JavaScript object, optionally creating a new instance. - * Copies all relevant properties from data to obj if supplied or a new instance if not. - * @param {Object} data The plain JavaScript object bearing properties of interest. - * @param {module:model/OAuth2ConsentRequest} obj Optional instance to populate. - * @return {module:model/OAuth2ConsentRequest} The populated OAuth2ConsentRequest instance. - */ - exports.constructFromObject = function(data, obj) { - if (data) { - obj = obj || new exports() - - if (data.hasOwnProperty('clientId')) { - obj['clientId'] = ApiClient.convertToType(data['clientId'], 'String') - } - if (data.hasOwnProperty('expiresAt')) { - obj['expiresAt'] = ApiClient.convertToType(data['expiresAt'], 'String') - } - if (data.hasOwnProperty('id')) { - obj['id'] = ApiClient.convertToType(data['id'], 'String') - } - if (data.hasOwnProperty('redirectUrl')) { - obj['redirectUrl'] = ApiClient.convertToType( - data['redirectUrl'], - 'String' - ) - } - if (data.hasOwnProperty('requestedScopes')) { - obj['requestedScopes'] = ApiClient.convertToType( - data['requestedScopes'], - ['String'] - ) - } - } - return obj - } - - /** - * ClientID is the client id that initiated the OAuth2 request. - * @member {String} clientId - */ - exports.prototype['clientId'] = undefined - /** - * ExpiresAt is the time where the access request will expire. - * @member {String} expiresAt - */ - exports.prototype['expiresAt'] = undefined - /** - * ID is the id of this consent request. - * @member {String} id - */ - exports.prototype['id'] = undefined - /** - * Redirect URL is the URL where the user agent should be redirected to after the consent has been accepted or rejected. - * @member {String} redirectUrl - */ - exports.prototype['redirectUrl'] = undefined - /** - * RequestedScopes represents a list of scopes that have been requested by the OAuth2 request initiator. - * @member {Array.} requestedScopes - */ - exports.prototype['requestedScopes'] = undefined - - return exports -}) diff --git a/sdk/js/swagger/src/model/OpenIDConnectContext.js b/sdk/js/swagger/src/model/OpenIDConnectContext.js new file mode 100644 index 00000000000..94e749b07df --- /dev/null +++ b/sdk/js/swagger/src/model/OpenIDConnectContext.js @@ -0,0 +1,96 @@ +/** + * ORY Hydra - Cloud Native OAuth 2.0 and OpenID Connect Server + * Welcome to the ORY Hydra HTTP API documentation. You will find documentation for all HTTP APIs here. Keep in mind that this document reflects the latest branch, always. Support for versioned documentation is coming in the future. + * + * OpenAPI spec version: Latest + * Contact: hi@ory.am + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * + * Swagger Codegen version: 2.2.3 + * + * Do not edit the class manually. + * + */ + +;(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(['ApiClient'], factory) + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + module.exports = factory(require('../ApiClient')) + } else { + // Browser globals (root is window) + if (!root.OryHydraCloudNativeOAuth20AndOpenIdConnectServer) { + root.OryHydraCloudNativeOAuth20AndOpenIdConnectServer = {} + } + root.OryHydraCloudNativeOAuth20AndOpenIdConnectServer.OpenIDConnectContext = factory( + root.OryHydraCloudNativeOAuth20AndOpenIdConnectServer.ApiClient + ) + } +})(this, function(ApiClient) { + 'use strict' + + /** + * The OpenIDConnectContext model module. + * @module model/OpenIDConnectContext + * @version Latest + */ + + /** + * Constructs a new OpenIDConnectContext. + * @alias module:model/OpenIDConnectContext + * @class + */ + var exports = function() { + var _this = this + } + + /** + * Constructs a OpenIDConnectContext from a plain JavaScript object, optionally creating a new instance. + * Copies all relevant properties from data to obj if supplied or a new instance if not. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @param {module:model/OpenIDConnectContext} obj Optional instance to populate. + * @return {module:model/OpenIDConnectContext} The populated OpenIDConnectContext instance. + */ + exports.constructFromObject = function(data, obj) { + if (data) { + obj = obj || new exports() + + if (data.hasOwnProperty('acr_values')) { + obj['acr_values'] = ApiClient.convertToType(data['acr_values'], [ + 'String' + ]) + } + if (data.hasOwnProperty('display')) { + obj['display'] = ApiClient.convertToType(data['display'], 'String') + } + if (data.hasOwnProperty('ui_locales')) { + obj['ui_locales'] = ApiClient.convertToType(data['ui_locales'], [ + 'String' + ]) + } + } + return obj + } + + /** + * ACRValues is the Authentication AuthorizationContext Class Reference requested in the OAuth 2.0 Authorization request. It is a parameter defined by OpenID Connect and expresses which level of authentication (e.g. 2FA) is required. OpenID Connect defines it as follows: > Requested Authentication AuthorizationContext Class Reference values. Space-separated string that specifies the acr values that the Authorization Server is being requested to use for processing this Authentication Request, with the values appearing in order of preference. The Authentication AuthorizationContext Class satisfied by the authentication performed is returned as the acr Claim Value, as specified in Section 2. The acr Claim is requested as a Voluntary Claim by this parameter. + * @member {Array.} acr_values + */ + exports.prototype['acr_values'] = undefined + /** + * Display is a string value that specifies how the Authorization Server displays the authentication and consent user interface pages to the End-User. The defined values are: page: The Authorization Server SHOULD display the authentication and consent UI consistent with a full User Agent page view. If the display parameter is not specified, this is the default display mode. popup: The Authorization Server SHOULD display the authentication and consent UI consistent with a popup User Agent window. The popup User Agent window should be of an appropriate size for a login-focused dialog and should not obscure the entire window that it is popping up over. touch: The Authorization Server SHOULD display the authentication and consent UI consistent with a device that leverages a touch interface. wap: The Authorization Server SHOULD display the authentication and consent UI consistent with a \"feature phone\" type display. The Authorization Server MAY also attempt to detect the capabilities of the User Agent and present an appropriate display. + * @member {String} display + */ + exports.prototype['display'] = undefined + /** + * UILocales is the End-User'id preferred languages and scripts for the user interface, represented as a space-separated list of BCP47 [RFC5646] language tag values, ordered by preference. For instance, the value \"fr-CA fr en\" represents a preference for French as spoken in Canada, then French (without a region designation), followed by English (without a region designation). An error SHOULD NOT result if some or all of the requested locales are not supported by the OpenID Provider. + * @member {Array.} ui_locales + */ + exports.prototype['ui_locales'] = undefined + + return exports +}) diff --git a/sdk/js/swagger/src/model/RejectRequest.js b/sdk/js/swagger/src/model/RejectRequest.js new file mode 100644 index 00000000000..fb427e7657d --- /dev/null +++ b/sdk/js/swagger/src/model/RejectRequest.js @@ -0,0 +1,115 @@ +/** + * ORY Hydra - Cloud Native OAuth 2.0 and OpenID Connect Server + * Welcome to the ORY Hydra HTTP API documentation. You will find documentation for all HTTP APIs here. Keep in mind that this document reflects the latest branch, always. Support for versioned documentation is coming in the future. + * + * OpenAPI spec version: Latest + * Contact: hi@ory.am + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * + * Swagger Codegen version: 2.2.3 + * + * Do not edit the class manually. + * + */ + +;(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(['ApiClient'], factory) + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + module.exports = factory(require('../ApiClient')) + } else { + // Browser globals (root is window) + if (!root.OryHydraCloudNativeOAuth20AndOpenIdConnectServer) { + root.OryHydraCloudNativeOAuth20AndOpenIdConnectServer = {} + } + root.OryHydraCloudNativeOAuth20AndOpenIdConnectServer.RejectRequest = factory( + root.OryHydraCloudNativeOAuth20AndOpenIdConnectServer.ApiClient + ) + } +})(this, function(ApiClient) { + 'use strict' + + /** + * The RejectRequest model module. + * @module model/RejectRequest + * @version Latest + */ + + /** + * Constructs a new RejectRequest. + * @alias module:model/RejectRequest + * @class + */ + var exports = function() { + var _this = this + } + + /** + * Constructs a RejectRequest from a plain JavaScript object, optionally creating a new instance. + * Copies all relevant properties from data to obj if supplied or a new instance if not. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @param {module:model/RejectRequest} obj Optional instance to populate. + * @return {module:model/RejectRequest} The populated RejectRequest instance. + */ + exports.constructFromObject = function(data, obj) { + if (data) { + obj = obj || new exports() + + if (data.hasOwnProperty('error')) { + obj['error'] = ApiClient.convertToType(data['error'], 'String') + } + if (data.hasOwnProperty('error_debug')) { + obj['error_debug'] = ApiClient.convertToType( + data['error_debug'], + 'String' + ) + } + if (data.hasOwnProperty('error_description')) { + obj['error_description'] = ApiClient.convertToType( + data['error_description'], + 'String' + ) + } + if (data.hasOwnProperty('error_hint')) { + obj['error_hint'] = ApiClient.convertToType( + data['error_hint'], + 'String' + ) + } + if (data.hasOwnProperty('status_code')) { + obj['status_code'] = ApiClient.convertToType( + data['status_code'], + 'Number' + ) + } + } + return obj + } + + /** + * @member {String} error + */ + exports.prototype['error'] = undefined + /** + * @member {String} error_debug + */ + exports.prototype['error_debug'] = undefined + /** + * @member {String} error_description + */ + exports.prototype['error_description'] = undefined + /** + * @member {String} error_hint + */ + exports.prototype['error_hint'] = undefined + /** + * @member {Number} status_code + */ + exports.prototype['status_code'] = undefined + + return exports +}) diff --git a/sdk/js/swagger/src/model/SwaggerAcceptConsentRequest.js b/sdk/js/swagger/src/model/SwaggerAcceptConsentRequest.js deleted file mode 100644 index 5c68db8e4a5..00000000000 --- a/sdk/js/swagger/src/model/SwaggerAcceptConsentRequest.js +++ /dev/null @@ -1,93 +0,0 @@ -/** - * ORY Hydra - Cloud Native OAuth 2.0 and OpenID Connect Server - * Welcome to the ORY Hydra HTTP API documentation. You will find documentation for all HTTP APIs here. Keep in mind that this document reflects the latest branch, always. Support for versioned documentation is coming in the future. - * - * OpenAPI spec version: Latest - * Contact: hi@ory.am - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * - * Swagger Codegen version: 2.2.3 - * - * Do not edit the class manually. - * - */ - -;(function(root, factory) { - if (typeof define === 'function' && define.amd) { - // AMD. Register as an anonymous module. - define(['ApiClient', 'model/ConsentRequestAcceptance'], factory) - } else if (typeof module === 'object' && module.exports) { - // CommonJS-like environments that support module.exports, like Node. - module.exports = factory( - require('../ApiClient'), - require('./ConsentRequestAcceptance') - ) - } else { - // Browser globals (root is window) - if (!root.OryHydraCloudNativeOAuth20AndOpenIdConnectServer) { - root.OryHydraCloudNativeOAuth20AndOpenIdConnectServer = {} - } - root.OryHydraCloudNativeOAuth20AndOpenIdConnectServer.SwaggerAcceptConsentRequest = factory( - root.OryHydraCloudNativeOAuth20AndOpenIdConnectServer.ApiClient, - root.OryHydraCloudNativeOAuth20AndOpenIdConnectServer - .ConsentRequestAcceptance - ) - } -})(this, function(ApiClient, ConsentRequestAcceptance) { - 'use strict' - - /** - * The SwaggerAcceptConsentRequest model module. - * @module model/SwaggerAcceptConsentRequest - * @version Latest - */ - - /** - * Constructs a new SwaggerAcceptConsentRequest. - * @alias module:model/SwaggerAcceptConsentRequest - * @class - * @param body {module:model/ConsentRequestAcceptance} - * @param id {String} in: path - */ - var exports = function(body, id) { - var _this = this - - _this['Body'] = body - _this['id'] = id - } - - /** - * Constructs a SwaggerAcceptConsentRequest from a plain JavaScript object, optionally creating a new instance. - * Copies all relevant properties from data to obj if supplied or a new instance if not. - * @param {Object} data The plain JavaScript object bearing properties of interest. - * @param {module:model/SwaggerAcceptConsentRequest} obj Optional instance to populate. - * @return {module:model/SwaggerAcceptConsentRequest} The populated SwaggerAcceptConsentRequest instance. - */ - exports.constructFromObject = function(data, obj) { - if (data) { - obj = obj || new exports() - - if (data.hasOwnProperty('Body')) { - obj['Body'] = ConsentRequestAcceptance.constructFromObject(data['Body']) - } - if (data.hasOwnProperty('id')) { - obj['id'] = ApiClient.convertToType(data['id'], 'String') - } - } - return obj - } - - /** - * @member {module:model/ConsentRequestAcceptance} Body - */ - exports.prototype['Body'] = undefined - /** - * in: path - * @member {String} id - */ - exports.prototype['id'] = undefined - - return exports -}) diff --git a/sdk/js/swagger/src/model/SwaggerOAuthConsentRequestPayload.js b/sdk/js/swagger/src/model/SwaggerOAuthConsentRequestPayload.js deleted file mode 100644 index d8fe4271252..00000000000 --- a/sdk/js/swagger/src/model/SwaggerOAuthConsentRequestPayload.js +++ /dev/null @@ -1,79 +0,0 @@ -/** - * ORY Hydra - Cloud Native OAuth 2.0 and OpenID Connect Server - * Welcome to the ORY Hydra HTTP API documentation. You will find documentation for all HTTP APIs here. Keep in mind that this document reflects the latest branch, always. Support for versioned documentation is coming in the future. - * - * OpenAPI spec version: Latest - * Contact: hi@ory.am - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * - * Swagger Codegen version: 2.2.3 - * - * Do not edit the class manually. - * - */ - -;(function(root, factory) { - if (typeof define === 'function' && define.amd) { - // AMD. Register as an anonymous module. - define(['ApiClient'], factory) - } else if (typeof module === 'object' && module.exports) { - // CommonJS-like environments that support module.exports, like Node. - module.exports = factory(require('../ApiClient')) - } else { - // Browser globals (root is window) - if (!root.OryHydraCloudNativeOAuth20AndOpenIdConnectServer) { - root.OryHydraCloudNativeOAuth20AndOpenIdConnectServer = {} - } - root.OryHydraCloudNativeOAuth20AndOpenIdConnectServer.SwaggerOAuthConsentRequestPayload = factory( - root.OryHydraCloudNativeOAuth20AndOpenIdConnectServer.ApiClient - ) - } -})(this, function(ApiClient) { - 'use strict' - - /** - * The SwaggerOAuthConsentRequestPayload model module. - * @module model/SwaggerOAuthConsentRequestPayload - * @version Latest - */ - - /** - * Constructs a new SwaggerOAuthConsentRequestPayload. - * @alias module:model/SwaggerOAuthConsentRequestPayload - * @class - * @param id {String} The id of the OAuth 2.0 Consent Request. - */ - var exports = function(id) { - var _this = this - - _this['id'] = id - } - - /** - * Constructs a SwaggerOAuthConsentRequestPayload from a plain JavaScript object, optionally creating a new instance. - * Copies all relevant properties from data to obj if supplied or a new instance if not. - * @param {Object} data The plain JavaScript object bearing properties of interest. - * @param {module:model/SwaggerOAuthConsentRequestPayload} obj Optional instance to populate. - * @return {module:model/SwaggerOAuthConsentRequestPayload} The populated SwaggerOAuthConsentRequestPayload instance. - */ - exports.constructFromObject = function(data, obj) { - if (data) { - obj = obj || new exports() - - if (data.hasOwnProperty('id')) { - obj['id'] = ApiClient.convertToType(data['id'], 'String') - } - } - return obj - } - - /** - * The id of the OAuth 2.0 Consent Request. - * @member {String} id - */ - exports.prototype['id'] = undefined - - return exports -}) diff --git a/sdk/js/swagger/src/model/SwaggerRejectConsentRequest.js b/sdk/js/swagger/src/model/SwaggerRejectConsentRequest.js deleted file mode 100644 index 84b29d24ca3..00000000000 --- a/sdk/js/swagger/src/model/SwaggerRejectConsentRequest.js +++ /dev/null @@ -1,93 +0,0 @@ -/** - * ORY Hydra - Cloud Native OAuth 2.0 and OpenID Connect Server - * Welcome to the ORY Hydra HTTP API documentation. You will find documentation for all HTTP APIs here. Keep in mind that this document reflects the latest branch, always. Support for versioned documentation is coming in the future. - * - * OpenAPI spec version: Latest - * Contact: hi@ory.am - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * - * Swagger Codegen version: 2.2.3 - * - * Do not edit the class manually. - * - */ - -;(function(root, factory) { - if (typeof define === 'function' && define.amd) { - // AMD. Register as an anonymous module. - define(['ApiClient', 'model/ConsentRequestRejection'], factory) - } else if (typeof module === 'object' && module.exports) { - // CommonJS-like environments that support module.exports, like Node. - module.exports = factory( - require('../ApiClient'), - require('./ConsentRequestRejection') - ) - } else { - // Browser globals (root is window) - if (!root.OryHydraCloudNativeOAuth20AndOpenIdConnectServer) { - root.OryHydraCloudNativeOAuth20AndOpenIdConnectServer = {} - } - root.OryHydraCloudNativeOAuth20AndOpenIdConnectServer.SwaggerRejectConsentRequest = factory( - root.OryHydraCloudNativeOAuth20AndOpenIdConnectServer.ApiClient, - root.OryHydraCloudNativeOAuth20AndOpenIdConnectServer - .ConsentRequestRejection - ) - } -})(this, function(ApiClient, ConsentRequestRejection) { - 'use strict' - - /** - * The SwaggerRejectConsentRequest model module. - * @module model/SwaggerRejectConsentRequest - * @version Latest - */ - - /** - * Constructs a new SwaggerRejectConsentRequest. - * @alias module:model/SwaggerRejectConsentRequest - * @class - * @param body {module:model/ConsentRequestRejection} - * @param id {String} in: path - */ - var exports = function(body, id) { - var _this = this - - _this['Body'] = body - _this['id'] = id - } - - /** - * Constructs a SwaggerRejectConsentRequest from a plain JavaScript object, optionally creating a new instance. - * Copies all relevant properties from data to obj if supplied or a new instance if not. - * @param {Object} data The plain JavaScript object bearing properties of interest. - * @param {module:model/SwaggerRejectConsentRequest} obj Optional instance to populate. - * @return {module:model/SwaggerRejectConsentRequest} The populated SwaggerRejectConsentRequest instance. - */ - exports.constructFromObject = function(data, obj) { - if (data) { - obj = obj || new exports() - - if (data.hasOwnProperty('Body')) { - obj['Body'] = ConsentRequestRejection.constructFromObject(data['Body']) - } - if (data.hasOwnProperty('id')) { - obj['id'] = ApiClient.convertToType(data['id'], 'String') - } - } - return obj - } - - /** - * @member {module:model/ConsentRequestRejection} Body - */ - exports.prototype['Body'] = undefined - /** - * in: path - * @member {String} id - */ - exports.prototype['id'] = undefined - - return exports -}) diff --git a/sdk/php/swagger/README.md b/sdk/php/swagger/README.md index 75f8c5473d1..85ef71bbce0 100644 --- a/sdk/php/swagger/README.md +++ b/sdk/php/swagger/README.md @@ -83,18 +83,21 @@ Class | Method | HTTP request | Description *JsonWebKeyApi* | [**getJsonWebKeySet**](docs/Api/JsonWebKeyApi.md#getjsonwebkeyset) | **GET** /keys/{set} | Retrieve a JSON Web Key Set *JsonWebKeyApi* | [**updateJsonWebKey**](docs/Api/JsonWebKeyApi.md#updatejsonwebkey) | **PUT** /keys/{set}/{kid} | Update a JSON Web Key *JsonWebKeyApi* | [**updateJsonWebKeySet**](docs/Api/JsonWebKeyApi.md#updatejsonwebkeyset) | **PUT** /keys/{set} | Update a JSON Web Key Set -*OAuth2Api* | [**acceptOAuth2ConsentRequest**](docs/Api/OAuth2Api.md#acceptoauth2consentrequest) | **PATCH** /oauth2/consent/requests/{id}/accept | Accept a consent request +*OAuth2Api* | [**acceptConsentRequest**](docs/Api/OAuth2Api.md#acceptconsentrequest) | **PUT** /oauth2/auth/requests/consent/{challenge}/accept | Accept an consent request +*OAuth2Api* | [**acceptLoginRequest**](docs/Api/OAuth2Api.md#acceptloginrequest) | **PUT** /oauth2/auth/requests/login/{challenge}/accept | Accept an login request *OAuth2Api* | [**createOAuth2Client**](docs/Api/OAuth2Api.md#createoauth2client) | **POST** /clients | Create an OAuth 2.0 client *OAuth2Api* | [**deleteOAuth2Client**](docs/Api/OAuth2Api.md#deleteoauth2client) | **DELETE** /clients/{id} | Deletes an OAuth 2.0 Client *OAuth2Api* | [**flushInactiveOAuth2Tokens**](docs/Api/OAuth2Api.md#flushinactiveoauth2tokens) | **POST** /oauth2/flush | Flush Expired OAuth2 Access Tokens +*OAuth2Api* | [**getConsentRequest**](docs/Api/OAuth2Api.md#getconsentrequest) | **GET** /oauth2/auth/requests/consent/{challenge} | Get consent request information +*OAuth2Api* | [**getLoginRequest**](docs/Api/OAuth2Api.md#getloginrequest) | **GET** /oauth2/auth/requests/login/{challenge} | Get an login request *OAuth2Api* | [**getOAuth2Client**](docs/Api/OAuth2Api.md#getoauth2client) | **GET** /clients/{id} | Get an OAuth 2.0 Client. -*OAuth2Api* | [**getOAuth2ConsentRequest**](docs/Api/OAuth2Api.md#getoauth2consentrequest) | **GET** /oauth2/consent/requests/{id} | Receive consent request information *OAuth2Api* | [**getWellKnown**](docs/Api/OAuth2Api.md#getwellknown) | **GET** /.well-known/openid-configuration | Server well known configuration *OAuth2Api* | [**introspectOAuth2Token**](docs/Api/OAuth2Api.md#introspectoauth2token) | **POST** /oauth2/introspect | Introspect OAuth2 tokens *OAuth2Api* | [**listOAuth2Clients**](docs/Api/OAuth2Api.md#listoauth2clients) | **GET** /clients | List OAuth 2.0 Clients *OAuth2Api* | [**oauthAuth**](docs/Api/OAuth2Api.md#oauthauth) | **GET** /oauth2/auth | The OAuth 2.0 authorize endpoint *OAuth2Api* | [**oauthToken**](docs/Api/OAuth2Api.md#oauthtoken) | **POST** /oauth2/token | The OAuth 2.0 token endpoint -*OAuth2Api* | [**rejectOAuth2ConsentRequest**](docs/Api/OAuth2Api.md#rejectoauth2consentrequest) | **PATCH** /oauth2/consent/requests/{id}/reject | Reject a consent request +*OAuth2Api* | [**rejectConsentRequest**](docs/Api/OAuth2Api.md#rejectconsentrequest) | **PUT** /oauth2/auth/requests/consent/{challenge}/reject | Reject an consent request +*OAuth2Api* | [**rejectLoginRequest**](docs/Api/OAuth2Api.md#rejectloginrequest) | **PUT** /oauth2/auth/requests/login/{challenge}/reject | Reject an logout request *OAuth2Api* | [**revokeOAuth2Token**](docs/Api/OAuth2Api.md#revokeoauth2token) | **POST** /oauth2/revoke | Revoke OAuth2 tokens *OAuth2Api* | [**updateOAuth2Client**](docs/Api/OAuth2Api.md#updateoauth2client) | **PUT** /clients/{id} | Update an OAuth 2.0 Client *OAuth2Api* | [**userinfo**](docs/Api/OAuth2Api.md#userinfo) | **POST** /userinfo | OpenID Connect Userinfo @@ -103,10 +106,12 @@ Class | Method | HTTP request | Description ## Documentation For Models + - [AcceptConsentRequest](docs/Model/AcceptConsentRequest.md) + - [AcceptLoginRequest](docs/Model/AcceptLoginRequest.md) + - [AuthenticationSession](docs/Model/AuthenticationSession.md) + - [CompletedRequest](docs/Model/CompletedRequest.md) - [ConsentRequest](docs/Model/ConsentRequest.md) - - [ConsentRequestAcceptance](docs/Model/ConsentRequestAcceptance.md) - - [ConsentRequestManager](docs/Model/ConsentRequestManager.md) - - [ConsentRequestRejection](docs/Model/ConsentRequestRejection.md) + - [ConsentRequestSession](docs/Model/ConsentRequestSession.md) - [FlushInactiveOAuth2TokensRequest](docs/Model/FlushInactiveOAuth2TokensRequest.md) - [Handler](docs/Model/Handler.md) - [InlineResponse200](docs/Model/InlineResponse200.md) @@ -116,22 +121,21 @@ Class | Method | HTTP request | Description - [JsonWebKeySet](docs/Model/JsonWebKeySet.md) - [JsonWebKeySetGeneratorRequest](docs/Model/JsonWebKeySetGeneratorRequest.md) - [KeyGenerator](docs/Model/KeyGenerator.md) + - [LoginRequest](docs/Model/LoginRequest.md) - [Manager](docs/Model/Manager.md) - [OAuth2Client](docs/Model/OAuth2Client.md) - - [OAuth2ConsentRequest](docs/Model/OAuth2ConsentRequest.md) - [OAuth2TokenIntrospection](docs/Model/OAuth2TokenIntrospection.md) - [OauthTokenResponse](docs/Model/OauthTokenResponse.md) + - [OpenIDConnectContext](docs/Model/OpenIDConnectContext.md) - [RawMessage](docs/Model/RawMessage.md) - - [SwaggerAcceptConsentRequest](docs/Model/SwaggerAcceptConsentRequest.md) + - [RejectRequest](docs/Model/RejectRequest.md) - [SwaggerFlushInactiveAccessTokens](docs/Model/SwaggerFlushInactiveAccessTokens.md) - [SwaggerJsonWebKeyQuery](docs/Model/SwaggerJsonWebKeyQuery.md) - [SwaggerJwkCreateSet](docs/Model/SwaggerJwkCreateSet.md) - [SwaggerJwkSetQuery](docs/Model/SwaggerJwkSetQuery.md) - [SwaggerJwkUpdateSet](docs/Model/SwaggerJwkUpdateSet.md) - [SwaggerJwkUpdateSetKey](docs/Model/SwaggerJwkUpdateSetKey.md) - - [SwaggerOAuthConsentRequestPayload](docs/Model/SwaggerOAuthConsentRequestPayload.md) - [SwaggerOAuthIntrospectionRequest](docs/Model/SwaggerOAuthIntrospectionRequest.md) - - [SwaggerRejectConsentRequest](docs/Model/SwaggerRejectConsentRequest.md) - [SwaggerRevokeOAuth2TokenParameters](docs/Model/SwaggerRevokeOAuth2TokenParameters.md) - [UserinfoResponse](docs/Model/UserinfoResponse.md) - [WellKnown](docs/Model/WellKnown.md) diff --git a/sdk/php/swagger/docs/Api/OAuth2Api.md b/sdk/php/swagger/docs/Api/OAuth2Api.md index 291b912e605..80d10400b72 100644 --- a/sdk/php/swagger/docs/Api/OAuth2Api.md +++ b/sdk/php/swagger/docs/Api/OAuth2Api.md @@ -5,30 +5,33 @@ All URIs are relative to *http://localhost* Method | HTTP request | Description ------------- | ------------- | ------------- -[**acceptOAuth2ConsentRequest**](OAuth2Api.md#acceptOAuth2ConsentRequest) | **PATCH** /oauth2/consent/requests/{id}/accept | Accept a consent request +[**acceptConsentRequest**](OAuth2Api.md#acceptConsentRequest) | **PUT** /oauth2/auth/requests/consent/{challenge}/accept | Accept an consent request +[**acceptLoginRequest**](OAuth2Api.md#acceptLoginRequest) | **PUT** /oauth2/auth/requests/login/{challenge}/accept | Accept an login request [**createOAuth2Client**](OAuth2Api.md#createOAuth2Client) | **POST** /clients | Create an OAuth 2.0 client [**deleteOAuth2Client**](OAuth2Api.md#deleteOAuth2Client) | **DELETE** /clients/{id} | Deletes an OAuth 2.0 Client [**flushInactiveOAuth2Tokens**](OAuth2Api.md#flushInactiveOAuth2Tokens) | **POST** /oauth2/flush | Flush Expired OAuth2 Access Tokens +[**getConsentRequest**](OAuth2Api.md#getConsentRequest) | **GET** /oauth2/auth/requests/consent/{challenge} | Get consent request information +[**getLoginRequest**](OAuth2Api.md#getLoginRequest) | **GET** /oauth2/auth/requests/login/{challenge} | Get an login request [**getOAuth2Client**](OAuth2Api.md#getOAuth2Client) | **GET** /clients/{id} | Get an OAuth 2.0 Client. -[**getOAuth2ConsentRequest**](OAuth2Api.md#getOAuth2ConsentRequest) | **GET** /oauth2/consent/requests/{id} | Receive consent request information [**getWellKnown**](OAuth2Api.md#getWellKnown) | **GET** /.well-known/openid-configuration | Server well known configuration [**introspectOAuth2Token**](OAuth2Api.md#introspectOAuth2Token) | **POST** /oauth2/introspect | Introspect OAuth2 tokens [**listOAuth2Clients**](OAuth2Api.md#listOAuth2Clients) | **GET** /clients | List OAuth 2.0 Clients [**oauthAuth**](OAuth2Api.md#oauthAuth) | **GET** /oauth2/auth | The OAuth 2.0 authorize endpoint [**oauthToken**](OAuth2Api.md#oauthToken) | **POST** /oauth2/token | The OAuth 2.0 token endpoint -[**rejectOAuth2ConsentRequest**](OAuth2Api.md#rejectOAuth2ConsentRequest) | **PATCH** /oauth2/consent/requests/{id}/reject | Reject a consent request +[**rejectConsentRequest**](OAuth2Api.md#rejectConsentRequest) | **PUT** /oauth2/auth/requests/consent/{challenge}/reject | Reject an consent request +[**rejectLoginRequest**](OAuth2Api.md#rejectLoginRequest) | **PUT** /oauth2/auth/requests/login/{challenge}/reject | Reject an logout request [**revokeOAuth2Token**](OAuth2Api.md#revokeOAuth2Token) | **POST** /oauth2/revoke | Revoke OAuth2 tokens [**updateOAuth2Client**](OAuth2Api.md#updateOAuth2Client) | **PUT** /clients/{id} | Update an OAuth 2.0 Client [**userinfo**](OAuth2Api.md#userinfo) | **POST** /userinfo | OpenID Connect Userinfo [**wellKnown**](OAuth2Api.md#wellKnown) | **GET** /.well-known/jwks.json | Get Well-Known JSON Web Keys -# **acceptOAuth2ConsentRequest** -> acceptOAuth2ConsentRequest($id, $body) +# **acceptConsentRequest** +> \Hydra\SDK\Model\CompletedRequest acceptConsentRequest($challenge, $body) -Accept a consent request +Accept an consent request -Call this endpoint to accept a consent request. This usually happens when a user agrees to give access rights to an application. The consent request id is usually transmitted via the URL query `consent`. For example: `http://consent-app.mydomain.com/?consent=1234abcd` +When an authorization code, hybrid, or implicit OAuth 2.0 Flow is initiated, ORY Hydra asks the login provider to authenticate the user and then tell ORY Hydra now about it. If the user authenticated, he/she must now be asked if the OAuth 2.0 Client which initiated the flow should be allowed to access the resources on the user's behalf. The consent provider which handles this request and is a web app implemented and hosted by you. It shows a user interface which asks the user to grant or deny the client access to the requested scope (\"Application my-dropbox-app wants write access to all your private files\"). The consent challenge is appended to the consent provider's URL to which the user's user-agent (browser) is redirected to. The consent provider uses that challenge to fetch information on the OAuth2 request and then tells ORY Hydra if the user accepted or rejected the request. This endpoint tells ORY Hydra that the user has authorized the OAuth 2.0 client to access resources on his/her behalf. The consent provider includes additional information, such as session data for access and ID tokens, and if the consent request should be used as basis for future requests. The response contains a redirect URL which the consent provider should redirect the user-agent to. ### Example ```php @@ -36,13 +39,14 @@ Call this endpoint to accept a consent request. This usually happens when a user require_once(__DIR__ . '/vendor/autoload.php'); $api_instance = new Hydra\SDK\Api\OAuth2Api(); -$id = "id_example"; // string | -$body = new \Hydra\SDK\Model\ConsentRequestAcceptance(); // \Hydra\SDK\Model\ConsentRequestAcceptance | +$challenge = "challenge_example"; // string | +$body = new \Hydra\SDK\Model\AcceptConsentRequest(); // \Hydra\SDK\Model\AcceptConsentRequest | try { - $api_instance->acceptOAuth2ConsentRequest($id, $body); + $result = $api_instance->acceptConsentRequest($challenge, $body); + print_r($result); } catch (Exception $e) { - echo 'Exception when calling OAuth2Api->acceptOAuth2ConsentRequest: ', $e->getMessage(), PHP_EOL; + echo 'Exception when calling OAuth2Api->acceptConsentRequest: ', $e->getMessage(), PHP_EOL; } ?> ``` @@ -51,12 +55,59 @@ try { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **id** | **string**| | - **body** | [**\Hydra\SDK\Model\ConsentRequestAcceptance**](../Model/ConsentRequestAcceptance.md)| | + **challenge** | **string**| | + **body** | [**\Hydra\SDK\Model\AcceptConsentRequest**](../Model/AcceptConsentRequest.md)| | [optional] ### Return type -void (empty response body) +[**\Hydra\SDK\Model\CompletedRequest**](../Model/CompletedRequest.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) + +# **acceptLoginRequest** +> \Hydra\SDK\Model\CompletedRequest acceptLoginRequest($challenge, $body) + +Accept an login request + +When an authorization code, hybrid, or implicit OAuth 2.0 Flow is initiated, ORY Hydra asks the login provider (sometimes called \"identity provider\") to authenticate the user and then tell ORY Hydra now about it. The login provider is an web-app you write and host, and it must be able to authenticate (\"show the user a login screen\") a user (in OAuth2 the proper name for user is \"resource owner\"). The authentication challenge is appended to the login provider URL to which the user's user-agent (browser) is redirected to. The login provider uses that challenge to fetch information on the OAuth2 request and then accept or reject the requested authentication process. This endpoint tells ORY Hydra that the user has successfully authenticated and includes additional information such as the user's ID and if ORY Hydra should remember the user's user agent for future authentication attempts by setting a cookie. The response contains a redirect URL which the login provider should redirect the user-agent to. + +### Example +```php +acceptLoginRequest($challenge, $body); + print_r($result); +} catch (Exception $e) { + echo 'Exception when calling OAuth2Api->acceptLoginRequest: ', $e->getMessage(), PHP_EOL; +} +?> +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **challenge** | **string**| | + **body** | [**\Hydra\SDK\Model\AcceptLoginRequest**](../Model/AcceptLoginRequest.md)| | [optional] + +### Return type + +[**\Hydra\SDK\Model\CompletedRequest**](../Model/CompletedRequest.md) ### Authorization @@ -202,12 +253,12 @@ No authorization required [[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) -# **getOAuth2Client** -> \Hydra\SDK\Model\OAuth2Client getOAuth2Client($id) +# **getConsentRequest** +> \Hydra\SDK\Model\ConsentRequest getConsentRequest($challenge) -Get an OAuth 2.0 Client. +Get consent request information -Get an OAUth 2.0 client by its ID. This endpoint never returns passwords. OAuth 2.0 clients are used to perform OAuth 2.0 and OpenID Connect flows. Usually, OAuth 2.0 clients are generated for applications which want to consume your OAuth 2.0 or OpenID Connect capabilities. To manage ORY Hydra, you will need an OAuth 2.0 Client as well. Make sure that this endpoint is well protected and only callable by first-party components. +When an authorization code, hybrid, or implicit OAuth 2.0 Flow is initiated, ORY Hydra asks the login provider to authenticate the user and then tell ORY Hydra now about it. If the user authenticated, he/she must now be asked if the OAuth 2.0 Client which initiated the flow should be allowed to access the resources on the user's behalf. The consent provider which handles this request and is a web app implemented and hosted by you. It shows a user interface which asks the user to grant or deny the client access to the requested scope (\"Application my-dropbox-app wants write access to all your private files\"). The consent challenge is appended to the consent provider's URL to which the user's user-agent (browser) is redirected to. The consent provider uses that challenge to fetch information on the OAuth2 request and then tells ORY Hydra if the user accepted or rejected the request. ### Example ```php @@ -215,13 +266,13 @@ Get an OAUth 2.0 client by its ID. This endpoint never returns passwords. OAuth require_once(__DIR__ . '/vendor/autoload.php'); $api_instance = new Hydra\SDK\Api\OAuth2Api(); -$id = "id_example"; // string | The id of the OAuth 2.0 Client. +$challenge = "challenge_example"; // string | try { - $result = $api_instance->getOAuth2Client($id); + $result = $api_instance->getConsentRequest($challenge); print_r($result); } catch (Exception $e) { - echo 'Exception when calling OAuth2Api->getOAuth2Client: ', $e->getMessage(), PHP_EOL; + echo 'Exception when calling OAuth2Api->getConsentRequest: ', $e->getMessage(), PHP_EOL; } ?> ``` @@ -230,11 +281,56 @@ try { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **id** | **string**| The id of the OAuth 2.0 Client. | + **challenge** | **string**| | ### Return type -[**\Hydra\SDK\Model\OAuth2Client**](../Model/OAuth2Client.md) +[**\Hydra\SDK\Model\ConsentRequest**](../Model/ConsentRequest.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) + +# **getLoginRequest** +> \Hydra\SDK\Model\LoginRequest getLoginRequest($challenge) + +Get an login request + +When an authorization code, hybrid, or implicit OAuth 2.0 Flow is initiated, ORY Hydra asks the login provider (sometimes called \"identity provider\") to authenticate the user and then tell ORY Hydra now about it. The login provider is an web-app you write and host, and it must be able to authenticate (\"show the user a login screen\") a user (in OAuth2 the proper name for user is \"resource owner\"). The authentication challenge is appended to the login provider URL to which the user's user-agent (browser) is redirected to. The login provider uses that challenge to fetch information on the OAuth2 request and then accept or reject the requested authentication process. + +### Example +```php +getLoginRequest($challenge); + print_r($result); +} catch (Exception $e) { + echo 'Exception when calling OAuth2Api->getLoginRequest: ', $e->getMessage(), PHP_EOL; +} +?> +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **challenge** | **string**| | + +### Return type + +[**\Hydra\SDK\Model\LoginRequest**](../Model/LoginRequest.md) ### Authorization @@ -247,12 +343,12 @@ No authorization required [[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) -# **getOAuth2ConsentRequest** -> \Hydra\SDK\Model\OAuth2ConsentRequest getOAuth2ConsentRequest($id) +# **getOAuth2Client** +> \Hydra\SDK\Model\OAuth2Client getOAuth2Client($id) -Receive consent request information +Get an OAuth 2.0 Client. -Call this endpoint to receive information on consent requests. The consent request id is usually transmitted via the URL query `consent`. For example: `http://consent-app.mydomain.com/?consent=1234abcd` +Get an OAUth 2.0 client by its ID. This endpoint never returns passwords. OAuth 2.0 clients are used to perform OAuth 2.0 and OpenID Connect flows. Usually, OAuth 2.0 clients are generated for applications which want to consume your OAuth 2.0 or OpenID Connect capabilities. To manage ORY Hydra, you will need an OAuth 2.0 Client as well. Make sure that this endpoint is well protected and only callable by first-party components. ### Example ```php @@ -260,13 +356,13 @@ Call this endpoint to receive information on consent requests. The consent reque require_once(__DIR__ . '/vendor/autoload.php'); $api_instance = new Hydra\SDK\Api\OAuth2Api(); -$id = "id_example"; // string | The id of the OAuth 2.0 Consent Request. +$id = "id_example"; // string | The id of the OAuth 2.0 Client. try { - $result = $api_instance->getOAuth2ConsentRequest($id); + $result = $api_instance->getOAuth2Client($id); print_r($result); } catch (Exception $e) { - echo 'Exception when calling OAuth2Api->getOAuth2ConsentRequest: ', $e->getMessage(), PHP_EOL; + echo 'Exception when calling OAuth2Api->getOAuth2Client: ', $e->getMessage(), PHP_EOL; } ?> ``` @@ -275,11 +371,11 @@ try { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **id** | **string**| The id of the OAuth 2.0 Consent Request. | + **id** | **string**| The id of the OAuth 2.0 Client. | ### Return type -[**\Hydra\SDK\Model\OAuth2ConsentRequest**](../Model/OAuth2ConsentRequest.md) +[**\Hydra\SDK\Model\OAuth2Client**](../Model/OAuth2Client.md) ### Authorization @@ -520,12 +616,12 @@ This endpoint does not need any parameter. [[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) -# **rejectOAuth2ConsentRequest** -> rejectOAuth2ConsentRequest($id, $body) +# **rejectConsentRequest** +> \Hydra\SDK\Model\CompletedRequest rejectConsentRequest($challenge, $body) -Reject a consent request +Reject an consent request -Call this endpoint to reject a consent request. This usually happens when a user denies access rights to an application. The consent request id is usually transmitted via the URL query `consent`. For example: `http://consent-app.mydomain.com/?consent=1234abcd` +When an authorization code, hybrid, or implicit OAuth 2.0 Flow is initiated, ORY Hydra asks the login provider to authenticate the user and then tell ORY Hydra now about it. If the user authenticated, he/she must now be asked if the OAuth 2.0 Client which initiated the flow should be allowed to access the resources on the user's behalf. The consent provider which handles this request and is a web app implemented and hosted by you. It shows a user interface which asks the user to grant or deny the client access to the requested scope (\"Application my-dropbox-app wants write access to all your private files\"). The consent challenge is appended to the consent provider's URL to which the user's user-agent (browser) is redirected to. The consent provider uses that challenge to fetch information on the OAuth2 request and then tells ORY Hydra if the user accepted or rejected the request. This endpoint tells ORY Hydra that the user has not authorized the OAuth 2.0 client to access resources on his/her behalf. The consent provider must include a reason why the consent was not granted. The response contains a redirect URL which the consent provider should redirect the user-agent to. ### Example ```php @@ -533,13 +629,14 @@ Call this endpoint to reject a consent request. This usually happens when a user require_once(__DIR__ . '/vendor/autoload.php'); $api_instance = new Hydra\SDK\Api\OAuth2Api(); -$id = "id_example"; // string | -$body = new \Hydra\SDK\Model\ConsentRequestRejection(); // \Hydra\SDK\Model\ConsentRequestRejection | +$challenge = "challenge_example"; // string | +$body = new \Hydra\SDK\Model\RejectRequest(); // \Hydra\SDK\Model\RejectRequest | try { - $api_instance->rejectOAuth2ConsentRequest($id, $body); + $result = $api_instance->rejectConsentRequest($challenge, $body); + print_r($result); } catch (Exception $e) { - echo 'Exception when calling OAuth2Api->rejectOAuth2ConsentRequest: ', $e->getMessage(), PHP_EOL; + echo 'Exception when calling OAuth2Api->rejectConsentRequest: ', $e->getMessage(), PHP_EOL; } ?> ``` @@ -548,12 +645,59 @@ try { Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **id** | **string**| | - **body** | [**\Hydra\SDK\Model\ConsentRequestRejection**](../Model/ConsentRequestRejection.md)| | + **challenge** | **string**| | + **body** | [**\Hydra\SDK\Model\RejectRequest**](../Model/RejectRequest.md)| | [optional] ### Return type -void (empty response body) +[**\Hydra\SDK\Model\CompletedRequest**](../Model/CompletedRequest.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) + +# **rejectLoginRequest** +> \Hydra\SDK\Model\CompletedRequest rejectLoginRequest($challenge, $body) + +Reject an logout request + +When an authorization code, hybrid, or implicit OAuth 2.0 Flow is initiated, ORY Hydra asks the login provider (sometimes called \"identity provider\") to authenticate the user and then tell ORY Hydra now about it. The login provider is an web-app you write and host, and it must be able to authenticate (\"show the user a login screen\") a user (in OAuth2 the proper name for user is \"resource owner\"). The authentication challenge is appended to the login provider URL to which the user's user-agent (browser) is redirected to. The login provider uses that challenge to fetch information on the OAuth2 request and then accept or reject the requested authentication process. This endpoint tells ORY Hydra that the user has not authenticated and includes a reason why the authentication was be denied. The response contains a redirect URL which the login provider should redirect the user-agent to. + +### Example +```php +rejectLoginRequest($challenge, $body); + print_r($result); +} catch (Exception $e) { + echo 'Exception when calling OAuth2Api->rejectLoginRequest: ', $e->getMessage(), PHP_EOL; +} +?> +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **challenge** | **string**| | + **body** | [**\Hydra\SDK\Model\RejectRequest**](../Model/RejectRequest.md)| | [optional] + +### Return type + +[**\Hydra\SDK\Model\CompletedRequest**](../Model/CompletedRequest.md) ### Authorization diff --git a/sdk/php/swagger/docs/Model/AcceptConsentRequest.md b/sdk/php/swagger/docs/Model/AcceptConsentRequest.md new file mode 100644 index 00000000000..ba740203f57 --- /dev/null +++ b/sdk/php/swagger/docs/Model/AcceptConsentRequest.md @@ -0,0 +1,13 @@ +# AcceptConsentRequest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**grant_scope** | **string[]** | GrantScope sets the scope the user authorized the client to use. Should be a subset of `requested_scope` | [optional] +**remember** | **bool** | Remember, if set to true, tells ORY Hydra to remember this consent authorization and reuse it if the same client asks the same user for the same, or a subset of, scope. | [optional] +**remember_for** | **int** | RememberFor sets how long the consent authorization should be remembered for in seconds. If set to `0`, the authorization will be remembered indefinitely. | [optional] +**session** | [**\Hydra\SDK\Model\ConsentRequestSession**](ConsentRequestSession.md) | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/sdk/php/swagger/docs/Model/AcceptLoginRequest.md b/sdk/php/swagger/docs/Model/AcceptLoginRequest.md new file mode 100644 index 00000000000..64e75cedb5c --- /dev/null +++ b/sdk/php/swagger/docs/Model/AcceptLoginRequest.md @@ -0,0 +1,13 @@ +# AcceptLoginRequest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**acr** | **string** | ACR sets the Authentication AuthorizationContext Class Reference value for this authentication session. You can use it to express that, for example, a user authenticated using two factor authentication. | [optional] +**remember** | **bool** | Remember, if set to true, tells ORY Hydra to remember this user by telling the user agent (browser) to store a cookie with authentication data. If the same user performs another OAuth 2.0 Authorization Request, he/she will not be asked to log in again. | [optional] +**remember_for** | **int** | RememberFor sets how long the authentication should be remembered for in seconds. If set to `0`, the authorization will be remembered indefinitely. | [optional] +**subject** | **string** | Subject is the user ID of the end-user that authenticated. | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/sdk/go/hydra/swagger/docs/SwaggerRejectConsentRequest.md b/sdk/php/swagger/docs/Model/AuthenticationSession.md similarity index 61% rename from sdk/go/hydra/swagger/docs/SwaggerRejectConsentRequest.md rename to sdk/php/swagger/docs/Model/AuthenticationSession.md index 80dc405992a..1c208702b6e 100644 --- a/sdk/go/hydra/swagger/docs/SwaggerRejectConsentRequest.md +++ b/sdk/php/swagger/docs/Model/AuthenticationSession.md @@ -1,10 +1,11 @@ -# SwaggerRejectConsentRequest +# AuthenticationSession ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**Body** | [**ConsentRequestRejection**](consentRequestRejection.md) | | [default to null] -**Id** | **string** | in: path | [default to null] +**authenticated_at** | [**\DateTime**](\DateTime.md) | | [optional] +**id** | **string** | | [optional] +**subject** | **string** | | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/sdk/php/swagger/docs/Model/ConsentRequestManager.md b/sdk/php/swagger/docs/Model/CompletedRequest.md similarity index 61% rename from sdk/php/swagger/docs/Model/ConsentRequestManager.md rename to sdk/php/swagger/docs/Model/CompletedRequest.md index 26f451f4d3a..b171b177f15 100644 --- a/sdk/php/swagger/docs/Model/ConsentRequestManager.md +++ b/sdk/php/swagger/docs/Model/CompletedRequest.md @@ -1,8 +1,9 @@ -# ConsentRequestManager +# CompletedRequest ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- +**redirect_to** | **string** | RedirectURL is the URL which you should redirect the user to once the authentication process is completed. | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/sdk/php/swagger/docs/Model/ConsentRequest.md b/sdk/php/swagger/docs/Model/ConsentRequest.md index 99da11f4c62..bd784f2a898 100644 --- a/sdk/php/swagger/docs/Model/ConsentRequest.md +++ b/sdk/php/swagger/docs/Model/ConsentRequest.md @@ -3,11 +3,13 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**client_id** | **string** | ClientID is the client id that initiated the OAuth2 request. | [optional] -**expires_at** | [**\DateTime**](\DateTime.md) | ExpiresAt is the time where the access request will expire. | [optional] -**id** | **string** | ID is the id of this consent request. | [optional] -**redirect_url** | **string** | Redirect URL is the URL where the user agent should be redirected to after the consent has been accepted or rejected. | [optional] -**requested_scopes** | **string[]** | RequestedScopes represents a list of scopes that have been requested by the OAuth2 request initiator. | [optional] +**challenge** | **string** | Challenge is the identifier (\"authorization challenge\") of the consent authorization request. It is used to identify the session. | [optional] +**client** | [**\Hydra\SDK\Model\OAuth2Client**](OAuth2Client.md) | | [optional] +**oidc_context** | [**\Hydra\SDK\Model\OpenIDConnectContext**](OpenIDConnectContext.md) | | [optional] +**request_url** | **string** | RequestURL is the original OAuth 2.0 Authorization URL requested by the OAuth 2.0 client. It is the URL which initiates the OAuth 2.0 Authorization Code or OAuth 2.0 Implicit flow. This URL is typically not needed, but might come in handy if you want to deal with additional request parameters. | [optional] +**requested_scope** | **string[]** | RequestedScope contains all scopes requested by the OAuth 2.0 client. | [optional] +**skip** | **bool** | Skip, if true, implies that the client has requested the same scopes from the same user previously. If true, you must not ask the user to grant the requested scopes. You must however either allow or deny the consent request using the usual API call. | [optional] +**subject** | **string** | Subject is the user ID of the end-user that authenticated. Now, that end user needs to grant or deny the scope requested by the OAuth 2.0 client. | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/sdk/php/swagger/docs/Model/ConsentRequestAcceptance.md b/sdk/php/swagger/docs/Model/ConsentRequestAcceptance.md deleted file mode 100644 index 4e388ea57a0..00000000000 --- a/sdk/php/swagger/docs/Model/ConsentRequestAcceptance.md +++ /dev/null @@ -1,13 +0,0 @@ -# ConsentRequestAcceptance - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**access_token_extra** | **map[string,object]** | AccessTokenExtra represents arbitrary data that will be added to the access token and that will be returned on introspection and warden requests. | [optional] -**grant_scopes** | **string[]** | A list of scopes that the user agreed to grant. It should be a subset of requestedScopes from the consent request. | [optional] -**id_token_extra** | **map[string,object]** | IDTokenExtra represents arbitrary data that will be added to the ID token. The ID token will only be issued if the user agrees to it and if the client requested an ID token. | [optional] -**subject** | **string** | Subject represents a unique identifier of the user (or service, or legal entity, ...) that accepted the OAuth2 request. | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/sdk/php/swagger/docs/Model/ConsentRequestRejection.md b/sdk/php/swagger/docs/Model/ConsentRequestRejection.md deleted file mode 100644 index 8aadad6825d..00000000000 --- a/sdk/php/swagger/docs/Model/ConsentRequestRejection.md +++ /dev/null @@ -1,10 +0,0 @@ -# ConsentRequestRejection - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**reason** | **string** | Reason represents the reason why the user rejected the consent request. | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/sdk/php/swagger/docs/Model/ConsentRequestSession.md b/sdk/php/swagger/docs/Model/ConsentRequestSession.md new file mode 100644 index 00000000000..0378a6b1dca --- /dev/null +++ b/sdk/php/swagger/docs/Model/ConsentRequestSession.md @@ -0,0 +1,11 @@ +# ConsentRequestSession + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**access_token** | **map[string,object]** | AccessToken sets session data for the access and refresh token, as well as any future tokens issued by the refresh grant. Keep in mind that this data will be available to anyone performing OAuth 2.0 Challenge Introspection. If only your services can perform OAuth 2.0 Challenge Introspection, this is usually fine. But if third parties can access that endpoint as well, sensitive data from the session might be exposed to them. Use with care! | [optional] +**id_token** | **map[string,object]** | IDToken sets session data for the OpenID Connect ID token. Keep in mind that the session'id payloads are readable by anyone that has access to the ID Challenge. Use with care! | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/sdk/php/swagger/docs/Model/Handler.md b/sdk/php/swagger/docs/Model/Handler.md index 5c607f1166a..903e7326394 100644 --- a/sdk/php/swagger/docs/Model/Handler.md +++ b/sdk/php/swagger/docs/Model/Handler.md @@ -3,6 +3,7 @@ ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- +**generators** | [**map[string,\Hydra\SDK\Model\KeyGenerator]**](KeyGenerator.md) | | [optional] **h** | [**\Hydra\SDK\Model\Writer**](Writer.md) | | [optional] **manager** | [**\Hydra\SDK\Model\Manager**](Manager.md) | | [optional] **resource_prefix** | **string** | | [optional] diff --git a/sdk/php/swagger/docs/Model/LoginRequest.md b/sdk/php/swagger/docs/Model/LoginRequest.md new file mode 100644 index 00000000000..9fb65f50fa2 --- /dev/null +++ b/sdk/php/swagger/docs/Model/LoginRequest.md @@ -0,0 +1,16 @@ +# LoginRequest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**challenge** | **string** | Challenge is the identifier (\"authentication challenge\") of the consent authentication request. It is used to identify the session. | [optional] +**client** | [**\Hydra\SDK\Model\OAuth2Client**](OAuth2Client.md) | | [optional] +**oidc_context** | [**\Hydra\SDK\Model\OpenIDConnectContext**](OpenIDConnectContext.md) | | [optional] +**request_url** | **string** | RequestURL is the original OAuth 2.0 Authorization URL requested by the OAuth 2.0 client. It is the URL which initiates the OAuth 2.0 Authorization Code or OAuth 2.0 Implicit flow. This URL is typically not needed, but might come in handy if you want to deal with additional request parameters. | [optional] +**requested_scope** | **string[]** | RequestedScope contains all scopes requested by the OAuth 2.0 client. | [optional] +**skip** | **bool** | Skip, if true, implies that the client has requested the same scopes from the same user previously. If true, you can skip asking the user to grant the requested scopes, and simply forward the user to the redirect URL. This feature allows you to update / set session information. | [optional] +**subject** | **string** | Subject is the user ID of the end-user that authenticated. Now, that end user needs to grant or deny the scope requested by the OAuth 2.0 client. | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/sdk/php/swagger/docs/Model/OAuth2ConsentRequest.md b/sdk/php/swagger/docs/Model/OAuth2ConsentRequest.md deleted file mode 100644 index ab17a4ee958..00000000000 --- a/sdk/php/swagger/docs/Model/OAuth2ConsentRequest.md +++ /dev/null @@ -1,14 +0,0 @@ -# OAuth2ConsentRequest - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**client_id** | **string** | ClientID is the client id that initiated the OAuth2 request. | [optional] -**expires_at** | **string** | ExpiresAt is the time where the access request will expire. | [optional] -**id** | **string** | ID is the id of this consent request. | [optional] -**redirect_url** | **string** | Redirect URL is the URL where the user agent should be redirected to after the consent has been accepted or rejected. | [optional] -**requested_scopes** | **string[]** | RequestedScopes represents a list of scopes that have been requested by the OAuth2 request initiator. | [optional] - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/sdk/php/swagger/docs/Model/OpenIDConnectContext.md b/sdk/php/swagger/docs/Model/OpenIDConnectContext.md new file mode 100644 index 00000000000..fcae5e3fbdd --- /dev/null +++ b/sdk/php/swagger/docs/Model/OpenIDConnectContext.md @@ -0,0 +1,12 @@ +# OpenIDConnectContext + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**acr_values** | **string[]** | ACRValues is the Authentication AuthorizationContext Class Reference requested in the OAuth 2.0 Authorization request. It is a parameter defined by OpenID Connect and expresses which level of authentication (e.g. 2FA) is required. OpenID Connect defines it as follows: > Requested Authentication AuthorizationContext Class Reference values. Space-separated string that specifies the acr values that the Authorization Server is being requested to use for processing this Authentication Request, with the values appearing in order of preference. The Authentication AuthorizationContext Class satisfied by the authentication performed is returned as the acr Claim Value, as specified in Section 2. The acr Claim is requested as a Voluntary Claim by this parameter. | [optional] +**display** | **string** | Display is a string value that specifies how the Authorization Server displays the authentication and consent user interface pages to the End-User. The defined values are: page: The Authorization Server SHOULD display the authentication and consent UI consistent with a full User Agent page view. If the display parameter is not specified, this is the default display mode. popup: The Authorization Server SHOULD display the authentication and consent UI consistent with a popup User Agent window. The popup User Agent window should be of an appropriate size for a login-focused dialog and should not obscure the entire window that it is popping up over. touch: The Authorization Server SHOULD display the authentication and consent UI consistent with a device that leverages a touch interface. wap: The Authorization Server SHOULD display the authentication and consent UI consistent with a \"feature phone\" type display. The Authorization Server MAY also attempt to detect the capabilities of the User Agent and present an appropriate display. | [optional] +**ui_locales** | **string[]** | UILocales is the End-User'id preferred languages and scripts for the user interface, represented as a space-separated list of BCP47 [RFC5646] language tag values, ordered by preference. For instance, the value \"fr-CA fr en\" represents a preference for French as spoken in Canada, then French (without a region designation), followed by English (without a region designation). An error SHOULD NOT result if some or all of the requested locales are not supported by the OpenID Provider. | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/sdk/go/hydra/swagger/docs/ConsentRequestRejection.md b/sdk/php/swagger/docs/Model/RejectRequest.md similarity index 53% rename from sdk/go/hydra/swagger/docs/ConsentRequestRejection.md rename to sdk/php/swagger/docs/Model/RejectRequest.md index 4b245fe779a..8dd449b865d 100644 --- a/sdk/go/hydra/swagger/docs/ConsentRequestRejection.md +++ b/sdk/php/swagger/docs/Model/RejectRequest.md @@ -1,9 +1,13 @@ -# ConsentRequestRejection +# RejectRequest ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**Reason** | **string** | Reason represents the reason why the user rejected the consent request. | [optional] [default to null] +**error** | **string** | | [optional] +**error_debug** | **string** | | [optional] +**error_description** | **string** | | [optional] +**error_hint** | **string** | | [optional] +**status_code** | **int** | | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/sdk/php/swagger/docs/Model/SwaggerAcceptConsentRequest.md b/sdk/php/swagger/docs/Model/SwaggerAcceptConsentRequest.md deleted file mode 100644 index 270615bf31a..00000000000 --- a/sdk/php/swagger/docs/Model/SwaggerAcceptConsentRequest.md +++ /dev/null @@ -1,11 +0,0 @@ -# SwaggerAcceptConsentRequest - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**body** | [**\Hydra\SDK\Model\ConsentRequestAcceptance**](ConsentRequestAcceptance.md) | | -**id** | **string** | in: path | - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/sdk/php/swagger/docs/Model/SwaggerOAuthConsentRequestPayload.md b/sdk/php/swagger/docs/Model/SwaggerOAuthConsentRequestPayload.md deleted file mode 100644 index 099a825c9fc..00000000000 --- a/sdk/php/swagger/docs/Model/SwaggerOAuthConsentRequestPayload.md +++ /dev/null @@ -1,10 +0,0 @@ -# SwaggerOAuthConsentRequestPayload - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**id** | **string** | The id of the OAuth 2.0 Consent Request. | - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/sdk/php/swagger/docs/Model/SwaggerRejectConsentRequest.md b/sdk/php/swagger/docs/Model/SwaggerRejectConsentRequest.md deleted file mode 100644 index 7a6a91c1878..00000000000 --- a/sdk/php/swagger/docs/Model/SwaggerRejectConsentRequest.md +++ /dev/null @@ -1,11 +0,0 @@ -# SwaggerRejectConsentRequest - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**body** | [**\Hydra\SDK\Model\ConsentRequestRejection**](ConsentRequestRejection.md) | | -**id** | **string** | in: path | - -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/sdk/php/swagger/lib/Api/OAuth2Api.php b/sdk/php/swagger/lib/Api/OAuth2Api.php index c218f5f1ccf..3aa96234ebd 100644 --- a/sdk/php/swagger/lib/Api/OAuth2Api.php +++ b/sdk/php/swagger/lib/Api/OAuth2Api.php @@ -88,47 +88,144 @@ public function setApiClient(\Hydra\SDK\ApiClient $apiClient) } /** - * Operation acceptOAuth2ConsentRequest + * Operation acceptConsentRequest * - * Accept a consent request + * Accept an consent request * * Client for Hydra * - * @param string $id (required) - * @param \Hydra\SDK\Model\ConsentRequestAcceptance $body (required) + * @param string $challenge (required) + * @param \Hydra\SDK\Model\AcceptConsentRequest $body (optional) * @throws \Hydra\SDK\ApiException on non-2xx response - * @return void + * @return \Hydra\SDK\Model\CompletedRequest */ - public function acceptOAuth2ConsentRequest($id, $body) + public function acceptConsentRequest($challenge, $body = null) { - list($response) = $this->acceptOAuth2ConsentRequestWithHttpInfo($id, $body); + list($response) = $this->acceptConsentRequestWithHttpInfo($challenge, $body); return $response; } /** - * Operation acceptOAuth2ConsentRequestWithHttpInfo + * Operation acceptConsentRequestWithHttpInfo * - * Accept a consent request + * Accept an consent request * * Client for Hydra * - * @param string $id (required) - * @param \Hydra\SDK\Model\ConsentRequestAcceptance $body (required) + * @param string $challenge (required) + * @param \Hydra\SDK\Model\AcceptConsentRequest $body (optional) * @throws \Hydra\SDK\ApiException on non-2xx response - * @return array of null, HTTP status code, HTTP response headers (array of strings) + * @return array of \Hydra\SDK\Model\CompletedRequest, HTTP status code, HTTP response headers (array of strings) */ - public function acceptOAuth2ConsentRequestWithHttpInfo($id, $body) + public function acceptConsentRequestWithHttpInfo($challenge, $body = null) { - // verify the required parameter 'id' is set - if ($id === null) { - throw new \InvalidArgumentException('Missing the required parameter $id when calling acceptOAuth2ConsentRequest'); + // verify the required parameter 'challenge' is set + if ($challenge === null) { + throw new \InvalidArgumentException('Missing the required parameter $challenge when calling acceptConsentRequest'); } - // verify the required parameter 'body' is set - if ($body === null) { - throw new \InvalidArgumentException('Missing the required parameter $body when calling acceptOAuth2ConsentRequest'); + // parse inputs + $resourcePath = "/oauth2/auth/requests/consent/{challenge}/accept"; + $httpBody = ''; + $queryParams = []; + $headerParams = []; + $formParams = []; + $_header_accept = $this->apiClient->selectHeaderAccept(['application/json']); + if (!is_null($_header_accept)) { + $headerParams['Accept'] = $_header_accept; + } + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(['application/json']); + + // path params + if ($challenge !== null) { + $resourcePath = str_replace( + "{" . "challenge" . "}", + $this->apiClient->getSerializer()->toPathValue($challenge), + $resourcePath + ); + } + // body params + $_tempBody = null; + if (isset($body)) { + $_tempBody = $body; + } + + // for model (json/xml) + if (isset($_tempBody)) { + $httpBody = $_tempBody; // $_tempBody is the method argument, if present + } elseif (count($formParams) > 0) { + $httpBody = $formParams; // for HTTP post (form) + } + // make the API Call + try { + list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( + $resourcePath, + 'PUT', + $queryParams, + $httpBody, + $headerParams, + '\Hydra\SDK\Model\CompletedRequest', + '/oauth2/auth/requests/consent/{challenge}/accept' + ); + + return [$this->apiClient->getSerializer()->deserialize($response, '\Hydra\SDK\Model\CompletedRequest', $httpHeader), $statusCode, $httpHeader]; + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Hydra\SDK\Model\CompletedRequest', $e->getResponseHeaders()); + $e->setResponseObject($data); + break; + case 401: + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Hydra\SDK\Model\InlineResponse401', $e->getResponseHeaders()); + $e->setResponseObject($data); + break; + case 500: + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Hydra\SDK\Model\InlineResponse401', $e->getResponseHeaders()); + $e->setResponseObject($data); + break; + } + + throw $e; + } + } + + /** + * Operation acceptLoginRequest + * + * Accept an login request + * + * Client for Hydra + * + * @param string $challenge (required) + * @param \Hydra\SDK\Model\AcceptLoginRequest $body (optional) + * @throws \Hydra\SDK\ApiException on non-2xx response + * @return \Hydra\SDK\Model\CompletedRequest + */ + public function acceptLoginRequest($challenge, $body = null) + { + list($response) = $this->acceptLoginRequestWithHttpInfo($challenge, $body); + return $response; + } + + /** + * Operation acceptLoginRequestWithHttpInfo + * + * Accept an login request + * + * Client for Hydra + * + * @param string $challenge (required) + * @param \Hydra\SDK\Model\AcceptLoginRequest $body (optional) + * @throws \Hydra\SDK\ApiException on non-2xx response + * @return array of \Hydra\SDK\Model\CompletedRequest, HTTP status code, HTTP response headers (array of strings) + */ + public function acceptLoginRequestWithHttpInfo($challenge, $body = null) + { + // verify the required parameter 'challenge' is set + if ($challenge === null) { + throw new \InvalidArgumentException('Missing the required parameter $challenge when calling acceptLoginRequest'); } // parse inputs - $resourcePath = "/oauth2/consent/requests/{id}/accept"; + $resourcePath = "/oauth2/auth/requests/login/{challenge}/accept"; $httpBody = ''; $queryParams = []; $headerParams = []; @@ -140,10 +237,10 @@ public function acceptOAuth2ConsentRequestWithHttpInfo($id, $body) $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(['application/json']); // path params - if ($id !== null) { + if ($challenge !== null) { $resourcePath = str_replace( - "{" . "id" . "}", - $this->apiClient->getSerializer()->toPathValue($id), + "{" . "challenge" . "}", + $this->apiClient->getSerializer()->toPathValue($challenge), $resourcePath ); } @@ -163,17 +260,21 @@ public function acceptOAuth2ConsentRequestWithHttpInfo($id, $body) try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( $resourcePath, - 'PATCH', + 'PUT', $queryParams, $httpBody, $headerParams, - null, - '/oauth2/consent/requests/{id}/accept' + '\Hydra\SDK\Model\CompletedRequest', + '/oauth2/auth/requests/login/{challenge}/accept' ); - return [null, $statusCode, $httpHeader]; + return [$this->apiClient->getSerializer()->deserialize($response, '\Hydra\SDK\Model\CompletedRequest', $httpHeader), $statusCode, $httpHeader]; } catch (ApiException $e) { switch ($e->getCode()) { + case 200: + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Hydra\SDK\Model\CompletedRequest', $e->getResponseHeaders()); + $e->setResponseObject($data); + break; case 401: $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Hydra\SDK\Model\InlineResponse401', $e->getResponseHeaders()); $e->setResponseObject($data); @@ -461,41 +562,41 @@ public function flushInactiveOAuth2TokensWithHttpInfo($body = null) } /** - * Operation getOAuth2Client + * Operation getConsentRequest * - * Get an OAuth 2.0 Client. + * Get consent request information * * Client for Hydra * - * @param string $id The id of the OAuth 2.0 Client. (required) + * @param string $challenge (required) * @throws \Hydra\SDK\ApiException on non-2xx response - * @return \Hydra\SDK\Model\OAuth2Client + * @return \Hydra\SDK\Model\ConsentRequest */ - public function getOAuth2Client($id) + public function getConsentRequest($challenge) { - list($response) = $this->getOAuth2ClientWithHttpInfo($id); + list($response) = $this->getConsentRequestWithHttpInfo($challenge); return $response; } /** - * Operation getOAuth2ClientWithHttpInfo + * Operation getConsentRequestWithHttpInfo * - * Get an OAuth 2.0 Client. + * Get consent request information * * Client for Hydra * - * @param string $id The id of the OAuth 2.0 Client. (required) + * @param string $challenge (required) * @throws \Hydra\SDK\ApiException on non-2xx response - * @return array of \Hydra\SDK\Model\OAuth2Client, HTTP status code, HTTP response headers (array of strings) + * @return array of \Hydra\SDK\Model\ConsentRequest, HTTP status code, HTTP response headers (array of strings) */ - public function getOAuth2ClientWithHttpInfo($id) + public function getConsentRequestWithHttpInfo($challenge) { - // verify the required parameter 'id' is set - if ($id === null) { - throw new \InvalidArgumentException('Missing the required parameter $id when calling getOAuth2Client'); + // verify the required parameter 'challenge' is set + if ($challenge === null) { + throw new \InvalidArgumentException('Missing the required parameter $challenge when calling getConsentRequest'); } // parse inputs - $resourcePath = "/clients/{id}"; + $resourcePath = "/oauth2/auth/requests/consent/{challenge}"; $httpBody = ''; $queryParams = []; $headerParams = []; @@ -507,10 +608,10 @@ public function getOAuth2ClientWithHttpInfo($id) $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(['application/json']); // path params - if ($id !== null) { + if ($challenge !== null) { $resourcePath = str_replace( - "{" . "id" . "}", - $this->apiClient->getSerializer()->toPathValue($id), + "{" . "challenge" . "}", + $this->apiClient->getSerializer()->toPathValue($challenge), $resourcePath ); } @@ -529,22 +630,112 @@ public function getOAuth2ClientWithHttpInfo($id) $queryParams, $httpBody, $headerParams, - '\Hydra\SDK\Model\OAuth2Client', - '/clients/{id}' + '\Hydra\SDK\Model\ConsentRequest', + '/oauth2/auth/requests/consent/{challenge}' ); - return [$this->apiClient->getSerializer()->deserialize($response, '\Hydra\SDK\Model\OAuth2Client', $httpHeader), $statusCode, $httpHeader]; + return [$this->apiClient->getSerializer()->deserialize($response, '\Hydra\SDK\Model\ConsentRequest', $httpHeader), $statusCode, $httpHeader]; } catch (ApiException $e) { switch ($e->getCode()) { case 200: - $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Hydra\SDK\Model\OAuth2Client', $e->getResponseHeaders()); + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Hydra\SDK\Model\ConsentRequest', $e->getResponseHeaders()); $e->setResponseObject($data); break; case 401: $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Hydra\SDK\Model\InlineResponse401', $e->getResponseHeaders()); $e->setResponseObject($data); break; - case 403: + case 500: + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Hydra\SDK\Model\InlineResponse401', $e->getResponseHeaders()); + $e->setResponseObject($data); + break; + } + + throw $e; + } + } + + /** + * Operation getLoginRequest + * + * Get an login request + * + * Client for Hydra + * + * @param string $challenge (required) + * @throws \Hydra\SDK\ApiException on non-2xx response + * @return \Hydra\SDK\Model\LoginRequest + */ + public function getLoginRequest($challenge) + { + list($response) = $this->getLoginRequestWithHttpInfo($challenge); + return $response; + } + + /** + * Operation getLoginRequestWithHttpInfo + * + * Get an login request + * + * Client for Hydra + * + * @param string $challenge (required) + * @throws \Hydra\SDK\ApiException on non-2xx response + * @return array of \Hydra\SDK\Model\LoginRequest, HTTP status code, HTTP response headers (array of strings) + */ + public function getLoginRequestWithHttpInfo($challenge) + { + // verify the required parameter 'challenge' is set + if ($challenge === null) { + throw new \InvalidArgumentException('Missing the required parameter $challenge when calling getLoginRequest'); + } + // parse inputs + $resourcePath = "/oauth2/auth/requests/login/{challenge}"; + $httpBody = ''; + $queryParams = []; + $headerParams = []; + $formParams = []; + $_header_accept = $this->apiClient->selectHeaderAccept(['application/json']); + if (!is_null($_header_accept)) { + $headerParams['Accept'] = $_header_accept; + } + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(['application/json']); + + // path params + if ($challenge !== null) { + $resourcePath = str_replace( + "{" . "challenge" . "}", + $this->apiClient->getSerializer()->toPathValue($challenge), + $resourcePath + ); + } + + // for model (json/xml) + if (isset($_tempBody)) { + $httpBody = $_tempBody; // $_tempBody is the method argument, if present + } elseif (count($formParams) > 0) { + $httpBody = $formParams; // for HTTP post (form) + } + // make the API Call + try { + list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( + $resourcePath, + 'GET', + $queryParams, + $httpBody, + $headerParams, + '\Hydra\SDK\Model\LoginRequest', + '/oauth2/auth/requests/login/{challenge}' + ); + + return [$this->apiClient->getSerializer()->deserialize($response, '\Hydra\SDK\Model\LoginRequest', $httpHeader), $statusCode, $httpHeader]; + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Hydra\SDK\Model\LoginRequest', $e->getResponseHeaders()); + $e->setResponseObject($data); + break; + case 401: $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Hydra\SDK\Model\InlineResponse401', $e->getResponseHeaders()); $e->setResponseObject($data); break; @@ -559,41 +750,41 @@ public function getOAuth2ClientWithHttpInfo($id) } /** - * Operation getOAuth2ConsentRequest + * Operation getOAuth2Client * - * Receive consent request information + * Get an OAuth 2.0 Client. * * Client for Hydra * - * @param string $id The id of the OAuth 2.0 Consent Request. (required) + * @param string $id The id of the OAuth 2.0 Client. (required) * @throws \Hydra\SDK\ApiException on non-2xx response - * @return \Hydra\SDK\Model\OAuth2ConsentRequest + * @return \Hydra\SDK\Model\OAuth2Client */ - public function getOAuth2ConsentRequest($id) + public function getOAuth2Client($id) { - list($response) = $this->getOAuth2ConsentRequestWithHttpInfo($id); + list($response) = $this->getOAuth2ClientWithHttpInfo($id); return $response; } /** - * Operation getOAuth2ConsentRequestWithHttpInfo + * Operation getOAuth2ClientWithHttpInfo * - * Receive consent request information + * Get an OAuth 2.0 Client. * * Client for Hydra * - * @param string $id The id of the OAuth 2.0 Consent Request. (required) + * @param string $id The id of the OAuth 2.0 Client. (required) * @throws \Hydra\SDK\ApiException on non-2xx response - * @return array of \Hydra\SDK\Model\OAuth2ConsentRequest, HTTP status code, HTTP response headers (array of strings) + * @return array of \Hydra\SDK\Model\OAuth2Client, HTTP status code, HTTP response headers (array of strings) */ - public function getOAuth2ConsentRequestWithHttpInfo($id) + public function getOAuth2ClientWithHttpInfo($id) { // verify the required parameter 'id' is set if ($id === null) { - throw new \InvalidArgumentException('Missing the required parameter $id when calling getOAuth2ConsentRequest'); + throw new \InvalidArgumentException('Missing the required parameter $id when calling getOAuth2Client'); } // parse inputs - $resourcePath = "/oauth2/consent/requests/{id}"; + $resourcePath = "/clients/{id}"; $httpBody = ''; $queryParams = []; $headerParams = []; @@ -627,21 +818,25 @@ public function getOAuth2ConsentRequestWithHttpInfo($id) $queryParams, $httpBody, $headerParams, - '\Hydra\SDK\Model\OAuth2ConsentRequest', - '/oauth2/consent/requests/{id}' + '\Hydra\SDK\Model\OAuth2Client', + '/clients/{id}' ); - return [$this->apiClient->getSerializer()->deserialize($response, '\Hydra\SDK\Model\OAuth2ConsentRequest', $httpHeader), $statusCode, $httpHeader]; + return [$this->apiClient->getSerializer()->deserialize($response, '\Hydra\SDK\Model\OAuth2Client', $httpHeader), $statusCode, $httpHeader]; } catch (ApiException $e) { switch ($e->getCode()) { case 200: - $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Hydra\SDK\Model\OAuth2ConsentRequest', $e->getResponseHeaders()); + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Hydra\SDK\Model\OAuth2Client', $e->getResponseHeaders()); $e->setResponseObject($data); break; case 401: $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Hydra\SDK\Model\InlineResponse401', $e->getResponseHeaders()); $e->setResponseObject($data); break; + case 403: + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Hydra\SDK\Model\InlineResponse401', $e->getResponseHeaders()); + $e->setResponseObject($data); + break; case 500: $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Hydra\SDK\Model\InlineResponse401', $e->getResponseHeaders()); $e->setResponseObject($data); @@ -1097,47 +1292,144 @@ public function oauthTokenWithHttpInfo() } /** - * Operation rejectOAuth2ConsentRequest + * Operation rejectConsentRequest * - * Reject a consent request + * Reject an consent request * * Client for Hydra * - * @param string $id (required) - * @param \Hydra\SDK\Model\ConsentRequestRejection $body (required) + * @param string $challenge (required) + * @param \Hydra\SDK\Model\RejectRequest $body (optional) * @throws \Hydra\SDK\ApiException on non-2xx response - * @return void + * @return \Hydra\SDK\Model\CompletedRequest */ - public function rejectOAuth2ConsentRequest($id, $body) + public function rejectConsentRequest($challenge, $body = null) { - list($response) = $this->rejectOAuth2ConsentRequestWithHttpInfo($id, $body); + list($response) = $this->rejectConsentRequestWithHttpInfo($challenge, $body); return $response; } /** - * Operation rejectOAuth2ConsentRequestWithHttpInfo + * Operation rejectConsentRequestWithHttpInfo * - * Reject a consent request + * Reject an consent request * * Client for Hydra * - * @param string $id (required) - * @param \Hydra\SDK\Model\ConsentRequestRejection $body (required) + * @param string $challenge (required) + * @param \Hydra\SDK\Model\RejectRequest $body (optional) * @throws \Hydra\SDK\ApiException on non-2xx response - * @return array of null, HTTP status code, HTTP response headers (array of strings) + * @return array of \Hydra\SDK\Model\CompletedRequest, HTTP status code, HTTP response headers (array of strings) */ - public function rejectOAuth2ConsentRequestWithHttpInfo($id, $body) + public function rejectConsentRequestWithHttpInfo($challenge, $body = null) { - // verify the required parameter 'id' is set - if ($id === null) { - throw new \InvalidArgumentException('Missing the required parameter $id when calling rejectOAuth2ConsentRequest'); + // verify the required parameter 'challenge' is set + if ($challenge === null) { + throw new \InvalidArgumentException('Missing the required parameter $challenge when calling rejectConsentRequest'); } - // verify the required parameter 'body' is set - if ($body === null) { - throw new \InvalidArgumentException('Missing the required parameter $body when calling rejectOAuth2ConsentRequest'); + // parse inputs + $resourcePath = "/oauth2/auth/requests/consent/{challenge}/reject"; + $httpBody = ''; + $queryParams = []; + $headerParams = []; + $formParams = []; + $_header_accept = $this->apiClient->selectHeaderAccept(['application/json']); + if (!is_null($_header_accept)) { + $headerParams['Accept'] = $_header_accept; + } + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(['application/json']); + + // path params + if ($challenge !== null) { + $resourcePath = str_replace( + "{" . "challenge" . "}", + $this->apiClient->getSerializer()->toPathValue($challenge), + $resourcePath + ); + } + // body params + $_tempBody = null; + if (isset($body)) { + $_tempBody = $body; + } + + // for model (json/xml) + if (isset($_tempBody)) { + $httpBody = $_tempBody; // $_tempBody is the method argument, if present + } elseif (count($formParams) > 0) { + $httpBody = $formParams; // for HTTP post (form) + } + // make the API Call + try { + list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( + $resourcePath, + 'PUT', + $queryParams, + $httpBody, + $headerParams, + '\Hydra\SDK\Model\CompletedRequest', + '/oauth2/auth/requests/consent/{challenge}/reject' + ); + + return [$this->apiClient->getSerializer()->deserialize($response, '\Hydra\SDK\Model\CompletedRequest', $httpHeader), $statusCode, $httpHeader]; + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Hydra\SDK\Model\CompletedRequest', $e->getResponseHeaders()); + $e->setResponseObject($data); + break; + case 401: + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Hydra\SDK\Model\InlineResponse401', $e->getResponseHeaders()); + $e->setResponseObject($data); + break; + case 500: + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Hydra\SDK\Model\InlineResponse401', $e->getResponseHeaders()); + $e->setResponseObject($data); + break; + } + + throw $e; + } + } + + /** + * Operation rejectLoginRequest + * + * Reject an logout request + * + * Client for Hydra + * + * @param string $challenge (required) + * @param \Hydra\SDK\Model\RejectRequest $body (optional) + * @throws \Hydra\SDK\ApiException on non-2xx response + * @return \Hydra\SDK\Model\CompletedRequest + */ + public function rejectLoginRequest($challenge, $body = null) + { + list($response) = $this->rejectLoginRequestWithHttpInfo($challenge, $body); + return $response; + } + + /** + * Operation rejectLoginRequestWithHttpInfo + * + * Reject an logout request + * + * Client for Hydra + * + * @param string $challenge (required) + * @param \Hydra\SDK\Model\RejectRequest $body (optional) + * @throws \Hydra\SDK\ApiException on non-2xx response + * @return array of \Hydra\SDK\Model\CompletedRequest, HTTP status code, HTTP response headers (array of strings) + */ + public function rejectLoginRequestWithHttpInfo($challenge, $body = null) + { + // verify the required parameter 'challenge' is set + if ($challenge === null) { + throw new \InvalidArgumentException('Missing the required parameter $challenge when calling rejectLoginRequest'); } // parse inputs - $resourcePath = "/oauth2/consent/requests/{id}/reject"; + $resourcePath = "/oauth2/auth/requests/login/{challenge}/reject"; $httpBody = ''; $queryParams = []; $headerParams = []; @@ -1149,10 +1441,10 @@ public function rejectOAuth2ConsentRequestWithHttpInfo($id, $body) $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(['application/json']); // path params - if ($id !== null) { + if ($challenge !== null) { $resourcePath = str_replace( - "{" . "id" . "}", - $this->apiClient->getSerializer()->toPathValue($id), + "{" . "challenge" . "}", + $this->apiClient->getSerializer()->toPathValue($challenge), $resourcePath ); } @@ -1172,17 +1464,21 @@ public function rejectOAuth2ConsentRequestWithHttpInfo($id, $body) try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( $resourcePath, - 'PATCH', + 'PUT', $queryParams, $httpBody, $headerParams, - null, - '/oauth2/consent/requests/{id}/reject' + '\Hydra\SDK\Model\CompletedRequest', + '/oauth2/auth/requests/login/{challenge}/reject' ); - return [null, $statusCode, $httpHeader]; + return [$this->apiClient->getSerializer()->deserialize($response, '\Hydra\SDK\Model\CompletedRequest', $httpHeader), $statusCode, $httpHeader]; } catch (ApiException $e) { switch ($e->getCode()) { + case 200: + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Hydra\SDK\Model\CompletedRequest', $e->getResponseHeaders()); + $e->setResponseObject($data); + break; case 401: $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Hydra\SDK\Model\InlineResponse401', $e->getResponseHeaders()); $e->setResponseObject($data); diff --git a/sdk/php/swagger/lib/Model/AcceptConsentRequest.php b/sdk/php/swagger/lib/Model/AcceptConsentRequest.php new file mode 100644 index 00000000000..c54891a3080 --- /dev/null +++ b/sdk/php/swagger/lib/Model/AcceptConsentRequest.php @@ -0,0 +1,323 @@ + 'string[]', + 'remember' => 'bool', + 'remember_for' => 'int', + 'session' => '\Hydra\SDK\Model\ConsentRequestSession' + ]; + + /** + * Array of property to format mappings. Used for (de)serialization + * @var string[] + */ + protected static $swaggerFormats = [ + 'grant_scope' => null, + 'remember' => null, + 'remember_for' => 'int64', + 'session' => null + ]; + + public static function swaggerTypes() + { + return self::$swaggerTypes; + } + + public static function swaggerFormats() + { + return self::$swaggerFormats; + } + + /** + * Array of attributes where the key is the local name, and the value is the original name + * @var string[] + */ + protected static $attributeMap = [ + 'grant_scope' => 'grant_scope', + 'remember' => 'remember', + 'remember_for' => 'remember_for', + 'session' => 'session' + ]; + + + /** + * Array of attributes to setter functions (for deserialization of responses) + * @var string[] + */ + protected static $setters = [ + 'grant_scope' => 'setGrantScope', + 'remember' => 'setRemember', + 'remember_for' => 'setRememberFor', + 'session' => 'setSession' + ]; + + + /** + * Array of attributes to getter functions (for serialization of requests) + * @var string[] + */ + protected static $getters = [ + 'grant_scope' => 'getGrantScope', + 'remember' => 'getRemember', + 'remember_for' => 'getRememberFor', + 'session' => 'getSession' + ]; + + public static function attributeMap() + { + return self::$attributeMap; + } + + public static function setters() + { + return self::$setters; + } + + public static function getters() + { + return self::$getters; + } + + + + + + /** + * Associative array for storing property values + * @var mixed[] + */ + protected $container = []; + + /** + * Constructor + * @param mixed[] $data Associated array of property values initializing the model + */ + public function __construct(array $data = null) + { + $this->container['grant_scope'] = isset($data['grant_scope']) ? $data['grant_scope'] : null; + $this->container['remember'] = isset($data['remember']) ? $data['remember'] : null; + $this->container['remember_for'] = isset($data['remember_for']) ? $data['remember_for'] : null; + $this->container['session'] = isset($data['session']) ? $data['session'] : null; + } + + /** + * show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function listInvalidProperties() + { + $invalid_properties = []; + + return $invalid_properties; + } + + /** + * validate all the properties in the model + * return true if all passed + * + * @return bool True if all properties are valid + */ + public function valid() + { + + return true; + } + + + /** + * Gets grant_scope + * @return string[] + */ + public function getGrantScope() + { + return $this->container['grant_scope']; + } + + /** + * Sets grant_scope + * @param string[] $grant_scope GrantScope sets the scope the user authorized the client to use. Should be a subset of `requested_scope` + * @return $this + */ + public function setGrantScope($grant_scope) + { + $this->container['grant_scope'] = $grant_scope; + + return $this; + } + + /** + * Gets remember + * @return bool + */ + public function getRemember() + { + return $this->container['remember']; + } + + /** + * Sets remember + * @param bool $remember Remember, if set to true, tells ORY Hydra to remember this consent authorization and reuse it if the same client asks the same user for the same, or a subset of, scope. + * @return $this + */ + public function setRemember($remember) + { + $this->container['remember'] = $remember; + + return $this; + } + + /** + * Gets remember_for + * @return int + */ + public function getRememberFor() + { + return $this->container['remember_for']; + } + + /** + * Sets remember_for + * @param int $remember_for RememberFor sets how long the consent authorization should be remembered for in seconds. If set to `0`, the authorization will be remembered indefinitely. + * @return $this + */ + public function setRememberFor($remember_for) + { + $this->container['remember_for'] = $remember_for; + + return $this; + } + + /** + * Gets session + * @return \Hydra\SDK\Model\ConsentRequestSession + */ + public function getSession() + { + return $this->container['session']; + } + + /** + * Sets session + * @param \Hydra\SDK\Model\ConsentRequestSession $session + * @return $this + */ + public function setSession($session) + { + $this->container['session'] = $session; + + return $this; + } + /** + * Returns true if offset exists. False otherwise. + * @param integer $offset Offset + * @return boolean + */ + public function offsetExists($offset) + { + return isset($this->container[$offset]); + } + + /** + * Gets offset. + * @param integer $offset Offset + * @return mixed + */ + public function offsetGet($offset) + { + return isset($this->container[$offset]) ? $this->container[$offset] : null; + } + + /** + * Sets value based on offset. + * @param integer $offset Offset + * @param mixed $value Value to be set + * @return void + */ + public function offsetSet($offset, $value) + { + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + /** + * Unsets offset. + * @param integer $offset Offset + * @return void + */ + public function offsetUnset($offset) + { + unset($this->container[$offset]); + } + + /** + * Gets the string presentation of the object + * @return string + */ + public function __toString() + { + if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print + return json_encode(\Hydra\SDK\ObjectSerializer::sanitizeForSerialization($this), JSON_PRETTY_PRINT); + } + + return json_encode(\Hydra\SDK\ObjectSerializer::sanitizeForSerialization($this)); + } +} + + diff --git a/sdk/php/swagger/lib/Model/ConsentRequestAcceptance.php b/sdk/php/swagger/lib/Model/AcceptLoginRequest.php similarity index 66% rename from sdk/php/swagger/lib/Model/ConsentRequestAcceptance.php rename to sdk/php/swagger/lib/Model/AcceptLoginRequest.php index 4c996c3b6a0..ae0e5548a08 100644 --- a/sdk/php/swagger/lib/Model/ConsentRequestAcceptance.php +++ b/sdk/php/swagger/lib/Model/AcceptLoginRequest.php @@ -1,6 +1,6 @@ 'map[string,object]', - 'grant_scopes' => 'string[]', - 'id_token_extra' => 'map[string,object]', + 'acr' => 'string', + 'remember' => 'bool', + 'remember_for' => 'int', 'subject' => 'string' ]; @@ -65,9 +65,9 @@ class ConsentRequestAcceptance implements ArrayAccess * @var string[] */ protected static $swaggerFormats = [ - 'access_token_extra' => null, - 'grant_scopes' => null, - 'id_token_extra' => null, + 'acr' => null, + 'remember' => null, + 'remember_for' => 'int64', 'subject' => null ]; @@ -86,9 +86,9 @@ public static function swaggerFormats() * @var string[] */ protected static $attributeMap = [ - 'access_token_extra' => 'accessTokenExtra', - 'grant_scopes' => 'grantScopes', - 'id_token_extra' => 'idTokenExtra', + 'acr' => 'acr', + 'remember' => 'remember', + 'remember_for' => 'remember_for', 'subject' => 'subject' ]; @@ -98,9 +98,9 @@ public static function swaggerFormats() * @var string[] */ protected static $setters = [ - 'access_token_extra' => 'setAccessTokenExtra', - 'grant_scopes' => 'setGrantScopes', - 'id_token_extra' => 'setIdTokenExtra', + 'acr' => 'setAcr', + 'remember' => 'setRemember', + 'remember_for' => 'setRememberFor', 'subject' => 'setSubject' ]; @@ -110,9 +110,9 @@ public static function swaggerFormats() * @var string[] */ protected static $getters = [ - 'access_token_extra' => 'getAccessTokenExtra', - 'grant_scopes' => 'getGrantScopes', - 'id_token_extra' => 'getIdTokenExtra', + 'acr' => 'getAcr', + 'remember' => 'getRemember', + 'remember_for' => 'getRememberFor', 'subject' => 'getSubject' ]; @@ -147,9 +147,9 @@ public static function getters() */ public function __construct(array $data = null) { - $this->container['access_token_extra'] = isset($data['access_token_extra']) ? $data['access_token_extra'] : null; - $this->container['grant_scopes'] = isset($data['grant_scopes']) ? $data['grant_scopes'] : null; - $this->container['id_token_extra'] = isset($data['id_token_extra']) ? $data['id_token_extra'] : null; + $this->container['acr'] = isset($data['acr']) ? $data['acr'] : null; + $this->container['remember'] = isset($data['remember']) ? $data['remember'] : null; + $this->container['remember_for'] = isset($data['remember_for']) ? $data['remember_for'] : null; $this->container['subject'] = isset($data['subject']) ? $data['subject'] : null; } @@ -179,64 +179,64 @@ public function valid() /** - * Gets access_token_extra - * @return map[string,object] + * Gets acr + * @return string */ - public function getAccessTokenExtra() + public function getAcr() { - return $this->container['access_token_extra']; + return $this->container['acr']; } /** - * Sets access_token_extra - * @param map[string,object] $access_token_extra AccessTokenExtra represents arbitrary data that will be added to the access token and that will be returned on introspection and warden requests. + * Sets acr + * @param string $acr ACR sets the Authentication AuthorizationContext Class Reference value for this authentication session. You can use it to express that, for example, a user authenticated using two factor authentication. * @return $this */ - public function setAccessTokenExtra($access_token_extra) + public function setAcr($acr) { - $this->container['access_token_extra'] = $access_token_extra; + $this->container['acr'] = $acr; return $this; } /** - * Gets grant_scopes - * @return string[] + * Gets remember + * @return bool */ - public function getGrantScopes() + public function getRemember() { - return $this->container['grant_scopes']; + return $this->container['remember']; } /** - * Sets grant_scopes - * @param string[] $grant_scopes A list of scopes that the user agreed to grant. It should be a subset of requestedScopes from the consent request. + * Sets remember + * @param bool $remember Remember, if set to true, tells ORY Hydra to remember this user by telling the user agent (browser) to store a cookie with authentication data. If the same user performs another OAuth 2.0 Authorization Request, he/she will not be asked to log in again. * @return $this */ - public function setGrantScopes($grant_scopes) + public function setRemember($remember) { - $this->container['grant_scopes'] = $grant_scopes; + $this->container['remember'] = $remember; return $this; } /** - * Gets id_token_extra - * @return map[string,object] + * Gets remember_for + * @return int */ - public function getIdTokenExtra() + public function getRememberFor() { - return $this->container['id_token_extra']; + return $this->container['remember_for']; } /** - * Sets id_token_extra - * @param map[string,object] $id_token_extra IDTokenExtra represents arbitrary data that will be added to the ID token. The ID token will only be issued if the user agrees to it and if the client requested an ID token. + * Sets remember_for + * @param int $remember_for RememberFor sets how long the authentication should be remembered for in seconds. If set to `0`, the authorization will be remembered indefinitely. * @return $this */ - public function setIdTokenExtra($id_token_extra) + public function setRememberFor($remember_for) { - $this->container['id_token_extra'] = $id_token_extra; + $this->container['remember_for'] = $remember_for; return $this; } @@ -252,7 +252,7 @@ public function getSubject() /** * Sets subject - * @param string $subject Subject represents a unique identifier of the user (or service, or legal entity, ...) that accepted the OAuth2 request. + * @param string $subject Subject is the user ID of the end-user that authenticated. * @return $this */ public function setSubject($subject) diff --git a/sdk/php/swagger/lib/Model/SwaggerRejectConsentRequest.php b/sdk/php/swagger/lib/Model/AuthenticationSession.php similarity index 75% rename from sdk/php/swagger/lib/Model/SwaggerRejectConsentRequest.php rename to sdk/php/swagger/lib/Model/AuthenticationSession.php index 5ed927a88a9..10366c04b16 100644 --- a/sdk/php/swagger/lib/Model/SwaggerRejectConsentRequest.php +++ b/sdk/php/swagger/lib/Model/AuthenticationSession.php @@ -1,6 +1,6 @@ '\Hydra\SDK\Model\ConsentRequestRejection', - 'id' => 'string' + 'authenticated_at' => '\DateTime', + 'id' => 'string', + 'subject' => 'string' ]; /** @@ -63,8 +64,9 @@ class SwaggerRejectConsentRequest implements ArrayAccess * @var string[] */ protected static $swaggerFormats = [ - 'body' => null, - 'id' => null + 'authenticated_at' => 'date-time', + 'id' => null, + 'subject' => null ]; public static function swaggerTypes() @@ -82,8 +84,9 @@ public static function swaggerFormats() * @var string[] */ protected static $attributeMap = [ - 'body' => 'Body', - 'id' => 'id' + 'authenticated_at' => 'AuthenticatedAt', + 'id' => 'ID', + 'subject' => 'Subject' ]; @@ -92,8 +95,9 @@ public static function swaggerFormats() * @var string[] */ protected static $setters = [ - 'body' => 'setBody', - 'id' => 'setId' + 'authenticated_at' => 'setAuthenticatedAt', + 'id' => 'setId', + 'subject' => 'setSubject' ]; @@ -102,8 +106,9 @@ public static function swaggerFormats() * @var string[] */ protected static $getters = [ - 'body' => 'getBody', - 'id' => 'getId' + 'authenticated_at' => 'getAuthenticatedAt', + 'id' => 'getId', + 'subject' => 'getSubject' ]; public static function attributeMap() @@ -137,8 +142,9 @@ public static function getters() */ public function __construct(array $data = null) { - $this->container['body'] = isset($data['body']) ? $data['body'] : null; + $this->container['authenticated_at'] = isset($data['authenticated_at']) ? $data['authenticated_at'] : null; $this->container['id'] = isset($data['id']) ? $data['id'] : null; + $this->container['subject'] = isset($data['subject']) ? $data['subject'] : null; } /** @@ -150,12 +156,6 @@ public function listInvalidProperties() { $invalid_properties = []; - if ($this->container['body'] === null) { - $invalid_properties[] = "'body' can't be null"; - } - if ($this->container['id'] === null) { - $invalid_properties[] = "'id' can't be null"; - } return $invalid_properties; } @@ -168,33 +168,27 @@ public function listInvalidProperties() public function valid() { - if ($this->container['body'] === null) { - return false; - } - if ($this->container['id'] === null) { - return false; - } return true; } /** - * Gets body - * @return \Hydra\SDK\Model\ConsentRequestRejection + * Gets authenticated_at + * @return \DateTime */ - public function getBody() + public function getAuthenticatedAt() { - return $this->container['body']; + return $this->container['authenticated_at']; } /** - * Sets body - * @param \Hydra\SDK\Model\ConsentRequestRejection $body + * Sets authenticated_at + * @param \DateTime $authenticated_at * @return $this */ - public function setBody($body) + public function setAuthenticatedAt($authenticated_at) { - $this->container['body'] = $body; + $this->container['authenticated_at'] = $authenticated_at; return $this; } @@ -210,7 +204,7 @@ public function getId() /** * Sets id - * @param string $id in: path + * @param string $id * @return $this */ public function setId($id) @@ -219,6 +213,27 @@ public function setId($id) return $this; } + + /** + * Gets subject + * @return string + */ + public function getSubject() + { + return $this->container['subject']; + } + + /** + * Sets subject + * @param string $subject + * @return $this + */ + public function setSubject($subject) + { + $this->container['subject'] = $subject; + + return $this; + } /** * Returns true if offset exists. False otherwise. * @param integer $offset Offset diff --git a/sdk/php/swagger/lib/Model/ConsentRequestRejection.php b/sdk/php/swagger/lib/Model/CompletedRequest.php similarity index 85% rename from sdk/php/swagger/lib/Model/ConsentRequestRejection.php rename to sdk/php/swagger/lib/Model/CompletedRequest.php index 225318e7907..90b0ef57727 100644 --- a/sdk/php/swagger/lib/Model/ConsentRequestRejection.php +++ b/sdk/php/swagger/lib/Model/CompletedRequest.php @@ -1,6 +1,6 @@ 'string' + 'redirect_to' => 'string' ]; /** @@ -62,7 +62,7 @@ class ConsentRequestRejection implements ArrayAccess * @var string[] */ protected static $swaggerFormats = [ - 'reason' => null + 'redirect_to' => null ]; public static function swaggerTypes() @@ -80,7 +80,7 @@ public static function swaggerFormats() * @var string[] */ protected static $attributeMap = [ - 'reason' => 'reason' + 'redirect_to' => 'redirect_to' ]; @@ -89,7 +89,7 @@ public static function swaggerFormats() * @var string[] */ protected static $setters = [ - 'reason' => 'setReason' + 'redirect_to' => 'setRedirectTo' ]; @@ -98,7 +98,7 @@ public static function swaggerFormats() * @var string[] */ protected static $getters = [ - 'reason' => 'getReason' + 'redirect_to' => 'getRedirectTo' ]; public static function attributeMap() @@ -132,7 +132,7 @@ public static function getters() */ public function __construct(array $data = null) { - $this->container['reason'] = isset($data['reason']) ? $data['reason'] : null; + $this->container['redirect_to'] = isset($data['redirect_to']) ? $data['redirect_to'] : null; } /** @@ -161,22 +161,22 @@ public function valid() /** - * Gets reason + * Gets redirect_to * @return string */ - public function getReason() + public function getRedirectTo() { - return $this->container['reason']; + return $this->container['redirect_to']; } /** - * Sets reason - * @param string $reason Reason represents the reason why the user rejected the consent request. + * Sets redirect_to + * @param string $redirect_to RedirectURL is the URL which you should redirect the user to once the authentication process is completed. * @return $this */ - public function setReason($reason) + public function setRedirectTo($redirect_to) { - $this->container['reason'] = $reason; + $this->container['redirect_to'] = $redirect_to; return $this; } diff --git a/sdk/php/swagger/lib/Model/ConsentRequest.php b/sdk/php/swagger/lib/Model/ConsentRequest.php index 7e912d0983a..134e4df14a0 100644 --- a/sdk/php/swagger/lib/Model/ConsentRequest.php +++ b/sdk/php/swagger/lib/Model/ConsentRequest.php @@ -47,18 +47,20 @@ class ConsentRequest implements ArrayAccess * The original name of the model. * @var string */ - protected static $swaggerModelName = 'ConsentRequest'; + protected static $swaggerModelName = 'consentRequest'; /** * Array of property to type mappings. Used for (de)serialization * @var string[] */ protected static $swaggerTypes = [ - 'client_id' => 'string', - 'expires_at' => '\DateTime', - 'id' => 'string', - 'redirect_url' => 'string', - 'requested_scopes' => 'string[]' + 'challenge' => 'string', + 'client' => '\Hydra\SDK\Model\OAuth2Client', + 'oidc_context' => '\Hydra\SDK\Model\OpenIDConnectContext', + 'request_url' => 'string', + 'requested_scope' => 'string[]', + 'skip' => 'bool', + 'subject' => 'string' ]; /** @@ -66,11 +68,13 @@ class ConsentRequest implements ArrayAccess * @var string[] */ protected static $swaggerFormats = [ - 'client_id' => null, - 'expires_at' => 'date-time', - 'id' => null, - 'redirect_url' => null, - 'requested_scopes' => null + 'challenge' => null, + 'client' => null, + 'oidc_context' => null, + 'request_url' => null, + 'requested_scope' => null, + 'skip' => null, + 'subject' => null ]; public static function swaggerTypes() @@ -88,11 +92,13 @@ public static function swaggerFormats() * @var string[] */ protected static $attributeMap = [ - 'client_id' => 'clientId', - 'expires_at' => 'expiresAt', - 'id' => 'id', - 'redirect_url' => 'redirectUrl', - 'requested_scopes' => 'requestedScopes' + 'challenge' => 'challenge', + 'client' => 'client', + 'oidc_context' => 'oidc_context', + 'request_url' => 'request_url', + 'requested_scope' => 'requested_scope', + 'skip' => 'skip', + 'subject' => 'subject' ]; @@ -101,11 +107,13 @@ public static function swaggerFormats() * @var string[] */ protected static $setters = [ - 'client_id' => 'setClientId', - 'expires_at' => 'setExpiresAt', - 'id' => 'setId', - 'redirect_url' => 'setRedirectUrl', - 'requested_scopes' => 'setRequestedScopes' + 'challenge' => 'setChallenge', + 'client' => 'setClient', + 'oidc_context' => 'setOidcContext', + 'request_url' => 'setRequestUrl', + 'requested_scope' => 'setRequestedScope', + 'skip' => 'setSkip', + 'subject' => 'setSubject' ]; @@ -114,11 +122,13 @@ public static function swaggerFormats() * @var string[] */ protected static $getters = [ - 'client_id' => 'getClientId', - 'expires_at' => 'getExpiresAt', - 'id' => 'getId', - 'redirect_url' => 'getRedirectUrl', - 'requested_scopes' => 'getRequestedScopes' + 'challenge' => 'getChallenge', + 'client' => 'getClient', + 'oidc_context' => 'getOidcContext', + 'request_url' => 'getRequestUrl', + 'requested_scope' => 'getRequestedScope', + 'skip' => 'getSkip', + 'subject' => 'getSubject' ]; public static function attributeMap() @@ -152,11 +162,13 @@ public static function getters() */ public function __construct(array $data = null) { - $this->container['client_id'] = isset($data['client_id']) ? $data['client_id'] : null; - $this->container['expires_at'] = isset($data['expires_at']) ? $data['expires_at'] : null; - $this->container['id'] = isset($data['id']) ? $data['id'] : null; - $this->container['redirect_url'] = isset($data['redirect_url']) ? $data['redirect_url'] : null; - $this->container['requested_scopes'] = isset($data['requested_scopes']) ? $data['requested_scopes'] : null; + $this->container['challenge'] = isset($data['challenge']) ? $data['challenge'] : null; + $this->container['client'] = isset($data['client']) ? $data['client'] : null; + $this->container['oidc_context'] = isset($data['oidc_context']) ? $data['oidc_context'] : null; + $this->container['request_url'] = isset($data['request_url']) ? $data['request_url'] : null; + $this->container['requested_scope'] = isset($data['requested_scope']) ? $data['requested_scope'] : null; + $this->container['skip'] = isset($data['skip']) ? $data['skip'] : null; + $this->container['subject'] = isset($data['subject']) ? $data['subject'] : null; } /** @@ -185,106 +197,148 @@ public function valid() /** - * Gets client_id + * Gets challenge * @return string */ - public function getClientId() + public function getChallenge() { - return $this->container['client_id']; + return $this->container['challenge']; } /** - * Sets client_id - * @param string $client_id ClientID is the client id that initiated the OAuth2 request. + * Sets challenge + * @param string $challenge Challenge is the identifier (\"authorization challenge\") of the consent authorization request. It is used to identify the session. * @return $this */ - public function setClientId($client_id) + public function setChallenge($challenge) { - $this->container['client_id'] = $client_id; + $this->container['challenge'] = $challenge; return $this; } /** - * Gets expires_at - * @return \DateTime + * Gets client + * @return \Hydra\SDK\Model\OAuth2Client */ - public function getExpiresAt() + public function getClient() { - return $this->container['expires_at']; + return $this->container['client']; } /** - * Sets expires_at - * @param \DateTime $expires_at ExpiresAt is the time where the access request will expire. + * Sets client + * @param \Hydra\SDK\Model\OAuth2Client $client * @return $this */ - public function setExpiresAt($expires_at) + public function setClient($client) { - $this->container['expires_at'] = $expires_at; + $this->container['client'] = $client; return $this; } /** - * Gets id - * @return string + * Gets oidc_context + * @return \Hydra\SDK\Model\OpenIDConnectContext */ - public function getId() + public function getOidcContext() { - return $this->container['id']; + return $this->container['oidc_context']; } /** - * Sets id - * @param string $id ID is the id of this consent request. + * Sets oidc_context + * @param \Hydra\SDK\Model\OpenIDConnectContext $oidc_context * @return $this */ - public function setId($id) + public function setOidcContext($oidc_context) { - $this->container['id'] = $id; + $this->container['oidc_context'] = $oidc_context; return $this; } /** - * Gets redirect_url + * Gets request_url * @return string */ - public function getRedirectUrl() + public function getRequestUrl() { - return $this->container['redirect_url']; + return $this->container['request_url']; } /** - * Sets redirect_url - * @param string $redirect_url Redirect URL is the URL where the user agent should be redirected to after the consent has been accepted or rejected. + * Sets request_url + * @param string $request_url RequestURL is the original OAuth 2.0 Authorization URL requested by the OAuth 2.0 client. It is the URL which initiates the OAuth 2.0 Authorization Code or OAuth 2.0 Implicit flow. This URL is typically not needed, but might come in handy if you want to deal with additional request parameters. * @return $this */ - public function setRedirectUrl($redirect_url) + public function setRequestUrl($request_url) { - $this->container['redirect_url'] = $redirect_url; + $this->container['request_url'] = $request_url; return $this; } /** - * Gets requested_scopes + * Gets requested_scope * @return string[] */ - public function getRequestedScopes() + public function getRequestedScope() + { + return $this->container['requested_scope']; + } + + /** + * Sets requested_scope + * @param string[] $requested_scope RequestedScope contains all scopes requested by the OAuth 2.0 client. + * @return $this + */ + public function setRequestedScope($requested_scope) + { + $this->container['requested_scope'] = $requested_scope; + + return $this; + } + + /** + * Gets skip + * @return bool + */ + public function getSkip() + { + return $this->container['skip']; + } + + /** + * Sets skip + * @param bool $skip Skip, if true, implies that the client has requested the same scopes from the same user previously. If true, you must not ask the user to grant the requested scopes. You must however either allow or deny the consent request using the usual API call. + * @return $this + */ + public function setSkip($skip) + { + $this->container['skip'] = $skip; + + return $this; + } + + /** + * Gets subject + * @return string + */ + public function getSubject() { - return $this->container['requested_scopes']; + return $this->container['subject']; } /** - * Sets requested_scopes - * @param string[] $requested_scopes RequestedScopes represents a list of scopes that have been requested by the OAuth2 request initiator. + * Sets subject + * @param string $subject Subject is the user ID of the end-user that authenticated. Now, that end user needs to grant or deny the scope requested by the OAuth 2.0 client. * @return $this */ - public function setRequestedScopes($requested_scopes) + public function setSubject($subject) { - $this->container['requested_scopes'] = $requested_scopes; + $this->container['subject'] = $subject; return $this; } diff --git a/sdk/php/swagger/lib/Model/ConsentRequestManager.php b/sdk/php/swagger/lib/Model/ConsentRequestManager.php deleted file mode 100644 index c6c20aba583..00000000000 --- a/sdk/php/swagger/lib/Model/ConsentRequestManager.php +++ /dev/null @@ -1,220 +0,0 @@ -container[$offset]); - } - - /** - * Gets offset. - * @param integer $offset Offset - * @return mixed - */ - public function offsetGet($offset) - { - return isset($this->container[$offset]) ? $this->container[$offset] : null; - } - - /** - * Sets value based on offset. - * @param integer $offset Offset - * @param mixed $value Value to be set - * @return void - */ - public function offsetSet($offset, $value) - { - if (is_null($offset)) { - $this->container[] = $value; - } else { - $this->container[$offset] = $value; - } - } - - /** - * Unsets offset. - * @param integer $offset Offset - * @return void - */ - public function offsetUnset($offset) - { - unset($this->container[$offset]); - } - - /** - * Gets the string presentation of the object - * @return string - */ - public function __toString() - { - if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print - return json_encode(\Hydra\SDK\ObjectSerializer::sanitizeForSerialization($this), JSON_PRETTY_PRINT); - } - - return json_encode(\Hydra\SDK\ObjectSerializer::sanitizeForSerialization($this)); - } -} - - diff --git a/sdk/php/swagger/lib/Model/SwaggerAcceptConsentRequest.php b/sdk/php/swagger/lib/Model/ConsentRequestSession.php similarity index 70% rename from sdk/php/swagger/lib/Model/SwaggerAcceptConsentRequest.php rename to sdk/php/swagger/lib/Model/ConsentRequestSession.php index 91c25957c51..5597b9a0954 100644 --- a/sdk/php/swagger/lib/Model/SwaggerAcceptConsentRequest.php +++ b/sdk/php/swagger/lib/Model/ConsentRequestSession.php @@ -1,6 +1,6 @@ '\Hydra\SDK\Model\ConsentRequestAcceptance', - 'id' => 'string' + 'access_token' => 'map[string,object]', + 'id_token' => 'map[string,object]' ]; /** @@ -63,8 +63,8 @@ class SwaggerAcceptConsentRequest implements ArrayAccess * @var string[] */ protected static $swaggerFormats = [ - 'body' => null, - 'id' => null + 'access_token' => null, + 'id_token' => null ]; public static function swaggerTypes() @@ -82,8 +82,8 @@ public static function swaggerFormats() * @var string[] */ protected static $attributeMap = [ - 'body' => 'Body', - 'id' => 'id' + 'access_token' => 'access_token', + 'id_token' => 'id_token' ]; @@ -92,8 +92,8 @@ public static function swaggerFormats() * @var string[] */ protected static $setters = [ - 'body' => 'setBody', - 'id' => 'setId' + 'access_token' => 'setAccessToken', + 'id_token' => 'setIdToken' ]; @@ -102,8 +102,8 @@ public static function swaggerFormats() * @var string[] */ protected static $getters = [ - 'body' => 'getBody', - 'id' => 'getId' + 'access_token' => 'getAccessToken', + 'id_token' => 'getIdToken' ]; public static function attributeMap() @@ -137,8 +137,8 @@ public static function getters() */ public function __construct(array $data = null) { - $this->container['body'] = isset($data['body']) ? $data['body'] : null; - $this->container['id'] = isset($data['id']) ? $data['id'] : null; + $this->container['access_token'] = isset($data['access_token']) ? $data['access_token'] : null; + $this->container['id_token'] = isset($data['id_token']) ? $data['id_token'] : null; } /** @@ -150,12 +150,6 @@ public function listInvalidProperties() { $invalid_properties = []; - if ($this->container['body'] === null) { - $invalid_properties[] = "'body' can't be null"; - } - if ($this->container['id'] === null) { - $invalid_properties[] = "'id' can't be null"; - } return $invalid_properties; } @@ -168,54 +162,48 @@ public function listInvalidProperties() public function valid() { - if ($this->container['body'] === null) { - return false; - } - if ($this->container['id'] === null) { - return false; - } return true; } /** - * Gets body - * @return \Hydra\SDK\Model\ConsentRequestAcceptance + * Gets access_token + * @return map[string,object] */ - public function getBody() + public function getAccessToken() { - return $this->container['body']; + return $this->container['access_token']; } /** - * Sets body - * @param \Hydra\SDK\Model\ConsentRequestAcceptance $body + * Sets access_token + * @param map[string,object] $access_token AccessToken sets session data for the access and refresh token, as well as any future tokens issued by the refresh grant. Keep in mind that this data will be available to anyone performing OAuth 2.0 Challenge Introspection. If only your services can perform OAuth 2.0 Challenge Introspection, this is usually fine. But if third parties can access that endpoint as well, sensitive data from the session might be exposed to them. Use with care! * @return $this */ - public function setBody($body) + public function setAccessToken($access_token) { - $this->container['body'] = $body; + $this->container['access_token'] = $access_token; return $this; } /** - * Gets id - * @return string + * Gets id_token + * @return map[string,object] */ - public function getId() + public function getIdToken() { - return $this->container['id']; + return $this->container['id_token']; } /** - * Sets id - * @param string $id in: path + * Sets id_token + * @param map[string,object] $id_token IDToken sets session data for the OpenID Connect ID token. Keep in mind that the session'id payloads are readable by anyone that has access to the ID Challenge. Use with care! * @return $this */ - public function setId($id) + public function setIdToken($id_token) { - $this->container['id'] = $id; + $this->container['id_token'] = $id_token; return $this; } diff --git a/sdk/php/swagger/lib/Model/Handler.php b/sdk/php/swagger/lib/Model/Handler.php index 4100bda208a..f2a667c1434 100644 --- a/sdk/php/swagger/lib/Model/Handler.php +++ b/sdk/php/swagger/lib/Model/Handler.php @@ -54,6 +54,7 @@ class Handler implements ArrayAccess * @var string[] */ protected static $swaggerTypes = [ + 'generators' => 'map[string,\Hydra\SDK\Model\KeyGenerator]', 'h' => '\Hydra\SDK\Model\Writer', 'manager' => '\Hydra\SDK\Model\Manager', 'resource_prefix' => 'string' @@ -64,6 +65,7 @@ class Handler implements ArrayAccess * @var string[] */ protected static $swaggerFormats = [ + 'generators' => null, 'h' => null, 'manager' => null, 'resource_prefix' => null @@ -84,6 +86,7 @@ public static function swaggerFormats() * @var string[] */ protected static $attributeMap = [ + 'generators' => 'Generators', 'h' => 'H', 'manager' => 'Manager', 'resource_prefix' => 'ResourcePrefix' @@ -95,6 +98,7 @@ public static function swaggerFormats() * @var string[] */ protected static $setters = [ + 'generators' => 'setGenerators', 'h' => 'setH', 'manager' => 'setManager', 'resource_prefix' => 'setResourcePrefix' @@ -106,6 +110,7 @@ public static function swaggerFormats() * @var string[] */ protected static $getters = [ + 'generators' => 'getGenerators', 'h' => 'getH', 'manager' => 'getManager', 'resource_prefix' => 'getResourcePrefix' @@ -142,6 +147,7 @@ public static function getters() */ public function __construct(array $data = null) { + $this->container['generators'] = isset($data['generators']) ? $data['generators'] : null; $this->container['h'] = isset($data['h']) ? $data['h'] : null; $this->container['manager'] = isset($data['manager']) ? $data['manager'] : null; $this->container['resource_prefix'] = isset($data['resource_prefix']) ? $data['resource_prefix'] : null; @@ -172,6 +178,27 @@ public function valid() } + /** + * Gets generators + * @return map[string,\Hydra\SDK\Model\KeyGenerator] + */ + public function getGenerators() + { + return $this->container['generators']; + } + + /** + * Sets generators + * @param map[string,\Hydra\SDK\Model\KeyGenerator] $generators + * @return $this + */ + public function setGenerators($generators) + { + $this->container['generators'] = $generators; + + return $this; + } + /** * Gets h * @return \Hydra\SDK\Model\Writer diff --git a/sdk/php/swagger/lib/Model/LoginRequest.php b/sdk/php/swagger/lib/Model/LoginRequest.php new file mode 100644 index 00000000000..d7537cab273 --- /dev/null +++ b/sdk/php/swagger/lib/Model/LoginRequest.php @@ -0,0 +1,404 @@ + 'string', + 'client' => '\Hydra\SDK\Model\OAuth2Client', + 'oidc_context' => '\Hydra\SDK\Model\OpenIDConnectContext', + 'request_url' => 'string', + 'requested_scope' => 'string[]', + 'skip' => 'bool', + 'subject' => 'string' + ]; + + /** + * Array of property to format mappings. Used for (de)serialization + * @var string[] + */ + protected static $swaggerFormats = [ + 'challenge' => null, + 'client' => null, + 'oidc_context' => null, + 'request_url' => null, + 'requested_scope' => null, + 'skip' => null, + 'subject' => null + ]; + + public static function swaggerTypes() + { + return self::$swaggerTypes; + } + + public static function swaggerFormats() + { + return self::$swaggerFormats; + } + + /** + * Array of attributes where the key is the local name, and the value is the original name + * @var string[] + */ + protected static $attributeMap = [ + 'challenge' => 'challenge', + 'client' => 'client', + 'oidc_context' => 'oidc_context', + 'request_url' => 'request_url', + 'requested_scope' => 'requested_scope', + 'skip' => 'skip', + 'subject' => 'subject' + ]; + + + /** + * Array of attributes to setter functions (for deserialization of responses) + * @var string[] + */ + protected static $setters = [ + 'challenge' => 'setChallenge', + 'client' => 'setClient', + 'oidc_context' => 'setOidcContext', + 'request_url' => 'setRequestUrl', + 'requested_scope' => 'setRequestedScope', + 'skip' => 'setSkip', + 'subject' => 'setSubject' + ]; + + + /** + * Array of attributes to getter functions (for serialization of requests) + * @var string[] + */ + protected static $getters = [ + 'challenge' => 'getChallenge', + 'client' => 'getClient', + 'oidc_context' => 'getOidcContext', + 'request_url' => 'getRequestUrl', + 'requested_scope' => 'getRequestedScope', + 'skip' => 'getSkip', + 'subject' => 'getSubject' + ]; + + public static function attributeMap() + { + return self::$attributeMap; + } + + public static function setters() + { + return self::$setters; + } + + public static function getters() + { + return self::$getters; + } + + + + + + /** + * Associative array for storing property values + * @var mixed[] + */ + protected $container = []; + + /** + * Constructor + * @param mixed[] $data Associated array of property values initializing the model + */ + public function __construct(array $data = null) + { + $this->container['challenge'] = isset($data['challenge']) ? $data['challenge'] : null; + $this->container['client'] = isset($data['client']) ? $data['client'] : null; + $this->container['oidc_context'] = isset($data['oidc_context']) ? $data['oidc_context'] : null; + $this->container['request_url'] = isset($data['request_url']) ? $data['request_url'] : null; + $this->container['requested_scope'] = isset($data['requested_scope']) ? $data['requested_scope'] : null; + $this->container['skip'] = isset($data['skip']) ? $data['skip'] : null; + $this->container['subject'] = isset($data['subject']) ? $data['subject'] : null; + } + + /** + * show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function listInvalidProperties() + { + $invalid_properties = []; + + return $invalid_properties; + } + + /** + * validate all the properties in the model + * return true if all passed + * + * @return bool True if all properties are valid + */ + public function valid() + { + + return true; + } + + + /** + * Gets challenge + * @return string + */ + public function getChallenge() + { + return $this->container['challenge']; + } + + /** + * Sets challenge + * @param string $challenge Challenge is the identifier (\"authentication challenge\") of the consent authentication request. It is used to identify the session. + * @return $this + */ + public function setChallenge($challenge) + { + $this->container['challenge'] = $challenge; + + return $this; + } + + /** + * Gets client + * @return \Hydra\SDK\Model\OAuth2Client + */ + public function getClient() + { + return $this->container['client']; + } + + /** + * Sets client + * @param \Hydra\SDK\Model\OAuth2Client $client + * @return $this + */ + public function setClient($client) + { + $this->container['client'] = $client; + + return $this; + } + + /** + * Gets oidc_context + * @return \Hydra\SDK\Model\OpenIDConnectContext + */ + public function getOidcContext() + { + return $this->container['oidc_context']; + } + + /** + * Sets oidc_context + * @param \Hydra\SDK\Model\OpenIDConnectContext $oidc_context + * @return $this + */ + public function setOidcContext($oidc_context) + { + $this->container['oidc_context'] = $oidc_context; + + return $this; + } + + /** + * Gets request_url + * @return string + */ + public function getRequestUrl() + { + return $this->container['request_url']; + } + + /** + * Sets request_url + * @param string $request_url RequestURL is the original OAuth 2.0 Authorization URL requested by the OAuth 2.0 client. It is the URL which initiates the OAuth 2.0 Authorization Code or OAuth 2.0 Implicit flow. This URL is typically not needed, but might come in handy if you want to deal with additional request parameters. + * @return $this + */ + public function setRequestUrl($request_url) + { + $this->container['request_url'] = $request_url; + + return $this; + } + + /** + * Gets requested_scope + * @return string[] + */ + public function getRequestedScope() + { + return $this->container['requested_scope']; + } + + /** + * Sets requested_scope + * @param string[] $requested_scope RequestedScope contains all scopes requested by the OAuth 2.0 client. + * @return $this + */ + public function setRequestedScope($requested_scope) + { + $this->container['requested_scope'] = $requested_scope; + + return $this; + } + + /** + * Gets skip + * @return bool + */ + public function getSkip() + { + return $this->container['skip']; + } + + /** + * Sets skip + * @param bool $skip Skip, if true, implies that the client has requested the same scopes from the same user previously. If true, you can skip asking the user to grant the requested scopes, and simply forward the user to the redirect URL. This feature allows you to update / set session information. + * @return $this + */ + public function setSkip($skip) + { + $this->container['skip'] = $skip; + + return $this; + } + + /** + * Gets subject + * @return string + */ + public function getSubject() + { + return $this->container['subject']; + } + + /** + * Sets subject + * @param string $subject Subject is the user ID of the end-user that authenticated. Now, that end user needs to grant or deny the scope requested by the OAuth 2.0 client. + * @return $this + */ + public function setSubject($subject) + { + $this->container['subject'] = $subject; + + return $this; + } + /** + * Returns true if offset exists. False otherwise. + * @param integer $offset Offset + * @return boolean + */ + public function offsetExists($offset) + { + return isset($this->container[$offset]); + } + + /** + * Gets offset. + * @param integer $offset Offset + * @return mixed + */ + public function offsetGet($offset) + { + return isset($this->container[$offset]) ? $this->container[$offset] : null; + } + + /** + * Sets value based on offset. + * @param integer $offset Offset + * @param mixed $value Value to be set + * @return void + */ + public function offsetSet($offset, $value) + { + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + /** + * Unsets offset. + * @param integer $offset Offset + * @return void + */ + public function offsetUnset($offset) + { + unset($this->container[$offset]); + } + + /** + * Gets the string presentation of the object + * @return string + */ + public function __toString() + { + if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print + return json_encode(\Hydra\SDK\ObjectSerializer::sanitizeForSerialization($this), JSON_PRETTY_PRINT); + } + + return json_encode(\Hydra\SDK\ObjectSerializer::sanitizeForSerialization($this)); + } +} + + diff --git a/sdk/php/swagger/lib/Model/OpenIDConnectContext.php b/sdk/php/swagger/lib/Model/OpenIDConnectContext.php new file mode 100644 index 00000000000..8ebeb0b268d --- /dev/null +++ b/sdk/php/swagger/lib/Model/OpenIDConnectContext.php @@ -0,0 +1,296 @@ + 'string[]', + 'display' => 'string', + 'ui_locales' => 'string[]' + ]; + + /** + * Array of property to format mappings. Used for (de)serialization + * @var string[] + */ + protected static $swaggerFormats = [ + 'acr_values' => null, + 'display' => null, + 'ui_locales' => null + ]; + + public static function swaggerTypes() + { + return self::$swaggerTypes; + } + + public static function swaggerFormats() + { + return self::$swaggerFormats; + } + + /** + * Array of attributes where the key is the local name, and the value is the original name + * @var string[] + */ + protected static $attributeMap = [ + 'acr_values' => 'acr_values', + 'display' => 'display', + 'ui_locales' => 'ui_locales' + ]; + + + /** + * Array of attributes to setter functions (for deserialization of responses) + * @var string[] + */ + protected static $setters = [ + 'acr_values' => 'setAcrValues', + 'display' => 'setDisplay', + 'ui_locales' => 'setUiLocales' + ]; + + + /** + * Array of attributes to getter functions (for serialization of requests) + * @var string[] + */ + protected static $getters = [ + 'acr_values' => 'getAcrValues', + 'display' => 'getDisplay', + 'ui_locales' => 'getUiLocales' + ]; + + public static function attributeMap() + { + return self::$attributeMap; + } + + public static function setters() + { + return self::$setters; + } + + public static function getters() + { + return self::$getters; + } + + + + + + /** + * Associative array for storing property values + * @var mixed[] + */ + protected $container = []; + + /** + * Constructor + * @param mixed[] $data Associated array of property values initializing the model + */ + public function __construct(array $data = null) + { + $this->container['acr_values'] = isset($data['acr_values']) ? $data['acr_values'] : null; + $this->container['display'] = isset($data['display']) ? $data['display'] : null; + $this->container['ui_locales'] = isset($data['ui_locales']) ? $data['ui_locales'] : null; + } + + /** + * show all the invalid properties with reasons. + * + * @return array invalid properties with reasons + */ + public function listInvalidProperties() + { + $invalid_properties = []; + + return $invalid_properties; + } + + /** + * validate all the properties in the model + * return true if all passed + * + * @return bool True if all properties are valid + */ + public function valid() + { + + return true; + } + + + /** + * Gets acr_values + * @return string[] + */ + public function getAcrValues() + { + return $this->container['acr_values']; + } + + /** + * Sets acr_values + * @param string[] $acr_values ACRValues is the Authentication AuthorizationContext Class Reference requested in the OAuth 2.0 Authorization request. It is a parameter defined by OpenID Connect and expresses which level of authentication (e.g. 2FA) is required. OpenID Connect defines it as follows: > Requested Authentication AuthorizationContext Class Reference values. Space-separated string that specifies the acr values that the Authorization Server is being requested to use for processing this Authentication Request, with the values appearing in order of preference. The Authentication AuthorizationContext Class satisfied by the authentication performed is returned as the acr Claim Value, as specified in Section 2. The acr Claim is requested as a Voluntary Claim by this parameter. + * @return $this + */ + public function setAcrValues($acr_values) + { + $this->container['acr_values'] = $acr_values; + + return $this; + } + + /** + * Gets display + * @return string + */ + public function getDisplay() + { + return $this->container['display']; + } + + /** + * Sets display + * @param string $display Display is a string value that specifies how the Authorization Server displays the authentication and consent user interface pages to the End-User. The defined values are: page: The Authorization Server SHOULD display the authentication and consent UI consistent with a full User Agent page view. If the display parameter is not specified, this is the default display mode. popup: The Authorization Server SHOULD display the authentication and consent UI consistent with a popup User Agent window. The popup User Agent window should be of an appropriate size for a login-focused dialog and should not obscure the entire window that it is popping up over. touch: The Authorization Server SHOULD display the authentication and consent UI consistent with a device that leverages a touch interface. wap: The Authorization Server SHOULD display the authentication and consent UI consistent with a \"feature phone\" type display. The Authorization Server MAY also attempt to detect the capabilities of the User Agent and present an appropriate display. + * @return $this + */ + public function setDisplay($display) + { + $this->container['display'] = $display; + + return $this; + } + + /** + * Gets ui_locales + * @return string[] + */ + public function getUiLocales() + { + return $this->container['ui_locales']; + } + + /** + * Sets ui_locales + * @param string[] $ui_locales UILocales is the End-User'id preferred languages and scripts for the user interface, represented as a space-separated list of BCP47 [RFC5646] language tag values, ordered by preference. For instance, the value \"fr-CA fr en\" represents a preference for French as spoken in Canada, then French (without a region designation), followed by English (without a region designation). An error SHOULD NOT result if some or all of the requested locales are not supported by the OpenID Provider. + * @return $this + */ + public function setUiLocales($ui_locales) + { + $this->container['ui_locales'] = $ui_locales; + + return $this; + } + /** + * Returns true if offset exists. False otherwise. + * @param integer $offset Offset + * @return boolean + */ + public function offsetExists($offset) + { + return isset($this->container[$offset]); + } + + /** + * Gets offset. + * @param integer $offset Offset + * @return mixed + */ + public function offsetGet($offset) + { + return isset($this->container[$offset]) ? $this->container[$offset] : null; + } + + /** + * Sets value based on offset. + * @param integer $offset Offset + * @param mixed $value Value to be set + * @return void + */ + public function offsetSet($offset, $value) + { + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + /** + * Unsets offset. + * @param integer $offset Offset + * @return void + */ + public function offsetUnset($offset) + { + unset($this->container[$offset]); + } + + /** + * Gets the string presentation of the object + * @return string + */ + public function __toString() + { + if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print + return json_encode(\Hydra\SDK\ObjectSerializer::sanitizeForSerialization($this), JSON_PRETTY_PRINT); + } + + return json_encode(\Hydra\SDK\ObjectSerializer::sanitizeForSerialization($this)); + } +} + + diff --git a/sdk/php/swagger/lib/Model/OAuth2ConsentRequest.php b/sdk/php/swagger/lib/Model/RejectRequest.php similarity index 61% rename from sdk/php/swagger/lib/Model/OAuth2ConsentRequest.php rename to sdk/php/swagger/lib/Model/RejectRequest.php index d3e0afda671..bc04aec6cdb 100644 --- a/sdk/php/swagger/lib/Model/OAuth2ConsentRequest.php +++ b/sdk/php/swagger/lib/Model/RejectRequest.php @@ -1,6 +1,6 @@ 'string', - 'expires_at' => 'string', - 'id' => 'string', - 'redirect_url' => 'string', - 'requested_scopes' => 'string[]' + 'error' => 'string', + 'error_debug' => 'string', + 'error_description' => 'string', + 'error_hint' => 'string', + 'status_code' => 'int' ]; /** @@ -66,11 +66,11 @@ class OAuth2ConsentRequest implements ArrayAccess * @var string[] */ protected static $swaggerFormats = [ - 'client_id' => null, - 'expires_at' => null, - 'id' => null, - 'redirect_url' => null, - 'requested_scopes' => null + 'error' => null, + 'error_debug' => null, + 'error_description' => null, + 'error_hint' => null, + 'status_code' => 'int64' ]; public static function swaggerTypes() @@ -88,11 +88,11 @@ public static function swaggerFormats() * @var string[] */ protected static $attributeMap = [ - 'client_id' => 'clientId', - 'expires_at' => 'expiresAt', - 'id' => 'id', - 'redirect_url' => 'redirectUrl', - 'requested_scopes' => 'requestedScopes' + 'error' => 'error', + 'error_debug' => 'error_debug', + 'error_description' => 'error_description', + 'error_hint' => 'error_hint', + 'status_code' => 'status_code' ]; @@ -101,11 +101,11 @@ public static function swaggerFormats() * @var string[] */ protected static $setters = [ - 'client_id' => 'setClientId', - 'expires_at' => 'setExpiresAt', - 'id' => 'setId', - 'redirect_url' => 'setRedirectUrl', - 'requested_scopes' => 'setRequestedScopes' + 'error' => 'setError', + 'error_debug' => 'setErrorDebug', + 'error_description' => 'setErrorDescription', + 'error_hint' => 'setErrorHint', + 'status_code' => 'setStatusCode' ]; @@ -114,11 +114,11 @@ public static function swaggerFormats() * @var string[] */ protected static $getters = [ - 'client_id' => 'getClientId', - 'expires_at' => 'getExpiresAt', - 'id' => 'getId', - 'redirect_url' => 'getRedirectUrl', - 'requested_scopes' => 'getRequestedScopes' + 'error' => 'getError', + 'error_debug' => 'getErrorDebug', + 'error_description' => 'getErrorDescription', + 'error_hint' => 'getErrorHint', + 'status_code' => 'getStatusCode' ]; public static function attributeMap() @@ -152,11 +152,11 @@ public static function getters() */ public function __construct(array $data = null) { - $this->container['client_id'] = isset($data['client_id']) ? $data['client_id'] : null; - $this->container['expires_at'] = isset($data['expires_at']) ? $data['expires_at'] : null; - $this->container['id'] = isset($data['id']) ? $data['id'] : null; - $this->container['redirect_url'] = isset($data['redirect_url']) ? $data['redirect_url'] : null; - $this->container['requested_scopes'] = isset($data['requested_scopes']) ? $data['requested_scopes'] : null; + $this->container['error'] = isset($data['error']) ? $data['error'] : null; + $this->container['error_debug'] = isset($data['error_debug']) ? $data['error_debug'] : null; + $this->container['error_description'] = isset($data['error_description']) ? $data['error_description'] : null; + $this->container['error_hint'] = isset($data['error_hint']) ? $data['error_hint'] : null; + $this->container['status_code'] = isset($data['status_code']) ? $data['status_code'] : null; } /** @@ -185,106 +185,106 @@ public function valid() /** - * Gets client_id + * Gets error * @return string */ - public function getClientId() + public function getError() { - return $this->container['client_id']; + return $this->container['error']; } /** - * Sets client_id - * @param string $client_id ClientID is the client id that initiated the OAuth2 request. + * Sets error + * @param string $error * @return $this */ - public function setClientId($client_id) + public function setError($error) { - $this->container['client_id'] = $client_id; + $this->container['error'] = $error; return $this; } /** - * Gets expires_at + * Gets error_debug * @return string */ - public function getExpiresAt() + public function getErrorDebug() { - return $this->container['expires_at']; + return $this->container['error_debug']; } /** - * Sets expires_at - * @param string $expires_at ExpiresAt is the time where the access request will expire. + * Sets error_debug + * @param string $error_debug * @return $this */ - public function setExpiresAt($expires_at) + public function setErrorDebug($error_debug) { - $this->container['expires_at'] = $expires_at; + $this->container['error_debug'] = $error_debug; return $this; } /** - * Gets id + * Gets error_description * @return string */ - public function getId() + public function getErrorDescription() { - return $this->container['id']; + return $this->container['error_description']; } /** - * Sets id - * @param string $id ID is the id of this consent request. + * Sets error_description + * @param string $error_description * @return $this */ - public function setId($id) + public function setErrorDescription($error_description) { - $this->container['id'] = $id; + $this->container['error_description'] = $error_description; return $this; } /** - * Gets redirect_url + * Gets error_hint * @return string */ - public function getRedirectUrl() + public function getErrorHint() { - return $this->container['redirect_url']; + return $this->container['error_hint']; } /** - * Sets redirect_url - * @param string $redirect_url Redirect URL is the URL where the user agent should be redirected to after the consent has been accepted or rejected. + * Sets error_hint + * @param string $error_hint * @return $this */ - public function setRedirectUrl($redirect_url) + public function setErrorHint($error_hint) { - $this->container['redirect_url'] = $redirect_url; + $this->container['error_hint'] = $error_hint; return $this; } /** - * Gets requested_scopes - * @return string[] + * Gets status_code + * @return int */ - public function getRequestedScopes() + public function getStatusCode() { - return $this->container['requested_scopes']; + return $this->container['status_code']; } /** - * Sets requested_scopes - * @param string[] $requested_scopes RequestedScopes represents a list of scopes that have been requested by the OAuth2 request initiator. + * Sets status_code + * @param int $status_code * @return $this */ - public function setRequestedScopes($requested_scopes) + public function setStatusCode($status_code) { - $this->container['requested_scopes'] = $requested_scopes; + $this->container['status_code'] = $status_code; return $this; } diff --git a/sdk/php/swagger/lib/Model/SwaggerOAuthConsentRequestPayload.php b/sdk/php/swagger/lib/Model/SwaggerOAuthConsentRequestPayload.php deleted file mode 100644 index 670bae43179..00000000000 --- a/sdk/php/swagger/lib/Model/SwaggerOAuthConsentRequestPayload.php +++ /dev/null @@ -1,248 +0,0 @@ - 'string' - ]; - - /** - * Array of property to format mappings. Used for (de)serialization - * @var string[] - */ - protected static $swaggerFormats = [ - 'id' => null - ]; - - public static function swaggerTypes() - { - return self::$swaggerTypes; - } - - public static function swaggerFormats() - { - return self::$swaggerFormats; - } - - /** - * Array of attributes where the key is the local name, and the value is the original name - * @var string[] - */ - protected static $attributeMap = [ - 'id' => 'id' - ]; - - - /** - * Array of attributes to setter functions (for deserialization of responses) - * @var string[] - */ - protected static $setters = [ - 'id' => 'setId' - ]; - - - /** - * Array of attributes to getter functions (for serialization of requests) - * @var string[] - */ - protected static $getters = [ - 'id' => 'getId' - ]; - - public static function attributeMap() - { - return self::$attributeMap; - } - - public static function setters() - { - return self::$setters; - } - - public static function getters() - { - return self::$getters; - } - - - - - - /** - * Associative array for storing property values - * @var mixed[] - */ - protected $container = []; - - /** - * Constructor - * @param mixed[] $data Associated array of property values initializing the model - */ - public function __construct(array $data = null) - { - $this->container['id'] = isset($data['id']) ? $data['id'] : null; - } - - /** - * show all the invalid properties with reasons. - * - * @return array invalid properties with reasons - */ - public function listInvalidProperties() - { - $invalid_properties = []; - - if ($this->container['id'] === null) { - $invalid_properties[] = "'id' can't be null"; - } - return $invalid_properties; - } - - /** - * validate all the properties in the model - * return true if all passed - * - * @return bool True if all properties are valid - */ - public function valid() - { - - if ($this->container['id'] === null) { - return false; - } - return true; - } - - - /** - * Gets id - * @return string - */ - public function getId() - { - return $this->container['id']; - } - - /** - * Sets id - * @param string $id The id of the OAuth 2.0 Consent Request. - * @return $this - */ - public function setId($id) - { - $this->container['id'] = $id; - - return $this; - } - /** - * Returns true if offset exists. False otherwise. - * @param integer $offset Offset - * @return boolean - */ - public function offsetExists($offset) - { - return isset($this->container[$offset]); - } - - /** - * Gets offset. - * @param integer $offset Offset - * @return mixed - */ - public function offsetGet($offset) - { - return isset($this->container[$offset]) ? $this->container[$offset] : null; - } - - /** - * Sets value based on offset. - * @param integer $offset Offset - * @param mixed $value Value to be set - * @return void - */ - public function offsetSet($offset, $value) - { - if (is_null($offset)) { - $this->container[] = $value; - } else { - $this->container[$offset] = $value; - } - } - - /** - * Unsets offset. - * @param integer $offset Offset - * @return void - */ - public function offsetUnset($offset) - { - unset($this->container[$offset]); - } - - /** - * Gets the string presentation of the object - * @return string - */ - public function __toString() - { - if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print - return json_encode(\Hydra\SDK\ObjectSerializer::sanitizeForSerialization($this), JSON_PRETTY_PRINT); - } - - return json_encode(\Hydra\SDK\ObjectSerializer::sanitizeForSerialization($this)); - } -} - -