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

Add PKCE support (for v5-dev Typescript) #659

Open
wants to merge 1 commit into
base: v5-dev
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
138 changes: 78 additions & 60 deletions docs/model/spec.rst
Original file line number Diff line number Diff line change
Expand Up @@ -336,25 +336,29 @@ This model function is **required** if the ``authorization_code`` grant is used.

An ``Object`` representing the authorization code and associated data.

+--------------------+--------+--------------------------------------------------------------+
| Name | Type | Description |
+====================+========+==============================================================+
| code | Object | The return value. |
+--------------------+--------+--------------------------------------------------------------+
| code.code | String | The authorization code passed to ``getAuthorizationCode()``. |
+--------------------+--------+--------------------------------------------------------------+
| code.expiresAt | Date | The expiry time of the authorization code. |
+--------------------+--------+--------------------------------------------------------------+
| [code.redirectUri] | String | The redirect URI of the authorization code. |
+--------------------+--------+--------------------------------------------------------------+
| [code.scope] | String | The authorized scope of the authorization code. |
+--------------------+--------+--------------------------------------------------------------+
| code.client | Object | The client associated with the authorization code. |
+--------------------+--------+--------------------------------------------------------------+
| code.client.id | String | A unique string identifying the client. |
+--------------------+--------+--------------------------------------------------------------+
| code.user | Object | The user associated with the authorization code. |
+--------------------+--------+--------------------------------------------------------------+
+----------------------------+--------+---------------------------------------------------------------+
| Name | Type | Description |
+============================+========+===============================================================+
| code | Object | The return value. |
+----------------------------+--------+---------------------------------------------------------------+
| code.code | String | The authorization code passed to ``getAuthorizationCode()``. |
+----------------------------+--------+---------------------------------------------------------------+
| code.expiresAt | Date | The expiry time of the authorization code. |
+----------------------------+--------+---------------------------------------------------------------+
| [code.redirectUri] | String | The redirect URI of the authorization code. |
+----------------------------+--------+---------------------------------------------------------------+
| [code.scope] | String | The authorized scope of the authorization code. |
+----------------------------+--------+---------------------------------------------------------------+
| code.client | Object | The client associated with the authorization code. |
+----------------------------+--------+---------------------------------------------------------------+
| code.client.id | String | A unique string identifying the client. |
+----------------------------+--------+---------------------------------------------------------------+
| code.user | Object | The user associated with the authorization code. |
+----------------------------+--------+---------------------------------------------------------------+
| [code.codeChallenge] | String | The code challenge string used with PKCE (RFC7636). |
+----------------------------+--------+---------------------------------------------------------------+
| [code.codeChallengeMethod] | String | The string for the code challenge method (`S256` or `plain`). |
+----------------------------+--------+---------------------------------------------------------------+

``code.client`` and ``code.user`` can carry additional properties that will be ignored by *oauth2-server*.

Expand All @@ -379,7 +383,9 @@ An ``Object`` representing the authorization code and associated data.
redirectUri: code.redirect_uri,
scope: code.scope,
client: client, // with 'id' property
user: user
user: user,
codeChallenge: code.code_challenge,
codeChallengeMethod: code.code_challenge_method
};
});
}
Expand Down Expand Up @@ -665,51 +671,59 @@ This model function is **required** if the ``authorization_code`` grant is used.

**Arguments:**

