Phastboy / buddy

Buddy is a comprehensive web application designed to enhance learning experiences.
0 stars 0 forks source link

Implement Token Signing on User Registration with Cookie Setting in `apps/buddy` #24

Open Phastboy opened 2 weeks ago

Phastboy commented 2 weeks ago

Generate a JWT in apps/auth, and when apps/buddy receives the registration response, set this JWT as an HTTP-only cookie in the response.


Tasks:

Step 1: Configure JWT Signing in apps/auth

  1. Set Up JWT Module in auth.module.ts:

    • In auth.module.ts, import and configure the NestJS JwtModule to allow for token signing:
      
      import { JwtModule } from '@nestjs/jwt';

    @Module({ imports: [ JwtModule.register({ secret: process.env.JWT_SECRET, // secret key from environment signOptions: { expiresIn: '1h' }, // token expiration (1 hour) }), ], })

    
    - This configuration ensures that JWTs are signed with the secret and will expire in one hour.
  2. Update Registration Logic to Sign JWT:

    • In the auth.controller.ts file, modify the registration logic to sign a JWT when a user is successfully registered.
    • After creating the user, generate the JWT with a payload including essential details like userId and username.
      const payload = { userId: user._id, username: user.username };
      const jwt = this.jwtService.sign(payload);
  3. Return JWT in Registration Response:

    • Ensure that the registration endpoint returns the signed JWT along with any other necessary user data. For example:
      return response.json({
      message: 'Registration successful',
      user: { id: user._id, username: user.username },
      token: jwt,
      });

Step 2: Modify apps/buddy to Set JWT as HTTP-only Cookie

  1. Set Up Environment Variables for Cookie Security:

    • Define the following environment variables in .env or a configuration file:
      • COOKIE_SECURE: Set to true in production to enable secure cookies.
      • COOKIE_MAX_AGE: Set a value to define the expiration time for cookies (e.g., 3600000 for 1 hour).
    • Example:
      COOKIE_SECURE=true
      COOKIE_MAX_AGE=3600000
  2. Receive JWT from apps/auth in apps/buddy:

    • In apps/buddy, handle the response from apps/auth after the user registers.
    • Extract the JWT from the response and prepare to set it in a cookie.
  3. Configure Cookie Setting in auth.controller.ts of apps/buddy:

    • Update the register method in auth.controller.ts of apps/buddy to set the JWT as an HTTP-only cookie.
    • Use the response.cookie() method to set the cookie, including appropriate security flags like httpOnly, secure, and sameSite:
      
      const cookieOptions = {
      httpOnly: true,
      secure: process.env.COOKIE_SECURE === 'true', // true if in production
      sameSite: process.env.COOKIE_SECURE === 'true' ? 'None' : 'Lax', // restrict cross-site requests
      path: '/', // cookie is valid across the entire domain
      maxAge: parseInt(process.env.COOKIE_MAX_AGE), // cookie expiration
      };

    response.cookie('jwt', jwt, cookieOptions); // set JWT as cookie

  4. Handle Edge Cases:

    • If JWT signing fails in apps/auth, ensure that apps/auth returns an error response (e.g., 400 Bad Request or 500 Internal Server Error).
    • apps/buddy should handle this error and respond appropriately, such as returning a clear error message to the user.

Step 3: Test Cookie Functionality and Security

  1. Verify Cookie Is Set Correctly on Registration:

    • Register a new user and inspect the browser’s cookies to ensure that the JWT is correctly set with the expected properties (i.e., httpOnly, secure, sameSite).
  2. Confirm Secure Cookie Behavior:

    • In production (over HTTPS), confirm that the secure flag is correctly set on the cookie.
    • Test that the cookie is not accessible via JavaScript by trying to access document.cookie in the browser’s console. It should not return the JWT if httpOnly is working properly.
  3. Confirm Cookie Expiration and SameSite Behavior:

    • Verify that the cookie expires after the time defined in COOKIE_MAX_AGE.
    • Confirm that the SameSite policy works as expected (e.g., restricts cross-site requests when set to Strict or Lax).

Acceptance Criteria: