Serverless function with authorizer arn provided returns 401 - serverless-framework

I am using serverless.
When I setup one of my functions as the following, which includes authorizer, on the client, I receive 401.
However when I remove it, there are no problems.
provider:
name: aws
runtime: nodejs8.10
region: eu-west-1
environment:
USER_POOL_ARN: "arn:aws:cognito-idp:eu-west-1:974280.....:userpool/eu-west-1........"
functions:
create:
handler: handlers/create.main
events:
- http:
path: create
method: post
cors: true
authorizer:
type: COGNITO_USER_POOLS
name: serviceBAuthFunc
arn: ${self:provider.environment.USER_POOL_ARN}
On the client, I expect a logged in user of the same user pool could get expected response. However it returns 401.
Any help is appreciated. Thanks.

After desperate hours spent, I have come up with the solution.
For anyone who comes across the same issue, here is a solution that worked for me.
Add integration: lambda after cors: true (though the order doesn't matter).
Below is just demonstrating that.
functions:
create:
handler: handlers/create.main
events:
- http:
path: create
method: post
cors: true
integration: lambda // this solves the problem
authorizer:
type: COGNITO_USER_POOLS
name: serviceBAuthFunc
arn: ${self:provider.environment.USER_POOL_ARN}
Send Authorization header with the value of Auth.currentSession().idToken.jwtToken while making the request.
Below is an example for sending headers using API of #aws-amplify/api and Auth of #aws-amplify/auth.
const currentSession = await Auth.currentSession()
await API.post(
'your-endpoint-name',
"/your-endpoint-path/..",
{
headers: {
'Authorization': currentSession.idToken.jwtToken
}
}
)

Related

Google Strategy NestJS

I have this issue, I think I've explored all the internet for it, I'm trying to implement an authentification with passport-google-oauth20 in NestJS.
I got an event click from the front then it goes in the first part of the code
#UseGuards(GoogleAuthGuard)
public async loginGoogle(#Req() req: any) {
}
thens it goes ine the GoogleAuthGuard Part :
constructor() {
super({
clientID: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_SECRET,
callbackURL: 'http://localhost:5000/redirect',
scope: ['email', 'profile'],
});
// super({ usernameField: 'token' });
}
But in the network console part of the browser I got a CORS error 402 after a redirect 302.
Request URL: http://localhost:3000/redirect
Request Method: GET
Status Code: 302 Found
Remote Address: 127.0.0.1:3000
Referrer Policy: strict-origin-when-cross-origin
Request URL: https://accounts.google.com/o/oauth2/v2/auth?response_type=code&redirect_uri=http%3A%2F%2Flocalhost%3A5000%2Fredirect&scope=email%20profile&client_id=[MyID].apps.googleusercontent.com
Request Method: OPTIONS
Status Code: 405
Remote Address: 216.58.204.109:443
Referrer Policy: strict-origin-when-cross-origin
I already tried to enable all type of cors :
app.enableCors({
origin: ['http://localhost:5000', 'http://localhost:3000'],
allowedHeaders: ['content-type'],
credentials: true,
preflightContinue: false,
optionsSuccessStatus: 204,
methods: 'GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS',
// exposedHeaders: '*',
});
I already configured the redirection on googleapis to allow this one too. I'm out of solution if anyone could help on it, it would be really appreciated.
It feels like the Authentification is good but when it's time to redirect something goes wrong and I can't put headers in the redirect.

Strapi 4 - User pemissions plugin policy extension

I'm attempting to migrate from Strapi 3 -> 4
I've managed to restructure my folder structure to get the schema working for all my content types.
However, in v3 I had an extra policy on the user-permissions plugin the verified the users jwt token with auth0.
I took the v3 implementation from these docs.
I'm attempting to get it to apply the same logic in v4 and i'm a bit lost since the new docs don't seem fully up-to-date.
I'm adding a new policy in /src/extensions/users-permissions/strapi-server.js
Taken from the docs here
module.exports = (plugin) => {
plugin.policies["permissions"] = async (ctx) => {
let role;
console.log("IN HERE");
if (ctx.state.user) {
// request is already authenticated in a different way
return true;
}
// ... A bunch more logic
return false
}
return plugin
}
If I run yarn strapi policies:list then my 'permissions' policy is listed.
However, when trying to use that policy anywhere, I don't see my console log to see that it's being applied.
I've tried to specify that policy in the routes setup:
module.exports = {
routes: [
{
method: "GET",
path: "/addition-requests",
handler: "addition-request.find",
},
{
method: "GET",
path: "/addition-requests/:id",
handler: "addition-request.findOne",
},
{
method: "POST",
path: "/addition-requests",
config: {
policies: ["plugin::users-permissions.permissions"],
},
handler: "addition-request.create",
},
],
};
Is there anything obvious I'm missing?
And is there a way to apply a policy to every request that requires auth rather than specifying a policy on the route?
It appears from reading this comment it appears as though any request made to a Strapi endpoint that contains a Bearer token is treated like a request that requires auth.
That seems to be why the policy isn't being run as if I remove the Authorization header the policy does run. The question of how to execute a policy on an endpoint that requires auth still remains however.
It appears that the issue around being able to do custom validation on a users jwt is an issue that a few people are facing with v4 Strapi. See my topic on their forum.

ses.sendmail() gives CORS error. 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*'..credentials mode is 'include'

I have been stuck on this for 4 days now. I really need some insights.
I have a serverless express app deployed on AWS. I am serving my frontend from S3 and backend from lambda. API gateway has proxy as shown in the serverless.yml below.
I have also used cloudfront to map my domain(https://my.domain.com.au) with the S3 bucket origin URL.
The normal GET POST PUT DELETE requests are working fine. But when I try to access any of the other AWS service from Lambda I get following CORS error.
Access to XMLHttpRequest at 'https://0cn0ej4t5w.execute-api.ap-southeast-2.amazonaws.com/prod/api/auth/reset-password' from origin 'https://my.domain.com.au' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
My use case is to send a mail from my app for which I tried using.
ses.sendEmail(params).promise();
This gave me the same error. So i tried invoking it through lambda, same error. Now i am trying to push mail contents to S3 and send mail from lambda using trigger but this gave me the same error.
The issue doesn't seem to be on the code as its working perfect from local environment. However, i don't want to leave any stones unturned.
Since, my lambda is in a VPC i have used internet gateway and tried setting up the private link as well.
Serverless.yml
service: my-api
# plugins
plugins:
- serverless-webpack
- serverless-offline
- serverless-dotenv-plugin
# custom for secret inclusions
custom:
stage: ${opt:stage, self:provider.stage}
serverless-offline:
httpPort: 5000
webpack:
webpackConfig: ./webpack.config.js
includeModules: # enable auto-packing of external modules
forceInclude:
- mysql
- mysql2
- passport-jwt
- jsonwebtoken
- moment
- moment-timezone
- lodash
# provider
provider:
name: aws
runtime: nodejs12.x
# you can overwrite defaults here
stage: prod
region: ${env:AWS_REGION_APP}
timeout: 10
iamManagedPolicies:
- 'arn:aws:iam::777777777777777:policy/LambdaSESAccessPolicy'
vpc:
securityGroupIds:
- ${env:AWS_SUBNET_GROUP_ID}
subnetIds:
- ${env:AWS_SUBNET_ID1}
- ${env:AWS_SUBNET_ID2}
- ${env:AWS_SUBNET_ID3}
environment:
/// env variables (hidden)
iamRoleStatements:
- Effect: "Allow"
Action:
- s3:*
- ses:*
- lambda:*
Resource: '*'
# functions
functions:
app:
handler: server.handler
events:
- http:
path: /
method: ANY
- http:
path: /{proxy+}
method: ANY
cors:
origin: ${env:CORS_ORIGIN_URL}
allowCredentials: true
headers: 'Access-Control-Allow-Origin, Access-Control-Allow-Headers, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method, Access-Control-Request-Headers, Authorization'
method: ANY
# you can add CloudFormation resource templates here
resources:
# API Gateway Errors
- ${file(resources/api-gateway-errors.yml)}
# VPC Access for RDS
- ${file(resources/lambda-vpc-access.yml)}
I have configured response headers as well:
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", process.env.CORS_ORIGIN_URL);
res.header("Access-Control-Allow-Headers", "Access-Control-Allow-Origin, Access-Control-Allow-Headers, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method, Access-Control-Request-Headers, Authorization");
res.header("Access-Control-Allow-Credentials", "true");
res.header("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT,DELETE");
next();
});
I actually have the same exact error as you but I've figured it out.
I'll just paste my code since you didn't show what your lambda function looks like.
I also know its been two weeks... so hopefully this helps someone in the future.
CORS errors are server side, and I'm sure you are aware. The problem with AWS SES is you have to handle the lambda correctly or it'll give you a cors error even though you have the right headers.
First things first... I don't think you have OPTIONS method in your api gateway...although I'm not sure if ANY can work as a replacement.
Second here is my code:
I check which http method I'm getting then I respond based on that. I am receiving a post event and some details come in the body. You might want to change the finally block to something else. The OPTIONS is important for the CORS, it lets the browser know that its okay to send the POST request (or at least that's how I see it)
var ses = new AWS.SES();
var RECEIVER = 'receiver#gmail.com';
var SENDER = 'sender#gmail.com';
exports.handler = async(event) => {
let body;
let statusCode = '200';
const headers = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET,DELETE,POST,PATCH,OPTIONS',
'Access-Control-Allow-Credentials': true,
'Access-Control-Allow-Headers': 'access-control-allow-credentials,access-control-allow-headers,access-control-allow-methods,Access-Control-Allow-Origin,authorization,content-type',
'Content-Type': 'application/json'
};
console.log(event);
try {
switch (event.httpMethod) {
case 'POST':
event = JSON.parse(event.body);
var params = {
Destination: {
ToAddresses: [
RECEIVER
]
},
Message: {
Body: {
Html: {
Data: html(event.name, event.phone, event.email, event.message), // 'Name: ' + event.name + '\nPhone: ' + event.phone + '\nEmail: ' + event.email + '\n\nMessage:\n' + event.message,
Charset: 'UTF-8'
}
},
Subject: {
Data: 'You Have a Message From ' + event.name,
Charset: 'UTF-8'
}
},
Source: SENDER
};
await ses.sendEmail(params).promise();
break;
case 'OPTIONS':
statusCode = '200';
body = "OK";
break;
default:
throw new Error(`Unsupported method "${event.httpMethod}"`);
}
}
catch (err) {
statusCode = '400';
body = err.message;
}
finally {
body = "{\"result\": \"Success\"}"
}
console.log({
statusCode,
body,
headers,
})
return {
statusCode,
body,
headers,
};
}

How to get SNS topic ARN inside lambda handler and set permissions to wite to it?

I have two lambda functions defined in serverless.yml: graphql and convertTextToSpeech. The former (in one of the GraphQL endpoints) should write to SNS topic to execute the latter one. Here is my serverless.yml file:
service: hello-world
provider:
name: aws
runtime: nodejs6.10
plugins:
- serverless-offline
functions:
graphql:
handler: dist/app.handler
events:
- http:
path: graphql
method: post
cors: true
convertTextToSpeach:
handler: dist/tasks/convertTextToSpeach.handler
events:
- sns:
topicName: convertTextToSpeach
displayName: Convert text to speach
And GraphQL endpoint writing to SNS:
// ...
const sns = new AWS.SNS()
const params = {
Message: 'Test',
Subject: 'Test SNS from lambda',
TopicArn: 'arn:aws:sns:us-east-1:101972216059:convertTextToSpeach'
}
await sns.publish(params).promise()
// ...
There are two issues here:
Topic ARN (which is required to write to a topic) is hardcoded it. How I can get this in my code "dynamically"? Is it provided somehow by serverless framework?
Even when topic arn is hardcoded lambda functions does not have permissions to wrote to that topic. How I can define such permissions in serverless.yml file?
1) You can resolve the topic dynamically.
This can be done through CloudFormation Intrinsic Functions, which are available within the serverless template (see the added environment section).
functions:
graphql:
handler: handler.hello
environment:
topicARN:
Ref: SNSTopicConvertTextToSpeach
events:
- http:
path: graphql
method: post
cors: true
convertTextToSpeach:
handler: handler.hello
events:
- sns:
topicName: convertTextToSpeach
displayName: Convert text to speach
In this case, the actual topic reference name (generated by the serverless framework) is SNSTopicConvertTextToSpeach. The generation of those names is explained in the serverless docs.
2) Now that the ARN of the topic is mapped into an environment variable, you can access it within the GraphQL lambda through the process variable (process.env.topicARN).
// ...
const sns = new AWS.SNS()
const params = {
Message: 'Test',
Subject: 'Test SNS from lambda',
TopicArn: process.env.topicARN
}
await sns.publish(params).promise()
// ...

XirSys - SimpleWebRTC - I get 'Could not validate application' when doing the request to iceServers

My request to xirsys endpoint looks like this:
$.ajax({
type: "POST",
dataType: "json",
url: "https://api.xirsys.com/getIceServers",
data: {
ident: "username",
secret: "secret_api_key",
domain: "dummy_subdomain.domain.com",
application: "default",
room: "default",
secure: 1
},
});
However, even if the username, secret and the rest of information seem to be correct into the xirsys dashboard, I get this error: 'Could not validate application'.
Do you have any idea ?
Thank you.
Well, I tried this and I now get a 200 status, but unfortunately I get this response:
{"p":"/getIceServers","s":200,"d":{"iceServers":[{"url":"stun:127.0.0.1"},{"username":"free","url":"turn:127.0.0.1?transport=udp","credential":"free"},{"username":"free","url":"turn:127.0.0.1?transport=tcp","credential":"free"}]},"e":null}
Which I think is a default response.
What could I do wrong ?
Currently, XirSys doesn't support the posting of JSON to its endpoints. You'll need to change it to posting standard POST cars for it to work. JSON support will be added very soon.
Regards,
Lee