Skip to content

flexbase-eng/http-client-middleware

Repository files navigation

Coverage Quality Gate Status

http-client-middleware

This is a middleware package to wrap http authentication.

Usage

Using wretch

Client Credentials

const clientCredentials = {
  tokenUrl: "https://some.url/auth/token",
  refreshTokenUrl: "https://some.url/auth/refresh",
  clientId: "myclient id",
  clientSecret: "super secret"
};

class SimpleAuthenticationTokenStore implements AuthenticationTokenStore {
    private _authenticationToken: AuthenticationToken | null = null;

    retrieveToken(): IAuthenticationToken | null {
        return this._authenticationToken;
    }

    storeToken(token: IAuthenticationToken | null): void {
        this._authenticationToken = token;
    }
}

const authMiddleware = authenticationTokenMiddleware({
    credentialProvider: () => clientCredentials,
    tokenAccessor: new ClientCredentialsAuthenticationTokenAccessor(),
    tokenStore: new SimpleAuthenticationTokenStore()
});

wretch(...).middlewares([authMiddleware]);

Password Credentials

// for password creds we only need to supply the urls as user/pass will come from a login form
const passwordCredentials = {
  tokenUrl: "https://some.url/auth/token",
  refreshTokenUrl: "https://some.url/auth/refresh",
};

class SimpleAuthenticationTokenStore implements AuthenticationTokenStore {
    private _authenticationToken: AuthenticationToken | null = null;

    retrieveToken(): IAuthenticationToken | null {
        return this._authenticationToken;
    }

    storeToken(token: IAuthenticationToken | null): void {
        this._authenticationToken = token;
    }
}

const authMiddleware = authenticationTokenMiddleware({
    credentialProvider: () => passwordCredentials,
    tokenAccessor: new PasswordAuthenticationTokenAccessor(),
    tokenStore: new SimpleAuthenticationTokenStore()
});

wretch(...).middlewares([authMiddleware]);