mirror of
https://github.com/FlipsideCrypto/DefinitelyTyped.git
synced 2026-02-06 19:07:08 +00:00
[simple-oauth2] Update typings to 4.1 to match with original library (#46162)
* simple-oauth2: Update typings to 4.1 * reformat quote and comma * Update index.d.ts
This commit is contained in:
parent
e4bda82e86
commit
30ed97b647
250
types/simple-oauth2/index.d.ts
vendored
250
types/simple-oauth2/index.d.ts
vendored
@ -1,37 +1,35 @@
|
||||
// Type definitions for simple-oauth2 2.5
|
||||
// Type definitions for simple-oauth2 4.1
|
||||
// Project: https://github.com/lelylan/simple-oauth2
|
||||
// Definitions by: Michael Müller <https://github.com/mad-mike>,
|
||||
// Troy Lamerton <https://github.com/troy-lamerton>
|
||||
// Martín Rodriguez <https://github.com/netux>
|
||||
// Linus Unnebäck <https://github.com/LinusU>
|
||||
// Do Nam <https://github.com/namdien177>
|
||||
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
|
||||
// TypeScript Version: 2.9
|
||||
// TypeScript Version: 3.8
|
||||
|
||||
/** Creates a new simple-oauth2 client with the passed configuration */
|
||||
export function create<ClientIdName extends string = 'client_id'>(options: ModuleOptions<ClientIdName>): OAuthClient<ClientIdName>;
|
||||
|
||||
export interface ModuleOptions<ClientIdName extends string = 'client_id'> {
|
||||
export interface ModuleOptions<ClientIdName extends string = "client_id"> {
|
||||
client: {
|
||||
/** Service registered client id. Required. */
|
||||
id: string,
|
||||
id: string;
|
||||
/** Service registered client secret. Required. */
|
||||
secret: string,
|
||||
secret: string;
|
||||
/** Parameter name used to send the client secret. Default to client_secret. */
|
||||
secretParamName?: string,
|
||||
secretParamName?: string;
|
||||
/** Parameter name used to send the client id. Default to client_id. */
|
||||
idParamName?: ClientIdName
|
||||
idParamName?: ClientIdName;
|
||||
};
|
||||
auth: {
|
||||
/** String used to set the host to request the tokens to. Required. */
|
||||
tokenHost: string,
|
||||
tokenHost: string;
|
||||
/** String path to request an access token. Default to /oauth/token. */
|
||||
tokenPath?: string,
|
||||
tokenPath?: string;
|
||||
/** String path to revoke an access token. Default to /oauth/revoke. */
|
||||
revokePath?: string,
|
||||
revokePath?: string;
|
||||
/** String used to set the host to request an "authorization code". Default to the value set on auth.tokenHost. */
|
||||
authorizeHost?: string,
|
||||
authorizeHost?: string;
|
||||
/** String path to request an authorization code. Default to /oauth/authorize. */
|
||||
authorizePath?: string
|
||||
authorizePath?: string;
|
||||
};
|
||||
/**
|
||||
* Used to set global options to the internal http library (wreck).
|
||||
@ -41,13 +39,13 @@ export interface ModuleOptions<ClientIdName extends string = 'client_id'> {
|
||||
http?: {};
|
||||
options?: {
|
||||
/** Format of data sent in the request body. Defaults to form. */
|
||||
bodyFormat?: "json" | "form",
|
||||
bodyFormat?: "json" | "form";
|
||||
/**
|
||||
* Indicates the method used to send the client.id/client.secret authorization params at the token request.
|
||||
* If set to body, the bodyFormat option will be used to format the credentials.
|
||||
* Defaults to header
|
||||
*/
|
||||
authorizationMethod?: "header" | "body"
|
||||
authorizationMethod?: "header" | "body";
|
||||
};
|
||||
}
|
||||
|
||||
@ -58,48 +56,29 @@ export interface Token {
|
||||
}
|
||||
|
||||
export interface AccessToken {
|
||||
/**
|
||||
* Immutable object containing the token object provided while constructing a new access token instance.
|
||||
* This property will usually have the schema as specified by RFC6750,
|
||||
* but the exact properties may vary between authorization servers.
|
||||
*/
|
||||
token: Token;
|
||||
|
||||
/** Check if the access token is expired or not */
|
||||
expired(): boolean;
|
||||
/**
|
||||
* Determines if the current access token is definitely expired or not
|
||||
* @param expirationWindowSeconds Window of time before the actual expiration to refresh the token. Defaults to 0.
|
||||
*/
|
||||
expired(expirationWindowSeconds?: number): boolean;
|
||||
|
||||
/** Refresh the access token */
|
||||
refresh(params?: {}): Promise<AccessToken>;
|
||||
|
||||
/** Revoke access or refresh token */
|
||||
revoke(tokenType: TokenType): Promise<void>;
|
||||
|
||||
/** Revoke both the existing access and refresh tokens */
|
||||
revokeAll(): Promise<void>;
|
||||
}
|
||||
|
||||
export type AuthorizationCode = string;
|
||||
export interface AuthorizationTokenConfig {
|
||||
[key: string]: any;
|
||||
|
||||
/** Authorization code (from previous step) */
|
||||
code: AuthorizationCode;
|
||||
/** A string that represents the callback uri */
|
||||
redirect_uri: string;
|
||||
/** A string or array of strings that represents the application privileges */
|
||||
scope?: string | string[];
|
||||
}
|
||||
|
||||
export interface PasswordTokenConfig {
|
||||
[key: string]: any;
|
||||
|
||||
/** A string that represents the registered username */
|
||||
username: string;
|
||||
/** A string that represents the registered password. */
|
||||
password: string;
|
||||
/** A string or array of strings that represents the application privileges */
|
||||
scope: string | string[];
|
||||
}
|
||||
|
||||
export interface ClientCredentialTokenConfig {
|
||||
[key: string]: any;
|
||||
|
||||
/** A string that represents the application privileges */
|
||||
scope?: string | string[];
|
||||
}
|
||||
|
||||
export interface WreckHttpOptions {
|
||||
baseUrl?: string;
|
||||
socketPath?: string;
|
||||
@ -107,7 +86,14 @@ export interface WreckHttpOptions {
|
||||
headers?: { [key: string]: any };
|
||||
redirects?: number;
|
||||
redirect303?: boolean;
|
||||
beforeRedirect?: (redirectMethod: string, statusCode: number, location: string, resHeaders: { [key: string]: any }, redirectOptions: any, next: () => {}) => void;
|
||||
beforeRedirect?: (
|
||||
redirectMethod: string,
|
||||
statusCode: number,
|
||||
location: string,
|
||||
resHeaders: { [key: string]: any },
|
||||
redirectOptions: any,
|
||||
next: () => {},
|
||||
) => void;
|
||||
redirected?: (statusCode: number, location: string, req: any) => void;
|
||||
timeout?: number;
|
||||
maxBytes?: number;
|
||||
@ -121,42 +107,136 @@ export interface WreckHttpOptions {
|
||||
gunzip?: boolean | "force";
|
||||
}
|
||||
|
||||
export interface OAuthClient<ClientIdName extends string = 'client_id'> {
|
||||
authorizationCode: {
|
||||
/**
|
||||
* Redirect the user to the autorization page
|
||||
* @return the absolute authorization url
|
||||
*/
|
||||
authorizeURL(
|
||||
params?: {
|
||||
/** A string that represents the Client-ID */
|
||||
[key in ClientIdName]?: string
|
||||
} & {
|
||||
/** A string that represents the registered application URI where the user is redirected after authentication */
|
||||
redirect_uri?: string,
|
||||
/** A string or array of strings that represents the application privileges */
|
||||
scope?: string | string[],
|
||||
/** A string that represents an option opaque value used by the client to main the state between the request and the callback */
|
||||
state?: string
|
||||
}
|
||||
): string,
|
||||
/**
|
||||
* The [Authorization Code](https://oauth.net/2/grant-types/authorization-code/) grant type is used by confidential
|
||||
* and public clients to exchange an authorization code for an access token.
|
||||
* After the user returns to the client via the redirect URL,
|
||||
* the application will get the authorization code from the URL and use it to request an access token.
|
||||
*/
|
||||
export class AuthorizationCode<ClientIdName extends string = "client_id"> {
|
||||
constructor(options: ModuleOptions<ClientIdName>);
|
||||
|
||||
/** Returns the Access Token object */
|
||||
getToken(params: AuthorizationTokenConfig, httpOptions?: WreckHttpOptions): Promise<Token>;
|
||||
};
|
||||
/**
|
||||
* Get a valid redirect URL used to redirect users to an authorization page
|
||||
*
|
||||
* @param params
|
||||
* @param params.redirectURI String representing the registered application URI where the user is redirected after authentication
|
||||
* @param params.scope String or array of strings representing the application privileges
|
||||
* @param params.state String representing an opaque value used by the client to main the state between the request and the callback
|
||||
*
|
||||
* @return the absolute authorization url
|
||||
*/
|
||||
authorizeURL(
|
||||
params?: {
|
||||
/** A string that represents the Client-ID */
|
||||
[key in ClientIdName]?: string;
|
||||
} & {
|
||||
redirect_uri?: string;
|
||||
scope?: string | string[];
|
||||
state?: string;
|
||||
},
|
||||
): string;
|
||||
|
||||
ownerPassword: {
|
||||
/** Returns the Access Token Object */
|
||||
getToken(params: PasswordTokenConfig, httpOptions?: WreckHttpOptions): Promise<Token>;
|
||||
};
|
||||
/**
|
||||
* Requests and returns an access token from the authorization server
|
||||
*
|
||||
* @param params
|
||||
* @param params.code Authorization code received by the callback URL
|
||||
* @param params.redirectURI String representing the registered application URI where the user is redirected after authentication
|
||||
* @param [params.scope] String or array of strings representing the application privileges
|
||||
* @param [httpOptions] Optional http options passed through the underlying http library
|
||||
*/
|
||||
getToken(params: AuthorizationTokenConfig, httpOptions?: WreckHttpOptions): Promise<AccessToken>;
|
||||
|
||||
clientCredentials: {
|
||||
/** Returns the Access Token Object */
|
||||
getToken(params: ClientCredentialTokenConfig, httpOptions?: WreckHttpOptions): Promise<Token>;
|
||||
};
|
||||
|
||||
accessToken: {
|
||||
/** Creates an OAuth2.AccessToken instance */
|
||||
create(tokenToUse: Token, httpOptions?: WreckHttpOptions): AccessToken;
|
||||
};
|
||||
/**
|
||||
* Creates a new access token by providing a token object as specified by RFC6750.
|
||||
* @param token
|
||||
*/
|
||||
createToken(token: Token): AccessToken;
|
||||
}
|
||||
|
||||
export interface AuthorizationTokenConfig {
|
||||
/** Authorization code received by the callback URL */
|
||||
code: string;
|
||||
/** String representing the registered application URI where the user is redirected after authentication */
|
||||
redirect_uri: string;
|
||||
/** String or array of strings representing the application privileges */
|
||||
scope?: string | string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* The [Resource Owner Password Credentials](https://oauth.net/2/grant-types/password/) grant type
|
||||
* is a way to exchange a user's credentials for an access token.
|
||||
* Because the client application has to collect the user's password and send it to the authorization server,
|
||||
* it is not recommended that this grant be used at all anymore.
|
||||
*/
|
||||
export class ResourceOwnerPassword<ClientIdName extends string = "client_id"> {
|
||||
constructor(options: ModuleOptions<ClientIdName>);
|
||||
|
||||
/**
|
||||
* Requests and returns an access token from the authorization server
|
||||
*
|
||||
* @param params
|
||||
* @param params.username A string representing the registered username
|
||||
* @param params.password A string representing the registered password
|
||||
* @param [params.scope] A String or array of strings representing the application privileges
|
||||
* @param [httpOptions] Optional http options passed through the underlying http library
|
||||
*/
|
||||
getToken(params: PasswordTokenConfig, httpOptions?: WreckHttpOptions): Promise<AccessToken>;
|
||||
|
||||
/**
|
||||
* Creates a new access token by providing a token object as specified by RFC6750.
|
||||
*
|
||||
* @param token Plain object representation of an access token
|
||||
*/
|
||||
createToken(token: Token): AccessToken;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a new access token using the current grant type.
|
||||
*/
|
||||
export interface PasswordTokenConfig {
|
||||
/** A string that represents the registered username */
|
||||
username: string;
|
||||
/** A string that represents the registered password. */
|
||||
password: string;
|
||||
/** A string or array of strings that represents the application privileges */
|
||||
scope: string | string[];
|
||||
|
||||
/**
|
||||
* Additional options will be automatically serialized as params for the token request.
|
||||
*/
|
||||
[key: string]: any;
|
||||
}
|
||||
|
||||
/**
|
||||
* The [Client Credentials](https://oauth.net/2/grant-types/client-credentials/) grant type
|
||||
* is used by clients to obtain an access token outside of the context of a user.
|
||||
* This is typically used by clients to access resources about themselves rather than to access a user's resources.
|
||||
*/
|
||||
export class ClientCredentials<ClientIdName extends string = "client_id"> {
|
||||
constructor(options: ModuleOptions<ClientIdName>);
|
||||
|
||||
/**
|
||||
* Requests and returns an access token from the authorization server
|
||||
*
|
||||
* @param params
|
||||
* @param [params.scope] A String or array of strings representing the application privileges
|
||||
* @param [httpOptions] Optional http options passed through the underlying http library
|
||||
*/
|
||||
getToken(params: ClientCredentialTokenConfig, httpOptions?: WreckHttpOptions): Promise<AccessToken>;
|
||||
|
||||
/**
|
||||
* Creates a new access token by providing a token object as specified by RFC6750.
|
||||
*
|
||||
* @param token Plain object representation of an access token
|
||||
*/
|
||||
createToken(token: Token): AccessToken;
|
||||
}
|
||||
|
||||
export interface ClientCredentialTokenConfig {
|
||||
/** A string that represents the application privileges */
|
||||
scope?: string | string[];
|
||||
|
||||
[key: string]: any;
|
||||
}
|
||||
|
||||
@ -7,35 +7,42 @@ import * as oauth2lib from "simple-oauth2";
|
||||
// Set the configuration settings
|
||||
const credentials: oauth2lib.ModuleOptions = {
|
||||
client: {
|
||||
id: '<client-id>',
|
||||
secret: '<client-secret>'
|
||||
id: "<client-id>",
|
||||
secret: "<client-secret>",
|
||||
},
|
||||
auth: {
|
||||
tokenHost: 'https://api.oauth.com'
|
||||
}
|
||||
tokenHost: "https://api.oauth.com",
|
||||
},
|
||||
};
|
||||
|
||||
const oauth2 = oauth2lib.create(credentials);
|
||||
const oauth2AuthorizationCode = new oauth2lib.AuthorizationCode(credentials);
|
||||
const oauth2ClientCredentials = new oauth2lib.ClientCredentials(credentials);
|
||||
const oauth2ResourceOwnerPassword = new oauth2lib.ResourceOwnerPassword(
|
||||
credentials
|
||||
);
|
||||
|
||||
// Test custom `idParamName`
|
||||
{
|
||||
const oauth2 = oauth2lib.create({ client: { id: 'x', secret: 'x', idParamName: 'foobar' }, auth: { tokenHost: 'x' } });
|
||||
oauth2.authorizationCode.authorizeURL({ foobar: 'x' });
|
||||
const oauth2AuthorizationCode = new oauth2lib.AuthorizationCode({
|
||||
client: { id: "x", secret: "x", idParamName: "foobar" },
|
||||
auth: { tokenHost: "x" },
|
||||
});
|
||||
oauth2AuthorizationCode.authorizeURL({ foobar: "x" });
|
||||
}
|
||||
|
||||
// #Authorization Code flow
|
||||
(async () => {
|
||||
// Authorization oauth2 URI
|
||||
const authorizationUri = oauth2.authorizationCode.authorizeURL({
|
||||
redirect_uri: 'http://localhost:3000/callback',
|
||||
scope: '<scope>',
|
||||
state: '<state>'
|
||||
const authorizationUri = oauth2AuthorizationCode.authorizeURL({
|
||||
redirect_uri: "http://localhost:3000/callback",
|
||||
scope: "<scope>",
|
||||
state: "<state>",
|
||||
});
|
||||
|
||||
oauth2.authorizationCode.authorizeURL({
|
||||
redirect_uri: 'http://localhost:3000/callback',
|
||||
scope: ['<scope1>', '<scope2>'],
|
||||
state: '<state>'
|
||||
oauth2AuthorizationCode.authorizeURL({
|
||||
redirect_uri: "http://localhost:3000/callback",
|
||||
scope: ["<scope1>", "<scope2>"],
|
||||
state: "<state>",
|
||||
});
|
||||
|
||||
// Redirect example using Express (see http://expressjs.com/api.html#res.redirect)
|
||||
@ -43,34 +50,34 @@ const oauth2 = oauth2lib.create(credentials);
|
||||
|
||||
// Get the access token object (the authorization code is given from the previous step).
|
||||
const tokenConfig = {
|
||||
code: '<code>',
|
||||
redirect_uri: 'http://localhost:3000/callback',
|
||||
scope: ['<scope1>', '<scope2>']
|
||||
code: "<code>",
|
||||
redirect_uri: "http://localhost:3000/callback",
|
||||
scope: ["<scope1>", "<scope2>"],
|
||||
};
|
||||
|
||||
// Save the access token
|
||||
try {
|
||||
const result = await oauth2.authorizationCode.getToken(tokenConfig);
|
||||
const accessToken = oauth2.accessToken.create(result);
|
||||
const result = await oauth2AuthorizationCode.getToken(tokenConfig);
|
||||
const accessToken = oauth2AuthorizationCode.createToken(result.token);
|
||||
} catch (error) {
|
||||
console.log('Access Token Error', error.message);
|
||||
console.log("Access Token Error", error.message);
|
||||
}
|
||||
})();
|
||||
|
||||
// #Password Credentials Flow
|
||||
(async () => {
|
||||
const tokenConfig = {
|
||||
username: 'username',
|
||||
password: 'password',
|
||||
scope: [ '<scope1>', '<scope2>' ],
|
||||
username: "username",
|
||||
password: "password",
|
||||
scope: ["<scope1>", "<scope2>"],
|
||||
};
|
||||
|
||||
// Save the access token
|
||||
try {
|
||||
const result = await oauth2.ownerPassword.getToken(tokenConfig);
|
||||
const accessToken = oauth2.accessToken.create(result);
|
||||
const result = await oauth2ResourceOwnerPassword.getToken(tokenConfig);
|
||||
const accessToken = oauth2ResourceOwnerPassword.createToken(result.token);
|
||||
} catch (error) {
|
||||
console.log('Access Token Error', error.message);
|
||||
console.log("Access Token Error", error.message);
|
||||
}
|
||||
})();
|
||||
|
||||
@ -80,46 +87,51 @@ const oauth2 = oauth2lib.create(credentials);
|
||||
|
||||
// Get the access token object for the client
|
||||
try {
|
||||
const result = await oauth2.clientCredentials.getToken(tokenConfig);
|
||||
const accessToken = oauth2.accessToken.create(result);
|
||||
const result = await oauth2ClientCredentials.getToken(tokenConfig);
|
||||
const accessToken = oauth2ClientCredentials.createToken(result.token);
|
||||
} catch (error) {
|
||||
console.log('Access Token error', error.message);
|
||||
console.log("Access Token error", error.message);
|
||||
}
|
||||
})();
|
||||
|
||||
// #Access Token object
|
||||
(async () => {
|
||||
async function TestFnAccessTokenObject(
|
||||
oauthSubject:
|
||||
| oauth2lib.AuthorizationCode
|
||||
| oauth2lib.ClientCredentials
|
||||
| oauth2lib.ResourceOwnerPassword
|
||||
) {
|
||||
// Sample of a JSON access token (you got it through previous steps)
|
||||
const tokenObject = {
|
||||
access_token: '<access-token>',
|
||||
refresh_token: '<refresh-token>',
|
||||
expires_in: '7200'
|
||||
access_token: "<access-token>",
|
||||
refresh_token: "<refresh-token>",
|
||||
expires_in: "7200",
|
||||
};
|
||||
|
||||
// Create the access token wrapper
|
||||
let accessToken = oauth2.accessToken.create(tokenObject);
|
||||
let accessToken = oauthSubject.createToken(tokenObject);
|
||||
|
||||
// Check if the token is expired. If expired it is refreshed.
|
||||
if (accessToken.expired()) {
|
||||
try {
|
||||
accessToken = await accessToken.refresh();
|
||||
} catch (error) {
|
||||
console.log('Error refreshing access token: ', error.message);
|
||||
console.log("Error refreshing access token: ", error.message);
|
||||
}
|
||||
}
|
||||
|
||||
// Revoke both access and refresh tokens
|
||||
try {
|
||||
// Revoke only the access token
|
||||
await accessToken.revoke('access_token');
|
||||
await accessToken.revoke("access_token");
|
||||
|
||||
// Session ended. But the refresh_token is still valid.
|
||||
// Revoke the refresh token
|
||||
await accessToken.revoke('refresh_token');
|
||||
await accessToken.revoke("refresh_token");
|
||||
|
||||
console.log('Token revoked');
|
||||
console.log("Token revoked");
|
||||
} catch (error) {
|
||||
console.log('Error revoking token: ', error.message);
|
||||
console.log("Error revoking token: ", error.message);
|
||||
}
|
||||
|
||||
// or...
|
||||
@ -128,15 +140,20 @@ const oauth2 = oauth2lib.create(credentials);
|
||||
// Revokes both tokens, refresh token is only revoked if the access_token is properly revoked
|
||||
await accessToken.revokeAll();
|
||||
} catch (error) {
|
||||
console.log('Error revoking token: ', error.message);
|
||||
console.log("Error revoking token: ", error.message);
|
||||
}
|
||||
})();
|
||||
}
|
||||
|
||||
// #Run test `#Access Token object`
|
||||
TestFnAccessTokenObject(oauth2AuthorizationCode);
|
||||
TestFnAccessTokenObject(oauth2ClientCredentials);
|
||||
TestFnAccessTokenObject(oauth2ResourceOwnerPassword);
|
||||
|
||||
// #Errors
|
||||
// not applicable, as those errors about missing authentication codes are already found by the typescript compiler
|
||||
|
||||
// (function () {
|
||||
// oauth2.authorizationCode.getToken({})
|
||||
// oauth2AuthorizationCode.getToken({})
|
||||
// .catch((error) => {
|
||||
// console.log(error.message);
|
||||
// });
|
||||
@ -147,17 +164,17 @@ const oauth2 = oauth2lib.create(credentials);
|
||||
// #Custom Grant
|
||||
(async () => {
|
||||
const tokenConfig = {
|
||||
username: 'username',
|
||||
password: 'password',
|
||||
scope: [ '<scope1>', '<scope2>' ],
|
||||
grant_type: 'openapi_2lo'
|
||||
username: "username",
|
||||
password: "password",
|
||||
scope: ["<scope1>", "<scope2>"],
|
||||
grant_type: "openapi_2lo",
|
||||
};
|
||||
|
||||
// Save the access token
|
||||
try {
|
||||
const result = await oauth2.ownerPassword.getToken(tokenConfig);
|
||||
const accessToken = oauth2.accessToken.create(result);
|
||||
const result = await oauth2ResourceOwnerPassword.getToken(tokenConfig);
|
||||
const accessToken = oauth2ResourceOwnerPassword.createToken(result.token);
|
||||
} catch (error) {
|
||||
console.log('Access Token Error', error.message);
|
||||
console.log("Access Token Error", error.message);
|
||||
}
|
||||
})();
|
||||
|
||||
162
types/simple-oauth2/v2/index.d.ts
vendored
Normal file
162
types/simple-oauth2/v2/index.d.ts
vendored
Normal file
@ -0,0 +1,162 @@
|
||||
// Type definitions for simple-oauth2 2.5
|
||||
// Project: https://github.com/lelylan/simple-oauth2
|
||||
// Definitions by: Michael Müller <https://github.com/mad-mike>,
|
||||
// Troy Lamerton <https://github.com/troy-lamerton>
|
||||
// Martín Rodriguez <https://github.com/netux>
|
||||
// Linus Unnebäck <https://github.com/LinusU>
|
||||
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
|
||||
// TypeScript Version: 2.9
|
||||
|
||||
/** Creates a new simple-oauth2 client with the passed configuration */
|
||||
export function create<ClientIdName extends string = 'client_id'>(options: ModuleOptions<ClientIdName>): OAuthClient<ClientIdName>;
|
||||
|
||||
export interface ModuleOptions<ClientIdName extends string = 'client_id'> {
|
||||
client: {
|
||||
/** Service registered client id. Required. */
|
||||
id: string,
|
||||
/** Service registered client secret. Required. */
|
||||
secret: string,
|
||||
/** Parameter name used to send the client secret. Default to client_secret. */
|
||||
secretParamName?: string,
|
||||
/** Parameter name used to send the client id. Default to client_id. */
|
||||
idParamName?: ClientIdName
|
||||
};
|
||||
auth: {
|
||||
/** String used to set the host to request the tokens to. Required. */
|
||||
tokenHost: string,
|
||||
/** String path to request an access token. Default to /oauth/token. */
|
||||
tokenPath?: string,
|
||||
/** String path to revoke an access token. Default to /oauth/revoke. */
|
||||
revokePath?: string,
|
||||
/** String used to set the host to request an "authorization code". Default to the value set on auth.tokenHost. */
|
||||
authorizeHost?: string,
|
||||
/** String path to request an authorization code. Default to /oauth/authorize. */
|
||||
authorizePath?: string
|
||||
};
|
||||
/**
|
||||
* Used to set global options to the internal http library (wreck).
|
||||
* All options except baseUrl are allowed
|
||||
* Defaults to header.Accept = "application/json"
|
||||
*/
|
||||
http?: {};
|
||||
options?: {
|
||||
/** Format of data sent in the request body. Defaults to form. */
|
||||
bodyFormat?: "json" | "form",
|
||||
/**
|
||||
* Indicates the method used to send the client.id/client.secret authorization params at the token request.
|
||||
* If set to body, the bodyFormat option will be used to format the credentials.
|
||||
* Defaults to header
|
||||
*/
|
||||
authorizationMethod?: "header" | "body"
|
||||
};
|
||||
}
|
||||
|
||||
export type TokenType = "access_token" | "refresh_token";
|
||||
|
||||
export interface Token {
|
||||
[x: string]: any;
|
||||
}
|
||||
|
||||
export interface AccessToken {
|
||||
token: Token;
|
||||
|
||||
/** Check if the access token is expired or not */
|
||||
expired(): boolean;
|
||||
/** Refresh the access token */
|
||||
refresh(params?: {}): Promise<AccessToken>;
|
||||
/** Revoke access or refresh token */
|
||||
revoke(tokenType: TokenType): Promise<void>;
|
||||
/** Revoke both the existing access and refresh tokens */
|
||||
revokeAll(): Promise<void>;
|
||||
}
|
||||
|
||||
export type AuthorizationCode = string;
|
||||
export interface AuthorizationTokenConfig {
|
||||
[key: string]: any;
|
||||
|
||||
/** Authorization code (from previous step) */
|
||||
code: AuthorizationCode;
|
||||
/** A string that represents the callback uri */
|
||||
redirect_uri: string;
|
||||
/** A string or array of strings that represents the application privileges */
|
||||
scope?: string | string[];
|
||||
}
|
||||
|
||||
export interface PasswordTokenConfig {
|
||||
[key: string]: any;
|
||||
|
||||
/** A string that represents the registered username */
|
||||
username: string;
|
||||
/** A string that represents the registered password. */
|
||||
password: string;
|
||||
/** A string or array of strings that represents the application privileges */
|
||||
scope: string | string[];
|
||||
}
|
||||
|
||||
export interface ClientCredentialTokenConfig {
|
||||
[key: string]: any;
|
||||
|
||||
/** A string that represents the application privileges */
|
||||
scope?: string | string[];
|
||||
}
|
||||
|
||||
export interface WreckHttpOptions {
|
||||
baseUrl?: string;
|
||||
socketPath?: string;
|
||||
payload?: any;
|
||||
headers?: { [key: string]: any };
|
||||
redirects?: number;
|
||||
redirect303?: boolean;
|
||||
beforeRedirect?: (redirectMethod: string, statusCode: number, location: string, resHeaders: { [key: string]: any }, redirectOptions: any, next: () => {}) => void;
|
||||
redirected?: (statusCode: number, location: string, req: any) => void;
|
||||
timeout?: number;
|
||||
maxBytes?: number;
|
||||
rejectUnauthorized?: boolean;
|
||||
downstreamRes?: any;
|
||||
agent?: any;
|
||||
secureProtocol?: string;
|
||||
ciphers?: string;
|
||||
events?: boolean;
|
||||
json?: true | "strict" | "force";
|
||||
gunzip?: boolean | "force";
|
||||
}
|
||||
|
||||
export interface OAuthClient<ClientIdName extends string = 'client_id'> {
|
||||
authorizationCode: {
|
||||
/**
|
||||
* Redirect the user to the autorization page
|
||||
* @return the absolute authorization url
|
||||
*/
|
||||
authorizeURL(
|
||||
params?: {
|
||||
/** A string that represents the Client-ID */
|
||||
[key in ClientIdName]?: string
|
||||
} & {
|
||||
/** A string that represents the registered application URI where the user is redirected after authentication */
|
||||
redirect_uri?: string,
|
||||
/** A string or array of strings that represents the application privileges */
|
||||
scope?: string | string[],
|
||||
/** A string that represents an option opaque value used by the client to main the state between the request and the callback */
|
||||
state?: string
|
||||
}
|
||||
): string,
|
||||
|
||||
/** Returns the Access Token object */
|
||||
getToken(params: AuthorizationTokenConfig, httpOptions?: WreckHttpOptions): Promise<Token>;
|
||||
};
|
||||
|
||||
ownerPassword: {
|
||||
/** Returns the Access Token Object */
|
||||
getToken(params: PasswordTokenConfig, httpOptions?: WreckHttpOptions): Promise<Token>;
|
||||
};
|
||||
|
||||
clientCredentials: {
|
||||
/** Returns the Access Token Object */
|
||||
getToken(params: ClientCredentialTokenConfig, httpOptions?: WreckHttpOptions): Promise<Token>;
|
||||
};
|
||||
|
||||
accessToken: {
|
||||
/** Creates an OAuth2.AccessToken instance */
|
||||
create(tokenToUse: Token, httpOptions?: WreckHttpOptions): AccessToken;
|
||||
};
|
||||
}
|
||||
163
types/simple-oauth2/v2/simple-oauth2-tests.ts
Normal file
163
types/simple-oauth2/v2/simple-oauth2-tests.ts
Normal file
@ -0,0 +1,163 @@
|
||||
// off https://github.com/lelylan/simple-oauth2/blob/master/README.md
|
||||
// slightly changed to remove external dependencies
|
||||
|
||||
// Initialize the OAuth2 Library
|
||||
import * as oauth2lib from "simple-oauth2";
|
||||
|
||||
// Set the configuration settings
|
||||
const credentials: oauth2lib.ModuleOptions = {
|
||||
client: {
|
||||
id: '<client-id>',
|
||||
secret: '<client-secret>'
|
||||
},
|
||||
auth: {
|
||||
tokenHost: 'https://api.oauth.com'
|
||||
}
|
||||
};
|
||||
|
||||
const oauth2 = oauth2lib.create(credentials);
|
||||
|
||||
// Test custom `idParamName`
|
||||
{
|
||||
const oauth2 = oauth2lib.create({ client: { id: 'x', secret: 'x', idParamName: 'foobar' }, auth: { tokenHost: 'x' } });
|
||||
oauth2.authorizationCode.authorizeURL({ foobar: 'x' });
|
||||
}
|
||||
|
||||
// #Authorization Code flow
|
||||
(async () => {
|
||||
// Authorization oauth2 URI
|
||||
const authorizationUri = oauth2.authorizationCode.authorizeURL({
|
||||
redirect_uri: 'http://localhost:3000/callback',
|
||||
scope: '<scope>',
|
||||
state: '<state>'
|
||||
});
|
||||
|
||||
oauth2.authorizationCode.authorizeURL({
|
||||
redirect_uri: 'http://localhost:3000/callback',
|
||||
scope: ['<scope1>', '<scope2>'],
|
||||
state: '<state>'
|
||||
});
|
||||
|
||||
// Redirect example using Express (see http://expressjs.com/api.html#res.redirect)
|
||||
// res.redirect(authorizationUri);
|
||||
|
||||
// Get the access token object (the authorization code is given from the previous step).
|
||||
const tokenConfig = {
|
||||
code: '<code>',
|
||||
redirect_uri: 'http://localhost:3000/callback',
|
||||
scope: ['<scope1>', '<scope2>']
|
||||
};
|
||||
|
||||
// Save the access token
|
||||
try {
|
||||
const result = await oauth2.authorizationCode.getToken(tokenConfig);
|
||||
const accessToken = oauth2.accessToken.create(result);
|
||||
} catch (error) {
|
||||
console.log('Access Token Error', error.message);
|
||||
}
|
||||
})();
|
||||
|
||||
// #Password Credentials Flow
|
||||
(async () => {
|
||||
const tokenConfig = {
|
||||
username: 'username',
|
||||
password: 'password',
|
||||
scope: [ '<scope1>', '<scope2>' ],
|
||||
};
|
||||
|
||||
// Save the access token
|
||||
try {
|
||||
const result = await oauth2.ownerPassword.getToken(tokenConfig);
|
||||
const accessToken = oauth2.accessToken.create(result);
|
||||
} catch (error) {
|
||||
console.log('Access Token Error', error.message);
|
||||
}
|
||||
})();
|
||||
|
||||
// #Client Credentials Flow
|
||||
(async () => {
|
||||
const tokenConfig = {};
|
||||
|
||||
// Get the access token object for the client
|
||||
try {
|
||||
const result = await oauth2.clientCredentials.getToken(tokenConfig);
|
||||
const accessToken = oauth2.accessToken.create(result);
|
||||
} catch (error) {
|
||||
console.log('Access Token error', error.message);
|
||||
}
|
||||
})();
|
||||
|
||||
// #Access Token object
|
||||
(async () => {
|
||||
// Sample of a JSON access token (you got it through previous steps)
|
||||
const tokenObject = {
|
||||
access_token: '<access-token>',
|
||||
refresh_token: '<refresh-token>',
|
||||
expires_in: '7200'
|
||||
};
|
||||
|
||||
// Create the access token wrapper
|
||||
let accessToken = oauth2.accessToken.create(tokenObject);
|
||||
|
||||
// Check if the token is expired. If expired it is refreshed.
|
||||
if (accessToken.expired()) {
|
||||
try {
|
||||
accessToken = await accessToken.refresh();
|
||||
} catch (error) {
|
||||
console.log('Error refreshing access token: ', error.message);
|
||||
}
|
||||
}
|
||||
|
||||
// Revoke both access and refresh tokens
|
||||
try {
|
||||
// Revoke only the access token
|
||||
await accessToken.revoke('access_token');
|
||||
|
||||
// Session ended. But the refresh_token is still valid.
|
||||
// Revoke the refresh token
|
||||
await accessToken.revoke('refresh_token');
|
||||
|
||||
console.log('Token revoked');
|
||||
} catch (error) {
|
||||
console.log('Error revoking token: ', error.message);
|
||||
}
|
||||
|
||||
// or...
|
||||
|
||||
try {
|
||||
// Revokes both tokens, refresh token is only revoked if the access_token is properly revoked
|
||||
await accessToken.revokeAll();
|
||||
} catch (error) {
|
||||
console.log('Error revoking token: ', error.message);
|
||||
}
|
||||
})();
|
||||
|
||||
// #Errors
|
||||
// not applicable, as those errors about missing authentication codes are already found by the typescript compiler
|
||||
|
||||
// (function () {
|
||||
// oauth2.authorizationCode.getToken({})
|
||||
// .catch((error) => {
|
||||
// console.log(error.message);
|
||||
// });
|
||||
|
||||
// // => { "status": "401", "message": "Unauthorized" }
|
||||
// })();
|
||||
|
||||
// #Custom Grant
|
||||
(async () => {
|
||||
const tokenConfig = {
|
||||
username: 'username',
|
||||
password: 'password',
|
||||
scope: [ '<scope1>', '<scope2>' ],
|
||||
grant_type: 'openapi_2lo'
|
||||
};
|
||||
|
||||
// Save the access token
|
||||
try {
|
||||
const result = await oauth2.ownerPassword.getToken(tokenConfig);
|
||||
const accessToken = oauth2.accessToken.create(result);
|
||||
} catch (error) {
|
||||
console.log('Access Token Error', error.message);
|
||||
}
|
||||
})();
|
||||
32
types/simple-oauth2/v2/tsconfig.json
Normal file
32
types/simple-oauth2/v2/tsconfig.json
Normal file
@ -0,0 +1,32 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"module": "commonjs",
|
||||
"lib": [
|
||||
"es6",
|
||||
"dom"
|
||||
],
|
||||
"noImplicitAny": true,
|
||||
"noImplicitThis": true,
|
||||
"strictNullChecks": true,
|
||||
"strictFunctionTypes": true,
|
||||
"baseUrl": "../../",
|
||||
"typeRoots": [
|
||||
"../../"
|
||||
],
|
||||
"paths": {
|
||||
"simple-oauth2": [
|
||||
"simple-oauth2/v2"
|
||||
],
|
||||
"simple-oauth2/*": [
|
||||
"simple-oauth2/v2/*"
|
||||
]
|
||||
},
|
||||
"types": [],
|
||||
"noEmit": true,
|
||||
"forceConsistentCasingInFileNames": true
|
||||
},
|
||||
"files": [
|
||||
"index.d.ts",
|
||||
"simple-oauth2-tests.ts"
|
||||
]
|
||||
}
|
||||
1
types/simple-oauth2/v2/tslint.json
Normal file
1
types/simple-oauth2/v2/tslint.json
Normal file
@ -0,0 +1 @@
|
||||
{ "extends": "dtslint/dt.json" }
|
||||
Loading…
Reference in New Issue
Block a user