4.0.7 • Published 2 months ago

@travetto/auth-rest-jwt v4.0.7

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

Rest Auth JWT

Rest authentication JWT integration support for the Travetto framework

Install: @travetto/auth-rest-jwt

npm install @travetto/auth-rest-jwt

# or

yarn add @travetto/auth-rest-jwt

One of Rest Auth's main responsibilities is being able to send and receive authentication/authorization information from the client. This data can be encoded in many different forms, and this module provides the ability to encode into and decode from JWTs. This module fulfills the contract required by Rest Auth of being able to encode and decode a user principal, by leveraging JWT's token generation features.

The token can be encoded as a cookie or as a header depending on configuration. Additionally, the encoding process allows for auto-renewing of the token if that is desired. When encoding as a cookie, this becomes a seamless experience, and can be understood as a light-weight session.

The JWTPrincipalEncoder is exposed as a tool for allowing for converting an authenticated principal into a JWT, and back again.

Code: JWTPrincipalEncoder

import { Principal } from '@travetto/auth';
import { AuthService, PrincipalEncoder } from '@travetto/auth-rest';
import { AppError, Env, TimeUtil } from '@travetto/base';
import { Config } from '@travetto/config';
import { Inject, Injectable } from '@travetto/di';
import { FilterContext } from '@travetto/rest';
import { JWTUtil, Payload } from '@travetto/jwt';
import { Ignore } from '@travetto/schema';

@Config('rest.auth.jwt')
export class RestJWTConfig {
  mode: 'cookie' | 'header' | 'all' = 'header';
  header = 'Authorization';
  cookie = 'trv.auth';
  signingKey?: string;
  headerPrefix = 'Bearer';
  maxAge: string | number = '1h';
  rollingRenew: boolean = false;

  @Ignore()
  maxAgeMs: number;

  get cookieMode(): boolean {
    return this.mode === 'cookie' || this.mode === 'all';
  }

  get headerMode(): boolean {
    return this.mode === 'header' || this.mode === 'all';
  }

  postConstruct(): void {

    this.maxAgeMs = typeof this.maxAge === 'string' ? TimeUtil.timeToMs(this.maxAge as '1y') : this.maxAge;

    if (!this.signingKey) {
      if (Env.production) {
        throw new AppError('The default signing key is only valid for development use, please specify a config value at rest.auth.jwt.signingKey');
      }
      this.signingKey = 'dummy';
    }
  }
}

/**
 * Principal encoder via JWT
 */
@Injectable()
export class JWTPrincipalEncoder implements PrincipalEncoder {

  @Inject()
  config: RestJWTConfig;

  @Inject()
  auth: AuthService;

  toJwtPayload(p: Principal): Payload {
    const exp = Math.trunc(p.expiresAt!.getTime() / 1000);
    const iat = Math.trunc(p.issuedAt!.getTime() / 1000);
    return {
      auth: {
        ...p,
      },
      exp,
      iat,
      iss: p.issuer,
      sub: p.id,
    };
  }

  /**
   * Get token for principal
   */
  async getToken(p: Principal): Promise<string> {
    return await JWTUtil.create(this.toJwtPayload(p), { key: this.config.signingKey });
  }

  /**
   * Rewrite token with new permissions
   */
  updateTokenPermissions(token: string, permissions: string[]): Promise<string> {
    return JWTUtil.rewrite<{ auth: Principal }>(
      token,
      p => ({
        ...p,
        auth: {
          ...p.auth,
          permissions
        }
      }),
      { key: this.config.signingKey }
    );
  }

  /**
   * Verify token to principal
   * @param token
   */
  async verifyToken(token: string, setActive = false): Promise<Principal> {
    const res = (await JWTUtil.verify<{ auth: Principal }>(token, { key: this.config.signingKey })).auth;
    if (setActive) {
      this.auth.setAuthenticationToken({ token, type: 'jwt' });
    }
    return {
      ...res,
      expiresAt: new Date(res.expiresAt!),
      issuedAt: new Date(res.issuedAt!),
    };
  }

  /**
   * Write context
   */
  async encode({ res }: FilterContext, p: Principal | undefined): Promise<void> {
    if (p) {
      const token = await this.getToken(p);
      if (this.config.cookieMode) {
        res.cookies.set(this.config.cookie, token, { expires: p.expiresAt });
      }
      if (this.config.headerMode) {
        res.setHeader(this.config.header, [this.config.headerPrefix, token].join(' ').trimStart());
      }
    } else if (this.config.cookieMode) {
      res.cookies.set(this.config.cookie, '', { expires: new Date(Date.now() - 1000 * 60 * 60) }); // Clear out cookie
    }
  }

  /**
   * Run before encoding, allowing for session extending if needed
   */
  preEncode(p: Principal): void {
    p.expiresAt ??= new Date(Date.now() + this.config.maxAgeMs);
    p.issuedAt ??= new Date();

    if (this.config.rollingRenew) {
      const end = p.expiresAt.getTime();
      const midPoint = end - this.config.maxAgeMs / 2;
      if (Date.now() > midPoint) { // If we are past the half way mark, renew the token
        p.issuedAt = new Date();
        p.expiresAt = new Date(Date.now() + this.config.maxAgeMs); // This will trigger a re-send
      }
    }
  }

