Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Plat 602 keycloak integration #1183

Merged
merged 21 commits into from
Mar 31, 2023
Merged
Show file tree
Hide file tree
Changes from 14 commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
19b0774
PLAT-602-sso-keycloak-integration
nour-borgi Feb 1, 2023
9992a60
Merge branch 'PLAT-638-adjust-login-cookies' of https://github.com/je…
nour-borgi Feb 9, 2023
0657b11
Merge branch 'PLAT-638-adjust-login-cookies-test-fix' of https://gith…
nour-borgi Feb 9, 2023
61e4c0a
PLAT-602-Integrate-keycloak
nour-borgi Feb 16, 2023
032682c
Remove failWithError in openid passport and fix error
nour-borgi Feb 17, 2023
580d4be
Merge branch 'PLAT-638-adjust-login-cookies-test-fix' of https://gith…
nour-borgi Feb 24, 2023
a7a4fdc
Merge branch 'PLAT-638-adjust-login-cookies' of https://github.com/je…
nour-borgi Feb 24, 2023
51c0367
Add tests + add more fixes
nour-borgi Feb 27, 2023
fe52c17
Add more tests to users.js
nour-borgi Feb 27, 2023
d4031fe
Remove unused condition
nour-borgi Feb 27, 2023
da49b04
Added openid to config.md description
nour-borgi Feb 28, 2023
b916ed5
Address feedback: replace _user with another name
nour-borgi Mar 16, 2023
750ae7a
Fix the update of the groups of user when no roled are coming from ke…
nour-borgi Mar 16, 2023
c3c495a
Add descriptions to the added keycloak config
nour-borgi Mar 24, 2023
854b78f
Remove keycloak usage from the code base
nour-borgi Mar 27, 2023
2ae7c2d
Fix tests after addressing chnages
nour-borgi Mar 27, 2023
e017e3c
Merge branch 'PLAT-602-keycloak-integration' of https://github.com/je…
nour-borgi Mar 27, 2023
7632b3d
Merge branch 'master' of https://github.com/jembi/openhim-core-js int…
nour-borgi Mar 27, 2023
1586d0d
Restirct update of openid user to a certain fields
nour-borgi Mar 28, 2023
9d3ebc9
Update config.md
nour-borgi Mar 31, 2023
fa2893c
Update config.md
nour-borgi Mar 31, 2023
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
1 change: 1 addition & 0 deletions config/config.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ The following config option are provided by the OpenHIM. All of these options ha
// * "local" means through the UI with hitting "/authentication/local" endpoint with username and password,
// this will create a session for the user and set cookies in the browser.
// * "basic" means with basic auth either through browser or postman by giving also username and password.
// * "openid" means with a third party authentication provider (keycloak).
// * [Deprecated] "token" means that a request should provide in the header an 'auth-token', 'auth-salt' and 'auth-ts' to be authenticated.
"authenicationTypes": ["token"]
},
Expand Down
9 changes: 8 additions & 1 deletion config/default.json
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,14 @@
"maxPayloadSizeMB": 50,
"truncateSize": 15000,
"truncateAppend": "\n[truncated ...]",
"authenticationTypes": ["basic", "local", "token"]
"authenticationTypes": ["basic", "local", "token", "openid"],
"keycloak": {
"url": "http://localhost:9088/realms/platform-realm",
"callbackUrl": "http://localhost:9000",
"clientId": "openhim-oauth",
"clientSecret": "tZKfEbWf0Ka5HBNZwFrdSyQH2xT1sNMR",
"scope": "openid email profile offline_access roles"
}
},
"rerun": {
"httpPort": 7786,
Expand Down
9 changes: 8 additions & 1 deletion config/test.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,14 @@
"maxPayloadSizeMB": 50,
"truncateSize": 10,
"truncateAppend": "\n[truncated ...]",
"authenticationTypes": ["token", "basic", "local"]
"authenticationTypes": ["token", "basic", "local", "openid"],
"keycloak": {
"url": "http://localhost:10000/realms/realm",
"callbackUrl": "http://localhost:10010",
"clientId": "client-id",
"clientSecret": "client-secret",
"scope": "openid email profile offline_access roles"
}
},
"caching": {
"enabled": false
Expand Down
14 changes: 14 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@
"passport-custom": "^1.1.1",
"passport-http": "^0.3.0",
"passport-local": "^1.0.0",
"passport-openidconnect": "^0.1.1",
"pem": "^1.14.4",
"raw-body": "^2.4.1",
"semver": "^7.3.2",
Expand Down
22 changes: 19 additions & 3 deletions src/api/authentication.js
Original file line number Diff line number Diff line change
Expand Up @@ -80,19 +80,35 @@ export function isAuthenticationTypeEnabled(type) {
return getEnabledAuthenticationTypesFromConfig(config).includes(type)
}

function requestType(ctx, type) {
const {headers} = ctx.request

if (
headers['auth-username'] ||
headers['auth-ts'] ||
headers['auth-salt'] ||
headers['auth-token']
) {
return type === 'token'
} else if (headers.authorization && headers.authorization.includes('Basic')) {
return type === 'basic'
}
return false
}

async function authenticateRequest(ctx) {
let user = null

// First attempt local authentication if enabled
// First attempt local or openid authentication if enabled
if (user == null && ctx.req.user) {
user = ctx.req.user
}
// Otherwise try token based authentication if enabled (@deprecated)
if (user == null) {
if (user == null && requestType(ctx, 'token')) {
user = await authenticateToken(ctx)
}
// Otherwise try basic based authentication if enabled
if (user == null) {
if (user == null && requestType(ctx, 'basic')) {
// Basic auth using middleware
user = await authenticateBasic(ctx)
}
Expand Down
54 changes: 40 additions & 14 deletions src/api/users.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,14 +39,7 @@ export function me(ctx) {
}

export async function authenticate(ctx) {
if (!ctx.req.user) {
utils.logAndSetResponse(
ctx,
404,
`Could not be authenticaticated`,
'info'
)
} else {
if (ctx.req.user) {
ctx.body = {
result: 'User authenticated successfully',
user: ctx.req.user
Expand All @@ -66,7 +59,6 @@ export async function authenticateToken(ctx, email) {
'Token authentication strategy is deprecated. Please consider using Local or Basic authentication.'
)


try {
email = unescape(email)

Expand Down Expand Up @@ -179,10 +171,9 @@ export async function userPasswordResetRequest(ctx, email) {
}

try {
const user = await UserModelAPI.findOneAndUpdate(
{email: utils.caseInsensitiveRegex(email)},
updateUserTokenExpiry
)
const user = await UserModelAPI.findOne({
email: utils.caseInsensitiveRegex(email)
})
if (!user) {
ctx.body = `Tried to request password reset for invalid email address: ${email}`
ctx.status = 404
Expand All @@ -192,6 +183,17 @@ export async function userPasswordResetRequest(ctx, email) {
return
}

if (user.provider === 'keycloak') {
ctx.body = `User was provided by Keycloak. Could not be updated.`
ctx.status = 403
logger.info(
`Tried to request password reset for a user provided by Keycloak: ${email}`
)
return
}

await UserModelAPI.findByIdAndUpdate(user.id, updateUserTokenExpiry)

const {consoleURL} = config.alerts
const setPasswordLink = `${consoleURL}/#!/set-password/${token}`

Expand Down Expand Up @@ -299,6 +301,15 @@ export async function updateUserByToken(ctx, token) {
ctx.status = 410
return
}

if (userDataExpiry.provider === 'keycloak') {
ctx.body = `User was provided by Keycloak. Could not be updated.`
ctx.status = 403
logger.info(
`Tried to request update by token for a user provided by Keycloak: ${token}`
)
return
}
} catch (error) {
utils.logAndSetResponse(
ctx,
Expand Down Expand Up @@ -346,7 +357,10 @@ export async function updateUserByToken(ctx, token) {
logger.warn(
'Token authentication strategy is deprecated. Please consider using Local or Basic authentication.'
)
;({user, error} = await updateTokenUser(userUpdateObj))
;({user, error} = await updateTokenUser({
...userUpdateObj,
provider: 'token'
}))
// Other providers
} else {
;({user, error} = await apiUpdateUser(userUpdateObj))
Expand Down Expand Up @@ -430,6 +444,8 @@ export async function addUser(ctx) {
delete userData.passwordSalt
delete userData.passwordAlgorithm
delete userData.password

userData.provider = password ? 'local' : 'token'
}

const user = new UserModelAPI(userData)
Expand Down Expand Up @@ -567,6 +583,15 @@ export async function updateUser(ctx, email) {
ctx.status = 404
return
}

if (userDetails.provider === 'keycloak') {
ctx.body = `User was provided by Keycloak. Could not be updated.`
ctx.status = 403
logger.info(
`Tried to request update for a user provided by Keycloak via API: ${email}`
)
return
}
} catch (e) {
utils.logAndSetResponse(
ctx,
Expand Down Expand Up @@ -615,6 +640,7 @@ export async function updateUser(ctx, email) {
passwordAlgorithm,
passwordHash,
passwordSalt,
provider: 'token',
...userData
}))
// Other providers
Expand Down
14 changes: 14 additions & 0 deletions src/koaApi.js
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,20 @@ export function setupApp(done) {
compose([passport.authenticate('local'), users.authenticate])
)
)
// Openid authentication
app.use(
route.post(
'/authenticate/openid',
compose([
(ctx, next) => {
ctx.request.query = ctx.request.body
return next()
},
passport.authenticate('openidconnect'),
users.authenticate
])
)
)
// @deprecated: Token authentication
app.use(route.get('/authenticate/:username', users.authenticateToken))

Expand Down
13 changes: 12 additions & 1 deletion src/middleware/sessionStore.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import {connectionAPI} from '../config'
import {config, connectionAPI} from '../config'
import {Schema} from 'mongoose'

/**
Expand Down Expand Up @@ -47,6 +47,17 @@ class MongooseStore {
return data
}

// This function is required by 'passport-openidconnect'
verify = async function (req, handle, next) {
var state = {handle}
var ctx = {
maxAge: config.api.maxAge,
issued: ''
}

return next(null, ctx, state)
}

static create() {
return new MongooseStore()
}
Expand Down
73 changes: 36 additions & 37 deletions src/model/users.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,9 +56,9 @@ export const UserModel = connectionDefault.model('User', UserSchema)
* and assign the newly created user a local Passport.
*
*/
export const createUser = async function (_user) {
// Create a clone to _user
const userToBeCreated = {..._user}
export const createUser = async function (newUserData) {
// Create a clone to newUserData
const userToBeCreated = {...newUserData}

let result = {error: null, user: null}

Expand Down Expand Up @@ -95,9 +95,9 @@ export const createUser = async function (_user) {
* and assign the newly created user a local Passport.
*
*/
export const updateUser = async function (_user) {
// Create a clone to _user
const userToBeUpdated = {..._user}
export const updateUser = async function (newUserData) {
// Create a clone to newUserData
const userToBeUpdated = {...newUserData}

let result = {user: null, error: null}

Expand All @@ -118,15 +118,14 @@ export const updateUser = async function (_user) {
await PassportModelAPI.findOne({
protocol: 'local',
user: user.id
}).then(async function (passport) {
if (passport) {
passport.password = password
result = await updatePassport(user, passport)
} else {
result = await createPassport(user, {password})
}
})
.then(async function (passport) {
if (passport) {
passport.password = password
result = await updatePassport(user, passport)
} else {
result = await createPassport(user, {password})
}
})
} else {
result.user = user
}
Expand All @@ -152,19 +151,20 @@ export const updateUser = async function (_user) {
* and assign the newly created user a token Passport.
*
*/
export const updateTokenUser = async function (_user) {
// Create a clone to _user
const userToBeUpdated = {..._user, provider: 'token'}
export const updateTokenUser = async function (newUserData) {
const provider = newUserData.provider ? newUserData.provider : 'token'
// Create a clone to newUserData
const userToBeUpdated = {...newUserData, provider}

let result = {user: null, error: null}

const {passwordHash, passwordAlgorithm, passwordSalt} = userToBeUpdated
const {passwordHash, passwordAlgorithm, passwordSalt} = userToBeUpdated

if (passwordHash || passwordAlgorithm || passwordSalt) {
userToBeUpdated.passwordHash = null
userToBeUpdated.passwordSalt = null
userToBeUpdated.passwordAlgorithm = null
}
if (passwordHash || passwordAlgorithm || passwordSalt) {
userToBeUpdated.passwordHash = null
userToBeUpdated.passwordSalt = null
userToBeUpdated.passwordAlgorithm = null
}

await UserModelAPI.findByIdAndUpdate(userToBeUpdated.id, userToBeUpdated, {
new: true
Expand All @@ -175,21 +175,20 @@ export const updateTokenUser = async function (_user) {
await PassportModelAPI.findOne({
protocol: 'token',
user: user.id
}).then(async function (passport) {
if (passport) {
passport.passwordHash = passwordHash
passport.passwordAlgorithm = passwordAlgorithm
passport.passwordSalt = passwordSalt
result = await updatePassport(user, passport)
} else {
result = await createPassport(user, {
passwordHash,
passwordAlgorithm,
passwordSalt
})
}
})
.then(async function (passport) {
if (passport) {
passport.passwordHash = passwordHash
passport.passwordAlgorithm = passwordAlgorithm
passport.passwordSalt = passwordSalt
result = await updatePassport(user, passport)
} else {
result = await createPassport(user, {
passwordHash,
passwordAlgorithm,
passwordSalt
})
}
})
} else {
result.user = user
}
Expand Down
Loading