Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,9 @@ func initConfig() {
viper.BindEnv("OAUTH2_LOGIN_URL")
viper.SetDefault("OAUTH2_LOGIN_URL", oauth2.DefaultConsentPath)

viper.BindEnv("OAUTH2_LOGOUT_REDIRECT_URL")
viper.SetDefault("OAUTH2_LOGOUT_REDIRECT_URL", oauth2.DefaultLogoutPath)

viper.BindEnv("OAUTH2_ERROR_URL")
viper.SetDefault("OAUTH2_ERROR_URL", oauth2.DefaultErrorPath)

Expand Down
4 changes: 4 additions & 0 deletions cmd/serve.go
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,10 @@ OAUTH2 CONTROLS
- OAUTH2_LOGIN_URL: The login provider's URL.
Example: OAUTH2_LOGIN_URL=https://id.myapp.com/login

- OAUTH2_LOGOUT_REDIRECT_URL: The URL where the user's browser will be redirected to after successfully logging out
of ORY Hydra.
Example: OAUTH2_LOGOUT_REDIRECT_URL=https://myapp.com/

- OAUTH2_ISSUER_URL: IssuerURL 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: OAUTH2_ISSUER_URL=https://hydra.myapp.com/
Expand Down
2 changes: 1 addition & 1 deletion cmd/server/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -250,7 +250,7 @@ func (h *Handler) registerRoutes(frontend, backend *httprouter.Router) {
// Set up handlers
h.Clients = newClientHandler(c, backend, clientsManager)
h.Keys = newJWKHandler(c, frontend, backend)
h.Consent = newConsentHandler(c, backend)
h.Consent = newConsentHandler(c, frontend, backend)
h.OAuth2 = newOAuth2Handler(c, frontend, backend, ctx.ConsentManager, oauth2Provider)
_ = newHealthHandler(c, backend)
}
Expand Down
7 changes: 4 additions & 3 deletions cmd/server/handler_consent_factory.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
package server

import (
"github.com/gorilla/sessions"
"github.com/julienschmidt/httprouter"
"github.com/ory/herodot"
"github.com/ory/hydra/client"
Expand All @@ -33,14 +34,14 @@ func injectConsentManager(c *config.Config, cm client.Manager) {
ctx.ConsentManager = ctx.Connection.NewConsentManager(cm, ctx.FositeStore)
}

func newConsentHandler(c *config.Config, router *httprouter.Router) *consent.Handler {
func newConsentHandler(c *config.Config, frontend, backend *httprouter.Router) *consent.Handler {
var ctx = c.Context()

w := herodot.NewJSONWriter(c.GetLogger())
w.ErrorEnhancer = writerErrorEnhancer

expectDependency(c.GetLogger(), ctx.ConsentManager)
h := consent.NewHandler(w, ctx.ConsentManager)
h.SetRoutes(router)
h := consent.NewHandler(w, ctx.ConsentManager, sessions.NewCookieStore(c.GetCookieSecret()), c.LogoutRedirectURL)
h.SetRoutes(frontend, backend)
return h
}
1 change: 1 addition & 0 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ type Config struct {
DatabasePlugin string `mapstructure:"DATABASE_PLUGIN" yaml:"-"`
ConsentURL string `mapstructure:"OAUTH2_CONSENT_URL" yaml:"-"`
LoginURL string `mapstructure:"OAUTH2_LOGIN_URL" yaml:"-"`
LogoutRedirectURL string `mapstructure:"OAUTH2_LOGOUT_REDIRECT_URL" yaml:"-"`
DefaultClientScope string `mapstructure:"OIDC_DYNAMIC_CLIENT_REGISTRATION_DEFAULT_SCOPE" yaml:"-"`
ErrorURL string `mapstructure:"OAUTH2_ERROR_URL" yaml:"-"`
AllowTLSTermination string `mapstructure:"HTTPS_ALLOW_TERMINATION_FROM" yaml:"-"`
Expand Down
75 changes: 59 additions & 16 deletions consent/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import (
"net/url"
"time"

"github.com/gorilla/sessions"
"github.com/julienschmidt/httprouter"
"github.com/ory/fosite"
"github.com/ory/go-convenience/urlx"
Expand All @@ -35,9 +36,11 @@ import (
)

type Handler struct {
H herodot.Writer
M Manager
RequestMaxAge time.Duration
H herodot.Writer
M Manager
LogoutRedirectURL string
RequestMaxAge time.Duration
CookieStore sessions.Store
}

const (
Expand All @@ -48,26 +51,32 @@ const (
func NewHandler(
h herodot.Writer,
m Manager,
c sessions.Store,
u string,
) *Handler {
return &Handler{
H: h,
M: m,
H: h,
M: m,
LogoutRedirectURL: u,
CookieStore: c,
}
}

func (h *Handler) SetRoutes(r *httprouter.Router) {
r.GET(LoginPath+"/:challenge", h.GetLoginRequest)
r.PUT(LoginPath+"/:challenge/accept", h.AcceptLoginRequest)
r.PUT(LoginPath+"/:challenge/reject", h.RejectLoginRequest)
func (h *Handler) SetRoutes(frontend, backend *httprouter.Router) {
backend.GET(LoginPath+"/:challenge", h.GetLoginRequest)
backend.PUT(LoginPath+"/:challenge/accept", h.AcceptLoginRequest)
backend.PUT(LoginPath+"/:challenge/reject", h.RejectLoginRequest)

r.GET(ConsentPath+"/:challenge", h.GetConsentRequest)
r.PUT(ConsentPath+"/:challenge/accept", h.AcceptConsentRequest)
r.PUT(ConsentPath+"/:challenge/reject", h.RejectConsentRequest)
backend.GET(ConsentPath+"/:challenge", h.GetConsentRequest)
backend.PUT(ConsentPath+"/:challenge/accept", h.AcceptConsentRequest)
backend.PUT(ConsentPath+"/:challenge/reject", h.RejectConsentRequest)

r.DELETE("/oauth2/auth/sessions/login/:user", h.DeleteLoginSession)
r.GET("/oauth2/auth/sessions/consent/:user", h.GetConsentSessions)
r.DELETE("/oauth2/auth/sessions/consent/:user", h.DeleteUserConsentSession)
r.DELETE("/oauth2/auth/sessions/consent/:user/:client", h.DeleteUserClientConsentSession)
backend.DELETE("/oauth2/auth/sessions/login/:user", h.DeleteLoginSession)
backend.GET("/oauth2/auth/sessions/consent/:user", h.GetConsentSessions)
backend.DELETE("/oauth2/auth/sessions/consent/:user", h.DeleteUserConsentSession)
backend.DELETE("/oauth2/auth/sessions/consent/:user/:client", h.DeleteUserClientConsentSession)

frontend.GET("/oauth2/auth/sessions/login/revoke", h.LogoutUser)
}

// swagger:route DELETE /oauth2/auth/sessions/consent/{user} oAuth2 revokeAllUserConsentSessions
Expand Down Expand Up @@ -571,3 +580,37 @@ func (h *Handler) RejectConsentRequest(w http.ResponseWriter, r *http.Request, p
RedirectTo: urlx.SetQuery(ru, url.Values{"consent_verifier": {request.Verifier}}).String(),
})
}

// swagger:route GET /oauth2/auth/sessions/login/revoke oAuth2 revokeUserLoginCookie
//
// Logs user out by deleting the session cookie
//
// This endpoint deletes ths user's login session cookie and redirects the browser to the url
// listed in `LOGOUT_REDIRECT_URL` environment variable. This endpoint does not work as an API but has to
// be called from the user's browser.
//
// Produces:
// - application/json
//
// Schemes: http, https
//
// Responses:
// 302: emptyResponse
// 404: genericError
// 500: genericError
func (h *Handler) LogoutUser(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
sid, err := revokeAuthenticationCookie(w, r, h.CookieStore)
if err != nil {
h.H.WriteError(w, r, err)
return
}

if sid != "" {
if err := h.M.DeleteAuthenticationSession(sid); err != nil {
h.H.WriteError(w, r, err)
return
}
}

http.Redirect(w, r, h.LogoutRedirectURL, 302)
}
91 changes: 91 additions & 0 deletions consent/handler_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
/*
* Copyright © 2015-2018 Aeneas Rekkas <aeneas+oss@aeneas.io>
*
* 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 <aeneas+oss@aeneas.io>
* @Copyright 2017-2018 Aeneas Rekkas <aeneas+oss@aeneas.io>
* @license Apache-2.0
*/

package consent

import (
"net/http"
"net/http/cookiejar"
"net/http/httptest"
"net/url"
"testing"
"time"

"github.com/gorilla/sessions"
"github.com/julienschmidt/httprouter"
"github.com/ory/herodot"
"github.com/pborman/uuid"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

func TestLogout(t *testing.T) {
cs := sessions.NewCookieStore([]byte("secret"))
r := httprouter.New()
h := NewHandler(
herodot.NewJSONWriter(nil),
NewMemoryManager(nil),
cs,
"https://www.ory.sh",
)

sid := uuid.New()

r.Handle("GET", "/login", func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
cookie, _ := cs.Get(r, cookieAuthenticationName)
require.NoError(t, h.M.CreateAuthenticationSession(&AuthenticationSession{
ID: sid,
Subject: "foo",
AuthenticatedAt: time.Now(),
}))

cookie.Values[cookieAuthenticationSIDName] = sid
cookie.Options.MaxAge = 60

require.NoError(t, cookie.Save(r, w))
})

r.Handle("GET", "/logout", func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
})

h.SetRoutes(r, r)
ts := httptest.NewServer(r)
defer ts.Close()

h.LogoutRedirectURL = ts.URL + "/logout"

u, err := url.Parse(ts.URL)
require.NoError(t, err)

cj, err := cookiejar.New(new(cookiejar.Options))
require.NoError(t, err)

c := &http.Client{Jar: cj}
resp, err := c.Get(ts.URL + "/login")
require.NoError(t, err)
require.EqualValues(t, http.StatusOK, resp.StatusCode)
require.Len(t, cj.Cookies(u), 1)

resp, err = c.Get(ts.URL + "/oauth2/auth/sessions/login/revoke")
require.NoError(t, err)
require.EqualValues(t, http.StatusOK, resp.StatusCode)
assert.Len(t, cj.Cookies(u), 0)
assert.EqualValues(t, ts.URL+"/logout", resp.Request.URL.String())
}
5 changes: 3 additions & 2 deletions consent/sdk_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import (
"testing"
"time"

"github.com/gorilla/sessions"
"github.com/julienschmidt/httprouter"
"github.com/ory/herodot"
. "github.com/ory/hydra/consent"
Expand All @@ -40,9 +41,9 @@ import (
func TestSDK(t *testing.T) {
m := NewMemoryManager(oauth2.NewFositeMemoryStore(nil, time.Minute))
router := httprouter.New()
h := NewHandler(herodot.NewJSONWriter(logrus.New()), m)
h := NewHandler(herodot.NewJSONWriter(logrus.New()), m, sessions.NewCookieStore([]byte("secret")), "https://www.ory.sh")

h.SetRoutes(router)
h.SetRoutes(router, router)
ts := httptest.NewServer(router)

sdk, err := hydra.NewSDK(&hydra.Configuration{
Expand Down
23 changes: 16 additions & 7 deletions consent/strategy_default.go
Original file line number Diff line number Diff line change
Expand Up @@ -257,21 +257,30 @@ func (s *DefaultStrategy) forwardAuthenticationRequest(w http.ResponseWriter, r
}

func (s *DefaultStrategy) revokeAuthenticationSession(w http.ResponseWriter, r *http.Request) error {
cookie, _ := s.CookieStore.Get(r, cookieAuthenticationName)
sid, err := revokeAuthenticationCookie(w, r, s.CookieStore)
if err != nil {
return err
}

if sid == "" {
return nil
}

return s.M.DeleteAuthenticationSession(sid)
}

func revokeAuthenticationCookie(w http.ResponseWriter, r *http.Request, s sessions.Store) (string, error) {
cookie, _ := s.Get(r, cookieAuthenticationName)
sid, _ := mapx.GetString(cookie.Values, cookieAuthenticationSIDName)

cookie.Options.MaxAge = -1
cookie.Values[cookieAuthenticationSIDName] = ""

if err := cookie.Save(r, w); err != nil {
return errors.WithStack(err)
return "", errors.WithStack(err)
}

if sid == "" {
return nil
}

return s.M.DeleteAuthenticationSession(sid)
return sid, nil
}

func (s *DefaultStrategy) obfuscateSubjectIdentifier(subject string, req fosite.AuthorizeRequester, forcedIdentifier string) (string, error) {
Expand Down
7 changes: 4 additions & 3 deletions consent/strategy_default_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -109,11 +109,12 @@ func TestStrategy(t *testing.T) {
}).ToMapClaims(), jwt.NewHeaders())
require.NoError(t, err)

cs := sessions.NewCookieStore([]byte("dummy-secret-yay"))
writer := herodot.NewJSONWriter(nil)
manager := NewMemoryManager(nil)
handler := NewHandler(writer, manager)
handler := NewHandler(writer, manager, cs, "https://www.ory.sh")
router := httprouter.New()
handler.SetRoutes(router)
handler.SetRoutes(router, router)
api := httptest.NewServer(router)

strategy := NewStrategy(
Expand All @@ -122,7 +123,7 @@ func TestStrategy(t *testing.T) {
ap.URL,
"/oauth2/auth",
manager,
sessions.NewCookieStore([]byte("dummy-secret-yay")),
cs,
fosite.ExactScopeStrategy,
false,
time.Hour,
Expand Down
28 changes: 28 additions & 0 deletions docs/api.swagger.json
Original file line number Diff line number Diff line change
Expand Up @@ -1191,6 +1191,34 @@
}
}
},
"/oauth2/auth/sessions/login/revoke": {
"get": {
"description": "This endpoint deletes ths user's login session cookie and redirects the browser to the url\nlisted in `LOGOUT_REDIRECT_URL` environment variable. This endpoint does not work as an API but has to\nbe called from the user's browser.",
"produces": [
"application/json"
],
"schemes": [
"http",
"https"
],
"tags": [
"oAuth2"
],
"summary": "Logs user out by deleting the session cookie",
"operationId": "revokeUserLoginCookie",
"responses": {
"302": {
"$ref": "#/responses/emptyResponse"
},
"404": {
"$ref": "#/responses/genericError"
},
"500": {
"$ref": "#/responses/genericError"
}
}
}
},
"/oauth2/auth/sessions/login/{user}": {
"delete": {
"description": "This endpoint invalidates a user's authentication session. After revoking the authentication session, the user\nhas to re-authenticate at ORY Hydra. This endpoint does not invalidate any tokens.",
Expand Down
2 changes: 2 additions & 0 deletions oauth2/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ const (
OAuth2JWTKeyName = "hydra.jwt.access-token"

DefaultConsentPath = "/oauth2/fallbacks/consent"
DefaultLogoutPath = "/oauth2/fallbacks/logout"
DefaultErrorPath = "/oauth2/fallbacks/error"
TokenPath = "/oauth2/token"
AuthPath = "/oauth2/auth"
Expand Down Expand Up @@ -161,6 +162,7 @@ func (h *Handler) SetRoutes(frontend, backend *httprouter.Router) {
frontend.POST(AuthPath, h.AuthHandler)
frontend.GET(DefaultConsentPath, h.DefaultConsentHandler)
frontend.GET(DefaultErrorPath, h.DefaultErrorHandler)
frontend.GET(DefaultLogoutPath, h.DefaultLogoutHandler)
frontend.POST(RevocationPath, h.RevocationHandler)
frontend.GET(WellKnownPath, h.WellKnownHandler)
frontend.GET(UserinfoPath, h.UserinfoHandler)
Expand Down
Loading