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 all 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
16 changes: 15 additions & 1 deletion config/config.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,8 +71,22 @@ 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 (e.g. 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"]
"authenicationTypes": ["token"],
// Openid connect provider configuration needed for the authentication
"openid": {
// Openid connect provider realm url link
"url": "http://localhost:9088/realms/platform-realm",
// Callback URL used by openid connect provider (should be the same callback URL specified in realm)
"callbackUrl": "http://localhost:9000",
// CLient ID specified in the realm
"clientId": "openhim-oauth",
// Client secret specified in the realm
"clientSecret": "tZKfEbWf0Ka5HBNZwFrdSyQH2xT1sNMR",
// Scopes to be requested from Openid connect provider
"scope": "openid email profile offline_access roles"
}
},
"rerun": {
// The port that the transaction re-run processor runs on, this port is
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"],
"openid": {
"url": "http://localhost:9088/realms/platform-realm",
"callbackUrl": "http://localhost:9000",
"clientId": "openhim-oauth",
"clientSecret": "tZKfEbWf0Ka5HBNZwFrdSyQH2xT1sNMR",
"scope": "openid email profile offline_access roles"
}
rcrichton marked this conversation as resolved.
Show resolved Hide resolved
},
"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"],
"openid": {
"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 (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
50 changes: 41 additions & 9 deletions src/api/users.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,9 +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 Down Expand Up @@ -173,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 @@ -186,6 +183,17 @@ export async function userPasswordResetRequest(ctx, email) {
return
}

if (user.provider === 'openid') {
ctx.body = `User supplied by OpenID Connect provider. Cannot request password reset.`
ctx.status = 403
logger.info(
`Tried to request password reset for a user supplied by OpenID Connect provider: ${email}`
)
return
}

await UserModelAPI.findByIdAndUpdate(user.id, updateUserTokenExpiry)

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

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

if (userDataExpiry.provider === 'openid') {
ctx.body = `User supplied by OpenID Connect provider. Could not be updated.`
ctx.status = 403
logger.info(
`Tried to request update by token for a user supplied by OpenID Connect provider: ${token}`
)
return
}
} catch (error) {
utils.logAndSetResponse(
ctx,
Expand Down Expand Up @@ -340,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 @@ -424,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 @@ -570,7 +592,7 @@ export async function updateUser(ctx, email) {
)
}

const {_doc: userData} = new UserModelAPI(ctx.request.body)
let {_doc: userData} = new UserModelAPI(ctx.request.body)
const {password} = ctx.request.body

// @deprecated
Expand All @@ -597,6 +619,15 @@ export async function updateUser(ctx, email) {
delete userData._id
}

if (userDetails.provider === 'openid') {
userData = {
msisdn: userData.msisdn,
dailyReport: userData.dailyReport,
weeklyReport: userData.weeklyReport,
settings: userData.settings
}
}

try {
let user, error
// @deprecated Token user update
Expand All @@ -609,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
6 changes: 3 additions & 3 deletions src/model/passport.js
Original file line number Diff line number Diff line change
Expand Up @@ -42,16 +42,16 @@ const PassportSchema = new Schema({

// Provider fields: Provider, identifer and tokens
//
// "provider" is the name of the third-party auth service in all lowercase
// (e.g. 'github', 'facebook') whereas "identifier" is a provider-specific
// "issuer" is the url of the third-party auth service used to define the baseUrl
// in any OIDC endpoint whereas "identifier" is a provider-specific
// key, typically an ID. These two fields are used as the main means of
// identifying a passport and tying it to a local user.
//
// The "tokens" field is a JSON object used in the case of the OAuth stan-
// dards. When using OAuth 1.0, a `token` as well as a `tokenSecret` will
// be issued by the provider. In the case of OAuth 2.0, an `accessToken`
// and a `refreshToken` will be issued.
provider: String,
issuer: String,
identifier: String,
tokens: Object,

Expand Down
21 changes: 11 additions & 10 deletions src/model/users.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ const UserSchema = new Schema({
/* --- ----------- --- */
provider: {
type: String,
enum: ['keycloak', 'local', 'token'], // token is deprecated
enum: ['openid', 'local', 'token'], // token is deprecated
default: 'local'
},
groups: [String],
Expand Down 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 Down Expand Up @@ -151,9 +151,10 @@ 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}

Expand Down
Loading