  /**
   * Read JWT from request
   */
  async decode({ req }: FilterContext): Promise<Principal | undefined> {
    let token: string | undefined = undefined;
    if (this.config.cookieMode) {
      token ??= req.cookies.get(this.config.cookie);
    }
    if (this.config.headerMode) {
      const header = req.headerFirst(this.config.header);
      if (header?.startsWith(this.config.headerPrefix)) {
        token ??= header.replace(this.config.headerPrefix, '').trim();
      }
    }

    if (token) {
      return await this.verifyToken(token, true);
    }
  }
}

As you can see, the encode token just creates a JWT based on the principal provided, and decoding verifies the token, and returns the principal.

4.0.7

2 months ago

4.0.6

2 months ago

4.0.5

2 months ago

4.0.4

2 months ago

4.0.3

2 months ago

4.0.1

3 months ago

4.0.0

3 months ago

4.0.2

3 months ago

4.0.0-rc.10

3 months ago

4.0.0-rc.9

3 months ago

4.0.0-rc.8

3 months ago

3.4.6

3 months ago

4.0.0-rc.7

3 months ago

4.0.0-rc.6

3 months ago

4.0.0-rc.5

3 months ago

4.0.0-rc.3

3 months ago

4.0.0-rc.4

3 months ago

4.0.0-rc.1

3 months ago

4.0.0-rc.2

3 months ago

4.0.0-rc.0

4 months ago

3.4.4

6 months ago

3.4.5

6 months ago

3.3.6

7 months ago

3.4.0

6 months ago

3.2.2

10 months ago

3.2.1

10 months ago

3.2.6

10 months ago

3.4.3

6 months ago

3.2.5

10 months ago

3.4.2

6 months ago

3.2.4

10 months ago

3.4.1

6 months ago

3.2.3

10 months ago

3.4.0-rc.7

6 months ago

3.4.0-rc.8

6 months ago

3.4.0-rc.5

6 months ago

3.4.0-rc.6

6 months ago

3.4.0-rc.3

6 months ago

3.4.0-rc.4

6 months ago

3.4.0-rc.1

6 months ago

3.4.0-rc.2

6 months ago

3.4.0-rc.0

7 months ago

3.3.1

9 months ago

3.3.0

9 months ago

3.3.5

8 months ago

3.3.4

8 months ago

3.3.3

8 months ago

3.3.2

9 months ago

3.2.0

11 months ago

3.1.18

11 months ago

3.2.0-rc.0

11 months ago

3.1.12

12 months ago

3.1.11

12 months ago

3.1.14

12 months ago

3.1.13

12 months ago

3.1.16

11 months ago

3.1.15

12 months ago

3.1.17

11 months ago

3.1.10

12 months ago

3.1.9

1 year ago

3.1.8

1 year ago

3.1.7

1 year ago

3.1.6

1 year ago

3.1.5

1 year ago

3.1.4

1 year ago

3.0.3

1 year ago

3.1.3

1 year ago

3.1.2

1 year ago

3.1.1

1 year ago

3.1.0

1 year ago

3.1.0-rc.2

1 year ago

3.1.0-rc.3

1 year ago

3.1.0-rc.0

1 year ago

3.1.0-rc.1

1 year ago

3.1.0-rc.6

1 year ago

3.1.0-rc.7

1 year ago

3.1.0-rc.4

1 year ago

3.1.0-rc.5

1 year ago

3.1.0-rc.8

1 year ago

3.0.0-rc.26

1 year ago

3.0.0-rc.27

1 year ago

3.0.1-rc.1

1 year ago

3.0.2

1 year ago

3.0.1

1 year ago

3.0.0

1 year ago

3.0.2-rc.1

1 year ago

3.0.2-rc.0

1 year ago

3.0.0-rc.24

1 year ago

3.0.0-rc.23

1 year ago

3.0.0-rc.25

1 year ago

3.0.0-rc.20

1 year ago

3.0.0-rc.22

1 year ago

3.0.0-rc.21

1 year ago

3.0.0-rc.15

1 year ago

3.0.0-rc.17

1 year ago

3.0.0-rc.16

1 year ago

3.0.0-rc.19

1 year ago

3.0.0-rc.18

1 year ago

3.0.0-rc.13

1 year ago

3.0.0-rc.12

1 year ago

3.0.0-rc.14

1 year ago

3.0.0-rc.6

1 year ago

3.0.0-rc.11

1 year ago

3.0.0-rc.10

1 year ago

3.0.0-rc.9

1 year ago

3.0.0-rc.8

1 year ago

3.0.0-rc.7

1 year ago

3.0.0-rc.4

2 years ago

3.0.0-rc.3

2 years ago

3.0.0-rc.2

2 years ago

3.0.0-rc.1

2 years ago

3.0.0-rc.0

2 years ago