+------------------------+----------+---------------------------------------------------------------------+
| Name | Type | Description |
+========================+==========+=====================================================================+
| code | Object | The code to be saved. |
+------------------------+----------+---------------------------------------------------------------------+
| code.authorizationCode | String | The authorization code to be saved. |
+------------------------+----------+---------------------------------------------------------------------+
| code.expiresAt | Date | The expiry time of the authorization code. |
+------------------------+----------+---------------------------------------------------------------------+
| code.redirectUri | String | The redirect URI associated with the authorization code. |
+------------------------+----------+---------------------------------------------------------------------+
| [code.scope] | String | The authorized scope of the authorization code. |
+------------------------+----------+---------------------------------------------------------------------+
| client | Object | The client associated with the authorization code. |
+------------------------+----------+---------------------------------------------------------------------+
| user | Object | The user associated with the authorization code. |
+------------------------+----------+---------------------------------------------------------------------+
| [callback] | Function | Node-style callback to be used instead of the returned ``Promise``. |
+------------------------+----------+---------------------------------------------------------------------+
+----------------------------+----------+---------------------------------------------------------------------+
| Name | Type | Description |
+============================+==========+=====================================================================+
| code | Object | The code to be saved. |
+----------------------------+----------+---------------------------------------------------------------------+
| code.authorizationCode | String | The authorization code to be saved. |
+----------------------------+----------+---------------------------------------------------------------------+
| code.expiresAt | Date | The expiry time of the authorization code. |
+----------------------------+----------+---------------------------------------------------------------------+
| code.redirectUri | String | The redirect URI associated with the authorization code. |
+----------------------------+----------+---------------------------------------------------------------------+
| [code.scope] | String | The authorized scope of the authorization code. |
+----------------------------+----------+---------------------------------------------------------------------+
| [code.codeChallenge] | String | The code challenge string used with PKCE (RFC7636). |
+----------------------------+----------+---------------------------------------------------------------------+
| [code.codeChallengeMethod] | String | The string for the code challenge method (`S256` or `plain`). |
+----------------------------+----------+---------------------------------------------------------------------+
| client | Object | The client associated with the authorization code. |
+----------------------------+----------+---------------------------------------------------------------------+
| user | Object | The user associated with the authorization code. |
+----------------------------+----------+---------------------------------------------------------------------+
| [callback] | Function | Node-style callback to be used instead of the returned ``Promise``. |
+----------------------------+----------+---------------------------------------------------------------------+

.. todo:: Is ``code.scope`` really optional?

**Return value:**

An ``Object`` representing the authorization code and associated data.

