8000 Allow redirect URL to be different than app origin by jonkoops · Pull Request #230 · keycloak/keycloak-js · GitHub
[go: up one dir, main page]

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
16 changes: 8 additions & 8 deletions lib/keycloak.js
Original file line number Diff line number Diff line change
Expand Up @@ -802,8 +802,8 @@ export default class Keycloak {
async #processInit (initOptions) {
const callback = this.#parseCallback(window.location.href)

if (callback?.redirectUri) {
window.history.replaceState(window.history.state, '', callback.redirectUri)
if (callback?.newUrl) {
window.history.replaceState(window.history.state, '', callback.newUrl)
}

if (callback && callback.valid) {
Expand Down Expand Up @@ -1050,28 +1050,28 @@ export default class Keycloak {
supportedParams.push('error_uri')

const url = new URL(urlString)
let redirectUri = ''
let newUrl = ''
let parsed

if (this.responseMode === 'query' && url.searchParams.size > 0) {
parsed = this.#parseCallbackParams(url.search, supportedParams)
url.search = parsed.paramsString
redirectUri = url.toString()
newUrl = url.toString()
} else if (this.responseMode === 'fragment' && url.hash.length > 0) {
parsed = this.#parseCallbackParams(url.hash.substring(1), supportedParams)
url.hash = ''
redirectUri = url.toString()
url.hash = parsed.paramsString
newUrl = url.toString()
}

if (parsed?.oauthParams) {
if (this.flow === 'standard' || this.flow === 'hybrid') {
if ((parsed.oauthParams.code || parsed.oauthParams.error) && parsed.oauthParams.state) {
parsed.oauthParams.redirectUri = redirectUri
parsed.oauthParams.newUrl = newUrl
return parsed.oauthParams
}
} else if (this.flow === 'implicit') {
if ((parsed.oauthParams.access_token || parsed.oauthParams.error) && parsed.oauthParams.state) {
parsed.oauthParams.redirectUri = redirectUri
parsed.oauthParams.newUrl = newUrl
return parsed.oauthParams
}
}
Expand Down
22 changes: 19 additions & 3 deletions test/app/app.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,27 @@
import express from 'express'
import path from 'node:path'
import { AUTH_SERVER_URL, CLIENT_ID } from '../support/common.ts'
import { AUTH_SERVER_URL, CLIENT_ID, REDIRECT_SERVICE_URL } from '../support/common.ts'

// Set up Express
const app = express()

// Expose middleware to simulate a 'redirect service' between the application and auth server.
app.use((req, res, next) => {
if (req.hostname === REDIRECT_SERVICE_URL.hostname) {
const { origin } = req.query

if (typeof origin !== 'string') {
res.status(400).send('Missing origin query parameter')
return
}

Comment thread
jonkoops marked this conversation as resolved.
Resolved
const redirectUrl = new URL(req.originalUrl, origin)
redirectUrl.searchParams.delete('origin')
res.redirect(redirectUrl.toString())
return
}
next()
})

// Expose 'public' directory and Keycloak JS source.
app.use(express.static(path.resolve(import.meta.dirname, 'public')))
app.use(express.static(path.resolve(import.meta.dirname, '../../lib')))
Expand All @@ -25,5 +42,4 @@ app.get('/adapter-config.json', (req, res) => {
})
})

// Start server
app.listen(3000)
1 change: 1 addition & 0 deletions test/support/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ export const APP_URL = new URL('http://localhost:3000')
export const AUTH_SERVER_URL = new URL('http://localhost:8080')
export const APP_URL_CROSS_ORIGIN = new URL('http://kjs-app.localhost:3000')
export const AUTH_SERVER_URL_CROSS_ORIGIN = new URL('http://kjs-auth.localhost:8080')
export const REDIRECT_SERVICE_URL = new URL('http://kjs-redirect.localhost:3000')
export const ADMIN_USERNAME = 'admin'
export const ADMIN_PASSWORD = 'admin'
export const CLIENT_ID = 'keycloak-js-test-client'
Expand Down
38 changes: 38 additions & 0 deletions test/tests/login-with-redirect.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { expect } from '@playwright/test'
import type { KeycloakInitOptions } from '../../lib/keycloak.js'
import { REDIRECT_SERVICE_URL } from '../support/common.ts'
import { createTestBed, test } from '../support/testbed.ts'

/**
* This test simulates a scenario where a user has configured the adapter to use a redirect URL
* on a different domain than the application (e.g. a redirect service), which then redirects
* back to the actual application. This redirect sits between the application and the auth server.
*/
test('logs in with a redirect service between the application and auth server', async ({ page, appUrl, authServerUrl }) => {
const { executor, updateClient } = await createTestBed(page, { appUrl, authServerUrl })

// Update the client to allow redirecting to the redirect service.
await updateClient({
redirectUris: [`${appUrl.origin}/*`, `${REDIRECT_SERVICE_URL.origin}/*`]
})

// Build the redirect URL that points to the redirect service instead of the application.
const redirectUrl = new URL(REDIRECT_SERVICE_URL)
redirectUrl.searchParams.set('origin', appUrl.origin)

const initOptions: KeycloakInitOptions = {
...executor.defaultInitOptions(),
redirectUri: redirectUrl.toString()
}

// Initially, no user should be authenticated.
expect(await executor.initializeAdapter(initOptions)).toBe(false)
expect(await executor.isAuthenticated()).toBe(false)

await executor.login()
await executor.submitLoginForm()

// After login, the user should be authenticated.
expect(await executor.initializeAdapter(initOptions)).toBe(true)
expect(await executor.isAuthenticated()).toBe(true)
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe check that the final url is the app one:

Suggested change
expect(await executor.isAuthenticated()).toBe(true)
expect(await executor.isAuthenticated()).toBe(true)
expect(page.url()).toBe(new URL(appUrl.origin).toString())

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Currently, navigation happens in the background implicitly. So there should be no need to do this. That said, I kind of want to refactor this, so that any navigation is handled explicitly. However, that is a topic separate from this PR.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Logged an issue for it #232

})
0