0.0.5 • Published 12 months ago

nestjs-auth-http v0.0.5

Weekly downloads
-
License
MIT
Repository
github
Last release
12 months ago

Description

Promise based Axios module for Nest.

Installation

$ npm i --save nestjs-auth-http axios

Usage

interfaces/oauth-token.interface.ts
export interface OAuthToken {
    token_type: 'Basic' | 'Bearer' | 'Digest' | 'HOBA' | 'Mutual';
    access_token: string;
    expires_in: number;
    // ...
};
auth/jwt-auth.provider.ts
import { AuthProvider, Async, AuthHttpInstance } from 'nestjs-auth-http';
import { OAuthToken } from '../interfaces';

export class OAuthProvider extends AuthProvider<OAuthToken> {
    constructor () {
        super('Bearer'); // readonly type = 'Bearer';
    }

    override isWhitelisted(url: string): boolean {
        return url.includes('/oauth2/token');
    }

    override credentials(client: AuthHttpInstance<OAuthToken>): Async<OAuthToken> {
        return client.post('/oauth2/token', { /* payload */ })
            .then((response) => response.data);
    }

    override isExpired(credentials: OAuthToken): Async<boolean> {
        /* token verification */
        return false;
    }

    override toAuthorization(credentials: OAuthToken): string {
        return `${this.type} ${credentials.access_token}`;
    }

    /* Default
    isUnauthorizedError(error: any): boolean {
        return error?.response?.status === 401;
    }
     */
}
auth/jwt-auth.provider.ts
import { Module } from '@nestjs/common';
import { AuthHttpModule } from 'nestjs-auth-http';
import { JwtAuthProvider } from './auth';
import { FooController } from './controllers';


@Module({
    imports: [AuthHttpModule.register({
        baseURL: 'http://token.api',
        authProvider: new JwtAuthProvider(),
        onCreate(instance) { // Called after the instance is created.
            /* do something */
            /* instance.interceptors.request.use() */
        },
    })],
    controllers: [FooController],
})
export class AppModule {}
controllers/foo-controller.ts
import { Controller, Post } from '@nestjs/common';
import { AuthHttpService } from 'nestjs-auth-http';

@Controller('/foo')
export class FooController {
    constructor (private readonly httpService: AuthHttpService) {}

    @Post('/bar')
    async bar() {
        const response = await this.httpService.post('/hello/world', { /* payload */ });
        return response.data;
    }
}

License

MIT licensed.

0.0.5

12 months ago

0.0.4

12 months ago

0.0.3

12 months ago

0.0.2

12 months ago

0.0.1

12 months ago