hapi-auth-jwt2: update to hapi 17

This commit is contained in:
Simon Schick
2018-03-02 03:37:59 +01:00
parent d8eae6101a
commit 9a9bc685ae
8 changed files with 383 additions and 155 deletions

View File

@@ -1,8 +1,7 @@
import Hapi = require('hapi');
import hapiAuthJwt2 = require('hapi-auth-jwt2');
import { Server } from 'hapi';
import * as hapiAuthJwt2 from 'hapi-auth-jwt2';
const server = new Hapi.Server();
server.connection({port: 8000});
const server = new Server({port: 8000});
interface User {
id: number;
@@ -20,19 +19,27 @@ const users: Users = {
}
};
function validate(decoded: User, request: Hapi.Request, callback: hapiAuthJwt2.ValidateCallback) {
callback(null, !!users[decoded.id]);
}
server.register(hapiAuthJwt2, err => {
const options: hapiAuthJwt2.Options = {
key: 'NeverShareYourSecret',
validateFunc: validate,
verifyOptions: {
algorithms: ['HS256']
server.register({
plugin: hapiAuthJwt2.plugin,
options: {
async verify() {
return {
isValid: true,
};
}
}
};
server.auth.strategy('jwt', 'jwt', options);
})
.then(() => {
const opts: hapiAuthJwt2.Options = {
key: 'NeverShareYourSecret',
async validate(decoded: { id: number }, request) {
return {
isValid: !!users[decoded.id],
};
},
verifyOptions: {
algorithms: ['HS256']
}
};
server.auth.strategy('jwt', 'jwt', opts);
});
server.start();

View File

@@ -1,132 +1,151 @@
// Type definitions for hapi-auth-jwt2 7.0
// Type definitions for hapi-auth-jwt2 8.0
// Project: https://github.com/dwyl/hapi-auth-jwt2
// Definitions by: Warren Seymour <https://github.com/warrenseymour>
// Simon Schick <https://github.com/SimonSchick>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.4
import { Request, Response, PluginFunction } from 'hapi';
import { Request, ResponseObject, Plugin, ResponseToolkit } from 'hapi';
declare namespace hapiAuthJwt2 {
/**
* A key lookup function
*
* @param decoded the *decoded* but *unverified* JWT received from client
* @param callback the key lookup callback
*/
type KeyLookup = (decoded: any, callback: KeyLookupCallback) => void;
/**
* Called when key lookup function has completed
*
* @param err an internal error
* @param key the secret key
* @param extraInfo any additional information that you would like
* to use in `validateFunc` which can be accessed via
* `request.plugins['hapi-auth-jwt2'].extraInfo`
*/
type KeyLookupCallback = (err: any, key: string, extraInfo?: any) => void;
/**
* Called when Validation has completed
*
* @param err an internal error
* @param valid `true` if the JWT was valid, otherwise `false`
* @param credentials alternative credentials to be set instead of `decoded`
*/
type ValidateCallback = (err: any, valid: boolean, credentials?: any) => void;
/**
* Options passed to `hapi.auth.strategy` when this plugin is used
*/
interface Options {
/**
* The secret key used to check the signature of the token *or* a *key lookup function*
*/
key?: string | KeyLookup;
/**
* The function which is run once the Token has been decoded
*
* @param decoded the *decoded* and *verified* JWT received from the client in *request.headers.authorization*
* @param request the original *request* received from the client
* @param callback the validation callback
*/
validateFunc(decoded: {}, request: Request, callback: ValidateCallback): void;
/**
* Settings to define how tokens are verified by the jsonwebtoken library
*/
verifyOptions?: {
/**
* Ignore expired tokens
*/
ignoreExpiration?: boolean;
/**
* Do not enforce token audience
*/
audience?: boolean;
/**
* Do not require the issuer to be valid
*/
issuer?: boolean;
/**
* List of allowed algorithms
*/
algorithms?: string[];
};
/**
* function called to decorate the response with authentication headers
* before the response headers or payload is written
*
* @param request the Request object
* @param reply is called if an error occurred
*/
responseFunc?(request: Request, reply: (err: any, response: Response) => void): void;
/**
* If you prefer to pass your token via url, simply add a token url
* parameter to your request or use a custom parameter by setting `urlKey.
* To disable the url parameter set urlKey to `false` or ''.
* @default 'token'
*/
urlKey?: string | boolean;
/**
* If you prefer to set your own cookie key or your project has a cookie
* called 'token' for another purpose, you can set a custom key for your
* cookie by setting `options.cookieKey='yourkeyhere'`. To disable cookies
* set cookieKey to `false` or ''.
* @default 'token'
*/
cookieKey?: string | boolean;
/**
* If you want to set a custom key for your header token use the
* `headerKey` option. To disable header token set headerKey to `false` or
* ''.
* @default 'authorization'
*/
headerKey?: string | boolean;
/**
* Allow custom token type, e.g. `Authorization: <tokenType> 12345678`
*/
tokenType?: string;
/**
* Set to `true` to receive the complete token (`decoded.header`,
* `decoded.payload` and `decoded.signature`) as decoded argument to key
* lookup and `verifyFunc` callbacks (*not `validateFunc`*)
* @default false
*/
complete?: boolean;
declare module 'hapi' {
interface ServerAuth {
strategy(name: string, scheme: 'jwt', options?: Options): void;
}
}
declare var hapiAuthJwt2: PluginFunction<{}>;
export interface ExtraInfo {
}
export = hapiAuthJwt2;
export interface ErrorContext {
/**
* Boom method to call (eg. unauthorized)
*/
errorType: string;
/**
* message passed into the Boom method call
*/
message?: string;
/**
* schema passed into the Boom method call
*/
schema: string;
/**
* attributes passed into the Boom method call
*/
attributes?: {
[key: string]: string;
};
}
/**
* Options passed to `hapi.auth.strategy` when this plugin is used
*/
export interface Options {
/**
* The secret key used to check the signature of the token *or* a *key lookup function*
*/
key?: string | string[] | Promise<{ isValid: boolean; key: string; extraInfo?: ExtraInfo }>;
/**
* The function which is run once the Token has been decoded
*
* @param decoded the *decoded* and *verified* JWT received from the client in *request.headers.authorization*
* @param request the original *request* received from the client
*/
validate(decoded: {}, request: Request, tk: ResponseToolkit): Promise<{
isValid: boolean;
credentials?: any;
response?: ResponseObject
}>;
/**
* Settings to define how tokens are verified by the jsonwebtoken library
*/
verifyOptions?: {
/**
* Ignore expired tokens
*/
ignoreExpiration?: boolean;
/**
* Do not enforce token audience
*/
audience?: boolean;
/**
* Do not require the issuer to be valid
*/
issuer?: boolean;
/**
* List of allowed algorithms
*/
algorithms?: string[];
};
/**
* function called to decorate the response with authentication headers
* before the response headers or payload is written
*
* @param request the Request object
* @param reply is called if an error occurred
*/
responseFunc?(request: Request, reply: (err: any, response: ResponseObject) => void): void;
/**
*
* @param ctx called when an error has been raised.
* It provides an extension point to allow the host the ability to customise the error messages returned.
*/
errorFunc?(ctx: ErrorContext): ErrorContext;
/**
* If you prefer to pass your token via url, simply add a token url
* parameter to your request or use a custom parameter by setting `urlKey.
* To disable the url parameter set urlKey to `false` or ''.
* @default 'token'
*/
urlKey?: string | boolean;
/**
* If you prefer to set your own cookie key or your project has a cookie
* called 'token' for another purpose, you can set a custom key for your
* cookie by setting `options.cookieKey='yourkeyhere'`. To disable cookies
* set cookieKey to `false` or ''.
* @default 'token'
*/
cookieKey?: string | boolean;
/**
* If you want to set a custom key for your header token use the
* `headerKey` option. To disable header token set headerKey to `false` or
* ''.
* @default 'authorization'
*/
headerKey?: string | boolean;
/**
* Allow custom token type, e.g. `Authorization: <tokenType> 12345678`
*/
tokenType?: string;
/**
* Set to `true` to receive the complete token (`decoded.header`,
* `decoded.payload` and `decoded.signature`) as decoded argument to key
* lookup and `verifyFunc` callbacks (*not `validateFunc`*)
* @default false
*/
complete?: boolean;
}
export interface RegisterOptions {
/**
* function which is run once the Token has been decoded (instead of a validate) with signature async function(decoded, request) where:
*/
verify?(decoded: any, request: Request): Promise<{
isValid: boolean;
credentials?: any;
}>;
}
export const plugin: Plugin<RegisterOptions>;

View File

@@ -13,20 +13,6 @@
"../"
],
"types": [],
"paths": {
"boom": [
"boom/v4"
],
"catbox": [
"catbox/v7"
],
"hapi": [
"hapi/v16"
],
"inert": [
"inert/v4"
]
},
"noEmit": true,
"forceConsistentCasingInFileNames": true
},

View File

@@ -1 +1,6 @@
{ "extends": "dtslint/dt.json" }
{
"extends": "dtslint/dt.json",
"rules": {
"no-empty-interface": false
}
}

View File

@@ -0,0 +1,38 @@
import Hapi = require('hapi');
import hapiAuthJwt2 = require('hapi-auth-jwt2');
const server = new Hapi.Server();
server.connection({port: 8000});
interface User {
id: number;
name: string;
}
interface Users {
[id: number]: User;
}
const users: Users = {
1: {
id: 1,
name: 'Test User'
}
};
function validate(decoded: User, request: Hapi.Request, callback: hapiAuthJwt2.ValidateCallback) {
callback(null, !!users[decoded.id]);
}
server.register(hapiAuthJwt2, err => {
const options: hapiAuthJwt2.Options = {
key: 'NeverShareYourSecret',
validateFunc: validate,
verifyOptions: {
algorithms: ['HS256']
}
};
server.auth.strategy('jwt', 'jwt', options);
});
server.start();

132
types/hapi-auth-jwt2/v7/index.d.ts vendored Normal file
View File

@@ -0,0 +1,132 @@
// Type definitions for hapi-auth-jwt2 7.0
// Project: https://github.com/dwyl/hapi-auth-jwt2
// Definitions by: Warren Seymour <https://github.com/warrenseymour>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.4
import { Request, Response, PluginFunction } from 'hapi';
declare namespace hapiAuthJwt2 {
/**
* A key lookup function
*
* @param decoded the *decoded* but *unverified* JWT received from client
* @param callback the key lookup callback
*/
type KeyLookup = (decoded: any, callback: KeyLookupCallback) => void;
/**
* Called when key lookup function has completed
*
* @param err an internal error
* @param key the secret key
* @param extraInfo any additional information that you would like
* to use in `validateFunc` which can be accessed via
* `request.plugins['hapi-auth-jwt2'].extraInfo`
*/
type KeyLookupCallback = (err: any, key: string, extraInfo?: any) => void;
/**
* Called when Validation has completed
*
* @param err an internal error
* @param valid `true` if the JWT was valid, otherwise `false`
* @param credentials alternative credentials to be set instead of `decoded`
*/
type ValidateCallback = (err: any, valid: boolean, credentials?: any) => void;
/**
* Options passed to `hapi.auth.strategy` when this plugin is used
*/
interface Options {
/**
* The secret key used to check the signature of the token *or* a *key lookup function*
*/
key?: string | KeyLookup;
/**
* The function which is run once the Token has been decoded
*
* @param decoded the *decoded* and *verified* JWT received from the client in *request.headers.authorization*
* @param request the original *request* received from the client
* @param callback the validation callback
*/
validateFunc(decoded: {}, request: Request, callback: ValidateCallback): void;
/**
* Settings to define how tokens are verified by the jsonwebtoken library
*/
verifyOptions?: {
/**
* Ignore expired tokens
*/
ignoreExpiration?: boolean;
/**
* Do not enforce token audience
*/
audience?: boolean;
/**
* Do not require the issuer to be valid
*/
issuer?: boolean;
/**
* List of allowed algorithms
*/
algorithms?: string[];
};
/**
* function called to decorate the response with authentication headers
* before the response headers or payload is written
*
* @param request the Request object
* @param reply is called if an error occurred
*/
responseFunc?(request: Request, reply: (err: any, response: Response) => void): void;
/**
* If you prefer to pass your token via url, simply add a token url
* parameter to your request or use a custom parameter by setting `urlKey.
* To disable the url parameter set urlKey to `false` or ''.
* @default 'token'
*/
urlKey?: string | boolean;
/**
* If you prefer to set your own cookie key or your project has a cookie
* called 'token' for another purpose, you can set a custom key for your
* cookie by setting `options.cookieKey='yourkeyhere'`. To disable cookies
* set cookieKey to `false` or ''.
* @default 'token'
*/
cookieKey?: string | boolean;
/**
* If you want to set a custom key for your header token use the
* `headerKey` option. To disable header token set headerKey to `false` or
* ''.
* @default 'authorization'
*/
headerKey?: string | boolean;
/**
* Allow custom token type, e.g. `Authorization: <tokenType> 12345678`
*/
tokenType?: string;
/**
* Set to `true` to receive the complete token (`decoded.header`,
* `decoded.payload` and `decoded.signature`) as decoded argument to key
* lookup and `verifyFunc` callbacks (*not `validateFunc`*)
* @default false
*/
complete?: boolean;
}
}
declare var hapiAuthJwt2: PluginFunction<{}>;
export = hapiAuthJwt2;

View File

@@ -0,0 +1,40 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../../",
"typeRoots": [
"../../"
],
"types": [],
"paths": {
"hapi-auth-jwt2": [
"hapi-auth-jwt2/v7"
],
"boom": [
"boom/v4"
],
"catbox": [
"catbox/v7"
],
"hapi": [
"hapi/v16"
],
"inert": [
"inert/v4"
]
},
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"hapi-auth-jwt2-tests.ts"
]
}

View File

@@ -0,0 +1 @@
{ "extends": "dtslint/dt.json" }