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

fix(authentication-service): added idp server controller for login and discovery endpoint #2131

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
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
13 changes: 13 additions & 0 deletions package-lock.json

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

Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,5 @@
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
export * from './jwt-keys.model';
export * from './revoked-token.model';
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import {Entity, model, property} from '@loopback/repository';

@model({
name: 'jwt_keys',
})
export class JwtKeys extends Entity {
@property({
type: 'string',
id: true,
})
id?: string;

@property({
type: 'string',
required: true,
name: 'key_id',
})
keyId: string;

@property({
type: 'string',
required: true,
name: 'public_key',
})
publicKey: string;

@property({
type: 'string',
required: true,
name: 'private_key',
})
privateKey: string;

@property({
type: 'date',
default: () => new Date(),
name: 'created_on',
})
createdOn?: Date;

constructor(data?: Partial<JwtKeys>) {
super(data);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,24 +3,28 @@
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
import {Constructor, inject, Provider} from '@loopback/context';
import {repository} from '@loopback/repository';
import {HttpErrors} from '@loopback/rest';
import {verify} from 'jsonwebtoken';
import * as jwt from 'jsonwebtoken';
import {
VerifyFunction,
AuthenticationBindings,
EntityWithIdentifier,
IAuthUser,
VerifyFunction,
} from 'loopback4-authentication';
import moment from 'moment-timezone';
import * as fs from 'fs/promises';
import * as jose from 'node-jose';
import {ILogger, LOGGER} from '../../logger-extension';
import {IAuthUserWithPermissions} from '../keys';
import {JwtKeysRepository} from '../repositories';

export class ServicesBearerAsymmetricTokenVerifyProvider
implements Provider<VerifyFunction.BearerFn>
{
constructor(
@inject(LOGGER.LOGGER_INJECT) public logger: ILogger,
@repository(JwtKeysRepository)
public jwtKeysRepo: JwtKeysRepository,
@inject(AuthenticationBindings.USER_MODEL, {optional: true})
public authUserModel?: Constructor<EntityWithIdentifier & IAuthUser>,
) {}
Expand All @@ -30,8 +34,30 @@ export class ServicesBearerAsymmetricTokenVerifyProvider
let user: IAuthUserWithPermissions;

try {
const publicKey = await fs.readFile(process.env.JWT_PUBLIC_KEY ?? '');
user = verify(token, publicKey, {
// Get the key that matches the token's kid
const decoded = jwt.decode(token.trim(), {complete: true});
if (!decoded) {
throw new Error('Token is not valid');
}
const kid = decoded?.header.kid;

// Load the JWKS
const key = await this.jwtKeysRepo.findOne({
where: {
keyId: kid,
},
});

if (!key) {
throw new Error('Key not found for verification');
}

// Convert the JWK to PEM format for verification
const jwkKey = await jose.JWK.asKey(key.publicKey, 'pem');
const pem = jwkKey.toPEM(false);

// Verify the token with the retrieved PEM-formatted public key
user = jwt.verify(token, pem, {
issuer: process.env.JWT_ISSUER,
algorithms: ['RS256'],
}) as IAuthUserWithPermissions;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,5 @@
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
export * from './jwt-keys.repository';
export * from './revoked-token.repository';
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import {inject} from '@loopback/core';
import {DefaultCrudRepository, juggler} from '@loopback/repository';
import {JwtKeys} from '../models';
import {AuthDbSourceName} from '../types';

export class JwtKeysRepository extends DefaultCrudRepository<
JwtKeys,
typeof JwtKeys.prototype.id
> {
constructor(
@inject(`datasources.${AuthDbSourceName}`)
dataSource: juggler.DataSource,
) {
super(JwtKeys, dataSource);
}
}
1 change: 1 addition & 0 deletions packages/core/src/components/bearer-verifier/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,4 @@
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
export const AuthCacheSourceName = 'AuthCache';
export const AuthDbSourceName = 'AuthDB';
4 changes: 3 additions & 1 deletion services/authentication-service/.env.defaults
Original file line number Diff line number Diff line change
Expand Up @@ -61,4 +61,6 @@ AZURE_AUTH_COOKIE_KEY=

#iv is 12 bit

AZURE_AUTH_COOKIE_IV=
AZURE_AUTH_COOKIE_IV=

MAX_JWT_KEYS=2
6 changes: 5 additions & 1 deletion services/authentication-service/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -82,4 +82,8 @@ AZURE_AUTH_COOKIE_IV=
AUTH0_DOMAIN=
AUTH0_CLIENT_ID=
AUTH0_CLIENT_SECRET=
AUTH0_CALLBACK_URL=
AUTH0_CALLBACK_URL=

MAX_JWT_KEYS=
JWT_PRIVATE_KEY_PASSPHRASE=
API_BASE_URL=
4 changes: 2 additions & 2 deletions services/authentication-service/.vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@
"editor.trimAutoWhitespace": true,
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.organizeImports": true,
"source.fixAll.eslint": true
"source.organizeImports": "explicit",
"source.fixAll.eslint": "explicit"
},

"files.exclude": {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
'use strict';

var dbm;
var type;
var seed;
var fs = require('fs');
var path = require('path');
var Promise;

/**
* We receive the dbmigrate dependency from dbmigrate initially.
* This enables us to not have to rely on NODE_PATH.
*/
exports.setup = function (options, seedLink) {
dbm = options.dbmigrate;
type = dbm.dataType;
seed = seedLink;
Promise = options.Promise;
};

exports.up = function (db) {
var filePath = path.join(
__dirname,
'sqls',
'20241105074844-add-jwt-keys-schema-up.sql',
);
return new Promise(function (resolve, reject) {
fs.readFile(filePath, {encoding: 'utf-8'}, function (err, data) {
if (err) return reject(err);
console.log('received data: ' + data);

resolve(data);
});
}).then(function (data) {
return db.runSql(data);
});
};

exports.down = function (db) {
var filePath = path.join(
__dirname,
'sqls',
'20241105074844-add-jwt-keys-schema-down.sql',
);
return new Promise(function (resolve, reject) {
fs.readFile(filePath, {encoding: 'utf-8'}, function (err, data) {
if (err) return reject(err);
console.log('received data: ' + data);

resolve(data);
});
}).then(function (data) {
return db.runSql(data);
});
};

exports._meta = {
version: 1,
};
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
DROP TABLE main.jwt_keys;
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
CREATE TABLE main.jwt_keys (
id INT AUTO_INCREMENT PRIMARY KEY,
key_id VARCHAR(100) UNIQUE NOT NULL,
public_key TEXT NOT NULL, -- Public key in PEM format
private_key TEXT NOT NULL, -- Private key in PEM format
created_on TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
'use strict';

var dbm;
var type;
var seed;
var fs = require('fs');
var path = require('path');
var Promise;

/**
* We receive the dbmigrate dependency from dbmigrate initially.
* This enables us to not have to rely on NODE_PATH.
*/
exports.setup = function (options, seedLink) {
dbm = options.dbmigrate;
type = dbm.dataType;
seed = seedLink;
Promise = options.Promise;
};

exports.up = function (db) {
var filePath = path.join(
__dirname,
'sqls',
'20241105074844-add-jwt-keys-schema-up.sql',
);
return new Promise(function (resolve, reject) {
fs.readFile(filePath, {encoding: 'utf-8'}, function (err, data) {
if (err) return reject(err);
console.log('received data: ' + data);

resolve(data);
});
}).then(function (data) {
return db.runSql(data);
});
};

exports.down = function (db) {
var filePath = path.join(
__dirname,
'sqls',
'20241105074844-add-jwt-keys-schema-down.sql',
);
return new Promise(function (resolve, reject) {
fs.readFile(filePath, {encoding: 'utf-8'}, function (err, data) {
if (err) return reject(err);
console.log('received data: ' + data);

resolve(data);
});
}).then(function (data) {
return db.runSql(data);
});
};

exports._meta = {
version: 1,
};
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
DROP TABLE main.jwt_keys;
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
CREATE TABLE main.jwt_keys (
id SERIAL PRIMARY KEY,
key_id VARCHAR(100) UNIQUE NOT NULL,
public_key TEXT NOT NULL, -- Public key in PEM format
private_key TEXT NOT NULL, -- Private key in PEM format
created_on TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
Loading
Loading