+------------------------+--------+---------------------------------------------------------------+
| Name | Type | Description |
+========================+========+===============================================================+
| code | Object | The return value. |
+------------------------+--------+---------------------------------------------------------------+
| code.authorizationCode | String | The authorization code passed to ``saveAuthorizationCode()``. |
+------------------------+--------+---------------------------------------------------------------+
| code.expiresAt | Date | The expiry time of the authorization code. |
+------------------------+--------+---------------------------------------------------------------+
| code.redirectUri | String | The redirect URI associated with the authorization code. |
+------------------------+--------+---------------------------------------------------------------+
| [code.scope] | String | The authorized scope of the authorization code. |
+------------------------+--------+---------------------------------------------------------------+
| code.client | Object | The client associated with the authorization code. |
+------------------------+--------+---------------------------------------------------------------+
| code.client.id | String | A unique string identifying the client. |
+------------------------+--------+---------------------------------------------------------------+
| code.user | Object | The user associated with the authorization code. |
+------------------------+--------+---------------------------------------------------------------+
+----------------------------+--------+----------------------------------------------------------------+
| Name | Type | Description |
+============================+========+================================================================+
| code | Object | The return value. |
+----------------------------+--------+----------------------------------------------------------------+
| code.authorizationCode | String | The authorization code passed to ``saveAuthorizationCode()``. |
+----------------------------+--------+----------------------------------------------------------------+
| code.expiresAt | Date | The expiry time of the authorization code. |
+----------------------------+--------+----------------------------------------------------------------+
| code.redirectUri | String | The redirect URI associated with the authorization code. |
+----------------------------+--------+----------------------------------------------------------------+
| [code.scope] | String | The authorized scope of the authorization code. |
+----------------------------+--------+----------------------------------------------------------------+
| code.client | Object | The client associated with the authorization code. |
+----------------------------+--------+----------------------------------------------------------------+
| code.client.id | String | A unique string identifying the client. |
+----------------------------+--------+----------------------------------------------------------------+
| code.user | Object | The user associated with the authorization code. |
+----------------------------+--------+----------------------------------------------------------------+
| [code.codeChallenge] | String | The code challenge string used with PKCE (RFC7636). |
+----------------------------+--------+----------------------------------------------------------------+
| [code.codeChallengeMethod] | String | The string for the code challenge method (`S256` or `plain` |
+----------------------------+--------+----------------------------------------------------------------+

``code.client`` and ``code.user`` can carry additional properties that will be ignored by *oauth2-server*.

Expand All @@ -725,7 +739,9 @@ An ``Object`` representing the authorization code and associated data.
redirect_uri: code.redirectUri,
scope: code.scope,
client_id: client.id,
user_id: user.id
user_id: user.id,
code_challenge: code.codeChallenge,
code_challenge_method: code.codeChallengeMethod
};
return db.saveAuthorizationCode(authCode)
.then(function(authorizationCode) {
Expand All @@ -735,7 +751,9 @@ An ``Object`` representing the authorization code and associated data.
redirectUri: authorizationCode.redirect_uri,
scope: authorizationCode.scope,
client: {id: authorizationCode.client_id},
user: {id: authorizationCode.user_id}
user: {id: authorizationCode.user_id},
codeChallenge: authorizationCode.code_challenge,
codeChallengeMethod: authorizationCode.code_challenge_method
};
});
}
Expand Down
29 changes: 29 additions & 0 deletions lib/grant-types/authorization-code-grant-type.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import {
import { AuthorizationCode, Client, Token, User } from '../interfaces';
import { Request } from '../request';
import * as is from '../validator/is';
import * as crypto from 'crypto';
import * as stringUtil from '../utils/string-util';

export class AuthorizationCodeGrantType extends AbstractGrantType {
constructor(options: any = {}) {
Expand Down Expand Up @@ -117,6 +119,33 @@ export class AuthorizationCodeGrantType extends AbstractGrantType {
);
}

if (code.codeChallenge) {
if (!request.body.code_verifier) {
throw new InvalidGrantError('Missing parameter: `code_verifier`');
}

let hash;
switch (code.codeChallengeMethod) {
case 'plain':
hash = request.body.code_verifier;
break;
case 'S256':
hash = stringUtil.base64URLEncode(crypto.createHash('sha256').update(request.body.code_verifier).digest());
break;
default:
throw new ServerError('Server error: `getAuthorizationCode()` did not return a valid `codeChallengeMethod` property');
}

if (code.codeChallenge !== hash) {
throw new InvalidGrantError('Invalid grant: code verifier is invalid');
}
} else {
if (request.body.code_verifier) {
// No code challenge but code_verifier was passed in.
throw new InvalidGrantError('Invalid grant: code verifier is invalid');
}
}

return code;
}

Expand Down
32 changes: 29 additions & 3 deletions lib/handlers/token-handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,11 @@ import { BearerTokenType } from '../token-types';
import { hasOwnProperty } from '../utils/fn';
import * as is from '../validator/is';

interface ClientCredentials {
clientId: string;
clientSecret?: string;
}

/**
* Grant types.
*/
Expand Down Expand Up @@ -127,17 +132,19 @@ export class TokenHandler {
* Get the client from the model.
*/

async getClient(request, response) {
const credentials = this.getClientCredentials(request);
async getClient(request: Request, response: Response) {
const credentials: ClientCredentials = this.getClientCredentials(request);
const grantType = request.body.grant_type;
const isPkce = this.isPKCERequest(request, grantType);

if (!credentials.clientId) {
throw new InvalidRequestError('Missing parameter: `client_id`');
}

if (
this.isClientAuthenticationRequired(grantType) &&
!credentials.clientSecret
!credentials.clientSecret &&
!isPkce
) {
throw new InvalidRequestError('Missing parameter: `client_secret`');
}
Expand Down Expand Up @@ -209,6 +216,12 @@ export class TokenHandler {
};
}

if (this.isPKCERequest(request, grantType)) {
if (request.body.client_id) {
return { clientId: request.body.client_id };
}
}

if (
!this.isClientAuthenticationRequired(grantType) &&
request.body.client_id
Expand Down Expand Up @@ -328,4 +341,17 @@ export class TokenHandler {

return true;
}

/**
* Check if the request is a PCKE request. We assume PKCE if grant type is 'authorization_code'
* and code verifier is present.
*/
isPKCERequest(request: Request, grantType: string): boolean {
if (grantType === 'authorization_code' && request.body.code_verifier) {
return true;
}

return false;
}

}
2 changes: 2 additions & 0 deletions lib/interfaces/authorization-code.interface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,5 +10,7 @@ export interface AuthorizationCode {
scope?: string;
client: Client;
user: User;
codeChallenge?: string;
codeChallengeMethod?: 'S256' | 'plain' | null;
[key: string]: any;
}
Loading