sst / ion

SST v3
https://sst.dev
MIT License
1.99k stars 231 forks source link

Example for Basic Auth #622

Closed gstrobl closed 3 weeks ago

gstrobl commented 3 months ago

I'm pretty new to ion, is it possible to provide an basic auth example like this here (https://docs.sst.dev/constructs/NextjsSite#configuring-basic-auth). I couldn't find something in the docs.

Thank you!

zhifez commented 3 months ago

Try this: https://github.com/sst/ion/tree/dev/examples/aws-auth

gstrobl commented 3 months ago

Does it work in this way? I tried so many things, but I didn't manage it to add an authentication.

/// <reference path="./.sst/platform/config.d.ts" />

export default $config({
  app(input) {
    return {
      name: 'test-app',
      removal: input?.stage === 'production' ? 'retain' : 'remove',
      home: 'aws'
    };
  },
  async run() {
    // Create the Lambda function for basic authentication
    const basicAuth = new sst.aws.Function("BasicAuthFunction", {
      handler: "basicAuth.handler",
      environment: {
        BASIC_AUTH_USERNAME:  'your-username',
        BASIC_AUTH_PASSWORD:  'your-password',
      }
    });

    // Create the Next.js application and link the API
    new sst.aws.Nextjs('MyWeb', {
      link: [basicAuth]
    });

    return {
      url: nextApp.url,
    };
  }
});

Here is the auth

// basicAuth.js
[exports.handler = async (event) => {
  const authHeader = event.headers.Authorization || event.headers.authorization;

  if (!authHeader) {
    return {
      statusCode: 401,
      body: JSON.stringify({ message: "Missing Authorization Header" }),
    };
  }

  const encodedCreds = authHeader.split(' ')[1];
  const buffer = Buffer.from(encodedCreds, 'base64');
  const [username, password] = buffer.toString('utf-8').split(':');

  const validUsername = process.env.BASIC_AUTH_USERNAME;
  const validPassword = process.env.BASIC_AUTH_PASSWORD;

  if (username === validUsername && password === validPassword) {
    return {
      isAuthorized: true,
    };
  }

  return {
    statusCode: 401,
    body: JSON.stringify({ message: "Invalid credentials" }),
  };
};]
jayair commented 3 months ago

I'll need to figure out how to do the SST2 example in Ion.

The snippet you are trying is a bit different. I haven't tried that before, I'm not sure if it'll work.

fwang commented 3 weeks ago

In v3.1.1, Nextjs and other SSR site components can be injected with custom CF function code.

Here's an example of using this functionality to achieve basic auth - https://github.com/sst/ion/blob/dev/examples/aws-nextjs-basic-auth/sst.config.ts