Closed gstrobl closed 3 weeks 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" }),
};
};]
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.
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
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!