Symfony 3 probleme with authentication - authentication

Hi guys i have a probleme with the guard authentication I use symfony 3.1 in my project the guard authentication work fine in my local machine but when i deploy to the server if the authentication succeed i am redirecting to the home page but i loose the authentication and become anonymous again.
Event when i want to register a new user in the deployement it doesnt work the error is bad csrf.
seems like in the deployement the navigator dont send cookies or dont accept them.
I am really confus cause all this work fine in my local server
Really need help.
Thx
security.yml :
security:
encoders:
UserBundle\Entity\User: bcrypt
providers:
database_users:
entity: {class: UserBundle:User, property: mail}
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
main:
anonymous: ~
guard:
authenticators:
- form_login_authenticator
confing.yml :
imports:
- { resource: parameters.yml }
- { resource: security.yml }
- { resource: services.yml }
- { resource: "#VendeurBundle/Resources/config/services.yml" }
- { resource: "#UserBundle/Resources/config/services.yml" }
# Put parameters here that don't need to change on each machine where the app is deployed
# http://symfony.com/doc/current/best_practices/configuration.html#application-related-configuration
parameters:
locale: fr
framework:
#esi: ~
translator: { fallbacks: ["%locale%"] }
secret: "%secret%"
router:
resource: "%kernel.root_dir%/config/routing.yml"
strict_requirements: ~
form: ~
csrf_protection: ~
validation: { enable_annotations: true }
#serializer: { enable_annotations: true }
templating:
engines: ['twig']
default_locale: "%locale%"
trusted_hosts: ~
trusted_proxies: ~
session:
# http://symfony.com/doc/current/reference/configuration/framework.html#handler-id
handler_id: session.handler.native_file
save_path: "%kernel.root_dir%/../var/sessions/%kernel.environment%"
cookie_lifetime: 1000
fragments: ~
http_method_override: true
assets: ~
# Twig Configuration
twig:
debug: "%kernel.debug%"
strict_variables: "%kernel.debug%"
form_themes:
- 'bootstrap_3_horizontal_layout.html.twig'
# Doctrine Configuration
doctrine:
dbal:
driver: pdo_mysql
host: "%database_host%"
port: "%database_port%"
dbname: "%database_name%"
user: "%database_user%"
password: "%database_password%"
charset: UTF8
# if using pdo_sqlite as your database driver:
# 1. add the path in parameters.yml
# e.g. database_path: "%kernel.root_dir%/data/data.db3"
# 2. Uncomment database_path in parameters.yml.dist
# 3. Uncomment next line:
# path: "%database_path%"
orm:
auto_generate_proxy_classes: "%kernel.debug%"
naming_strategy: doctrine.orm.naming_strategy.underscore
auto_mapping: true
# Swiftmailer Configuration
swiftmailer:
transport: "%mailer_transport%"
host: "%mailer_host%"
username: "%mailer_user%"
password: "%mailer_password%"
spool: { type: memory }
stof_doctrine_extensions:
orm:
default:
timestampable: true
white_october_pagerfanta:
exceptions_strategy:
out_of_range_page: ~
not_valid_current_page: ~
Controller :
/**
* #Route("/connexion", name="security_login")
*/
public function loginAction()
{
if ($this->isAuthenticated()) {
return $this->redirectToRoute('homepage');
}
$helper = $this->get('security.authentication_utils');
return $this->render(':connexion:login.html.twig', array(
// last username entered by the user (if any)
'last_username' => $helper->getLastUsername(),
// last authentication error (if any)
'error' => $helper->getLastAuthenticationError(),
));
}
/**
* #Route("/logout", name="logout")
* #Security("is_authenticated()")
*/
public function logoutAction()
{
$this->container->get('security.token_storage')->setToken(null);
return $this->redirectToRoute("homepage");
}
/**
* #Route("/login_check", name="security_login_check")
*/
public function loginCheckAction()
{
// will never be executed
}
Update : I found the probleme the server destroy the session for every request but i dont know how to solve it.

Related

User not logged in, even after `LoginSuccessEvent` fired

It worked a while back, but I'm having issues backtracking where I went wrong.
I'll give you all the details first:
#security.yaml
security:
password_hashers:
Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface: 'auto'
providers:
users:
entity:
class: 'App\Entity\User'
property: 'username'
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
main:
lazy: true
provider: users
form_login:
login_path: app_login
check_path: app_login
enable_csrf: true
logout:
path: app_logout
access_control:
- { path: ^/admin, roles: ROLE_ADMIN }
- { path: ^/profile, roles: ROLE_USER }
role_hierarchy:
ROLE_ADMIN: ROLE_USER
ROLE_SUPER_ADMIN: [ ROLE_ADMIN, ROLE_ALLOWED_TO_SWITCH ]
Pretty basic, here's where it gets messy for me:
controllers:
resource: ../src/Controller/
type: annotation
prefix: /{_locale}
requirements:
_locale: '%app.supported_locales%'
defaults:
_locales: '%app.default_locale%'
middleware: 'locale_middleware'
app_default_locale_redirect:
path: /
methods: GET
controller: App\Controller\DefaultController::defaultLocaleRedirect
defaults:
_locale: '%app.default_locale%'
requirements:
_locale: '^(?!%app.supported_locales%).*'
app_login:
path: /{_locale}/login
app_logout:
path: /{_locale}/logout
methods: GET
I want to redirect all URLs that don't have a supported locale in the URL to the default locale. That's what the middleware is for, and thats why app_login and app_logout both have /{_locale} in their paths. It works as far as I can see.
My default controller handles that using method:
/**
* #Route("/default-locale-redirect")
*/
public function defaultLocaleRedirect(Request $request): RedirectResponse
{
$defaultLocale = $request->getLocale();
return new RedirectResponse($request->getBaseUrl() . '/' . $defaultLocale . '/');
}
I'm also subscribed to the LoginSuccessEvent event, and relevant events:
public static function getSubscribedEvents(): array {
return [
LogoutEvent::class => 'onLogout',
LoginSuccessEvent::class => "onLogin",
LoginFailureEvent::class => "onLoginFailure"
];
}
public function onLogout(LogoutEvent $event): void {
$this->flash->add("success", $this->trans->trans("account.auth.logged_off"));
}
public function onLogin(LoginSuccessEvent $event): void {
$token = $this->tokenStorage->getToken();
$user = $token->getUser();
$roles = $token->getRoleNames();
$this->flash->add("success", $this->trans->trans("account.auth.logged_on"));
}
public function onLoginFailure(LoginFailureEvent $event): void {
$this->flash->add("error", $this->trans->trans("account.auth.failed"));
}
When I place a breakpoint in onLogin, the breakpoint gets hit, and $token, $user and $roles are populated perfectly.
After the page reloads, though, I notice the user is not authenticated. Somehow I believe the token is not persisted. The dev toolbar confirms this, and is_granted("IS_AUTHENTICATED_FULLY") also returns false.
I tried clearing all caches. What am I doing wrong?

Serverless Express Lambda async invoke not working

I have a basic Serverless Express app in a lambda, with a route set to async true. I want to trigger this route asynchronously from a different application, and expect it to run in the background without having to wait for the response.
My full serverless.yml
service: service-name
useDotenv: true
custom:
serverless-offline:
useChildProcesses: true
webpack:
webpackConfig: ./webpack.config.js
packager: "yarn"
includeModules:
forceExclude:
- aws-sdk
prune:
automatic: true
includeLayers: true
number: 3
envStage:
staging: staging
domainPrefix:
staging: service.staging
customDomain:
domainName: ${self:custom.domainPrefix.${opt:stage}}.mydomain.com
basePath: ""
stage: ${self:custom.envStage.${opt:stage}}
createRoute53Record: true
plugins:
- serverless-domain-manager
- serverless-webpack
- serverless-prune-plugin
- serverless-offline
provider:
lambdaHashingVersion: "20201221"
name: aws
runtime: nodejs14.x
region: us-east-1
apiGateway:
minimumCompressionSize: 1024
iamRoleStatements:
- Effect: Allow
Action: ssm:Get*
Resource: "arn:aws:ssm:*:*:parameter/myparams/*"
- Effect: Allow
Action: kms:Decrypt
Resource: "*"
functions:
express:
handler: src/index.middyHandler
events:
- http:
path: /
method: options
- http:
path: /{any+} # Catch all routes
method: options
- http:
path: foo/{any+}
method: get
- http:
path: foo/{any+}
method: post
async: true
Note: The role that deploys this app has permissions to read write to Cloudwatch, and I can see logs from the synchronous invocations, but not from async invocations.
My index.middyHandler
import serverless from "serverless-http";
import express from "express";
import helmet from "helmet";
import bodyParser from "body-parser";
import cookieParser from "cookie-parser";
import middy from "#middy/core";
import ssm from "#middy/ssm";
import doNotWaitForEmptyEventLoop from "#middy/do-not-wait-for-empty-event-loop";
import cors from "cors";
import fooRoutes from "./routes/foo";
const app = express();
app.use(
cors({
methods: "GET,HEAD,OPTIONS,POST",
preflightContinue: false,
credentials: true,
origin: true,
optionsSuccessStatus: 204,
})
);
app.use(helmet({ contentSecurityPolicy: false, crossOriginEmbedderPolicy: false }));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.get("/ping", (req, res) => {
res.send("Pong!");
});
// Register routes
app.use("/foo", fooRoutes);
const handler = serverless(app);
export const middyHandler = middy(handler)
.use(
doNotWaitForEmptyEventLoop({
runOnError: true,
runOnAfter: true,
runOnBefore: true,
})
)
.use(
ssm({
setToEnv: true,
fetchData: {
MY_KEYS: "ssm/path"
},
})
)
When I call this method, it correctly returns a 200 response immediately. But the actual code is never run, I have a DB insert in there, and it doesn't happen. In the API Gateway I can see the X-Amz-Invocation-Type header is correctly being passed as Event type.
It is not a proxy integration, as required for async invocation
What am I missing here? The route controller is a test and the code is very simple
testAsync: async (req, res) => {
console.log("In Test Async"); // Does not display in Cloudwatch
try {
const { value } = req.body;
const resp = await updateTest(value); // This just inserts an entry in the DB with value
return res.send(resp);
} catch (err) {
return res.status(500).send(err);
}
},
Is there any other setting I'm missing here? I'm not an AWS expert, so any help would be highly appreciated. Thanks!

How can I set up 2 AWS lambda functions, with one firing an event on eventBridge and the other reacting to it?

I'm using the serverless framework to try and test EventBridge.
The documentation is a little sparce, but for my test I would like to have two lambda functions created: first one publishes an event, the second consumes it.
Here is my YAML:
service: events
frameworkVersion: '2'
provider:
name: aws
runtime: nodejs12.x
lambdaHashingVersion: '20201221'
functions:
vehicle:
handler: handler.vehicle
events:
- httpApi:
path: /vehicle
method: '*'
bundle:
handler: handler.bundle
events:
- httpApi:
path: /bundle
method: '*'
- eventBridge:
eventBus: vehicle-bus
pattern:
source:
- aos.vehicle.upload
detail-type:
- VehicleUpload
and my handler.js
"use strict";
const AWS = require('aws-sdk');
module.exports.vehicle = async (event) => {
const eventBridge = new AWS.EventBridge({ region: 'us-east-1' });
const vrm = 'WR17MMN'
return eventBridge.putEvents({
Entries: [
{
EventBusName: 'veihcle-bus',
Source: 'aos.vehicle.upload',
DetailType: 'VehicleUpload',
Detail: `{ "Registration": "${vrm}" }`,
},
]
}).promise()
};
module.exports.bundle = async (event) => {
return {
statusCode: 200,
body: JSON.stringify(
{
message: "BUNDLE",
input: event,
aos: "First test OK",
},
null,
2
),
};
};
(I realise I can't just return that from the Lambda but it also needs to be an endpoint. If I make the function body of bundle empty I still get a server error.
What am I missing?
So you need this minimal setup:
org: myOrg
app: my-events
service: event-bridge-serverless
provider:
name: aws
runtime: nodejs10.x
region: eu-west-1
lambdaHashingVersion: 20201221
environment:
DYNAMODB_TABLE: ${self:service}-dev
eventBridge:
useCloudFormation: true
iamRoleStatements:
- Effect: "Allow"
Action:
- "events:PutEvents"
Resource: "*"
functions:
asset:
handler: handler.asset
events:
- eventBridge:
eventBus: my-events
pattern:
source:
- my.event

Serverless framework lambda function access denied to S3

Anyone have any ideas why I'm getting "Access Denied" when trying to put object into S3 inside a lambda function? I have the serverless AWS user with AdministorAccess and allow access to s3 resource inside serverless.yml:
iamRoleStatements:
- Effect: Allow
Action:
- s3:PutObject
Resource: "arn:aws:s3:::*"
Edit - here are the files
serverless.yml
service: testtest
app: testtest
org: workx
provider:
name: aws
runtime: nodejs12.x
iamRoleStatements:
- Effect: Allow
Action:
- s3:PutObject
Resource: "arn:aws:s3:::*/*"
functions:
hello:
handler: handler.hello
events:
- http:
path: users/create
method: get
handler.js
'use strict';
const AWS = require('aws-sdk');
// get reference to S3 client
const S3 = new AWS.S3();
// Uload the content to s3 and allow download
async function uploadToS3(content) {
console.log('going to upload to s3!');
const Bucket = 'mtest-exports';
const key = 'testtest.csv';
try {
const destparams = {
Bucket,
Key: key,
Body: content,
ContentType: "text/csv",
};
console.log('going to put object', destparams);
const putResult = await S3.putObject(destparams).promise();
return putResult;
} catch (error) {
console.log(error);
throw error;
}
}
module.exports.hello = async event => {
const result = await uploadToS3('hello world');
return {
statusCode: 200,
body: JSON.stringify(result),
};
};
I was using TypeScript plugin - #serverless/typescript. I used it to create Lambda function that will resize images that are uploaded to S3 + do some kind of content moderation.
Here is the content of serverless.ts file:
import type { AWS } from '#serverless/typescript';
import resizeImageLambda from '#functions/resizeImageLambda';
const serverlessConfiguration: AWS = {
service: 'myservice-image-resize',
frameworkVersion: '3',
plugins: ['serverless-esbuild'],
provider: {
name: 'aws',
stage: 'dev',
region: 'us-east-1',
profile: 'myProjectProfile', // reference to your local AWS profile created by serverless config command
// architecture: 'arm64', // to support Lambda w/ graviton
iam: {
role: {
statements: [
{
Effect: 'Allow',
Action: [
's3:GetObject',
's3:PutObject',
's3:PutObjectAcl',
's3:ListBucket',
'rekognition:DetectModerationLabels'
],
Resource: [
'arn:aws:s3:::myBucket/*',
'arn:aws:s3:::myBucket',
'arn:aws:s3:::/*',
'*'
]
},
{
Effect: 'Allow',
Action: [
's3:ListBucket',
'rekognition:DetectModerationLabels'
],
Resource: ['arn:aws:s3:::myBucket']
}
]
}
},
// architecture: 'arm64',
runtime: 'nodejs16.x',
environment: {
AWS_NODEJS_CONNECTION_REUSE_ENABLED: '1',
NODE_OPTIONS: '--enable-source-maps --stack-trace-limit=1000',
SOURCE_BUCKET_NAME:
'${self:custom.myEnvironment.SOURCE_BUCKET_NAME.${self:custom.myStage}}',
DESTINATION_BUCKET_NAME:
'${self:custom.myEnvironment.DESTINATION_BUCKET_NAME.${self:custom.myStage}}'
}
},
// import the function via paths
functions: { resizeImageLambda },
package: { individually: true },
custom: {
esbuild: {
bundle: true,
minify: false,
sourcemap: true,
exclude: ['aws-sdk'],
target: 'node16',
define: { 'require.resolve': undefined },
platform: 'node',
concurrency: 10,
external: ['sharp'],
packagerOptions: {
scripts:
'rm -rf node_modules/sharp && SHARP_IGNORE_GLOBAL_LIBVIPS=1 npm install --arch=x64 --platform=linux --libc=glibc sharp'
}
},
myEnvironment: {
SOURCE_BUCKET_NAME: {
dev: 'myBucket',
prod: 'myBucket-prod'
},
DESTINATION_BUCKET_NAME: {
dev: 'myBucket',
prod: 'myBucketProd'
}
},
myStage: '${opt:stage, self:provider.stage}'
}
};
module.exports = serverlessConfiguration;
resizeImageLambda.ts
/* eslint-disable no-template-curly-in-string */
// import { Config } from './config';
export const handlerPath = (context: string) =>
`${context.split(process.cwd())[1].substring(1).replace(/\\/g, '/')}`;
export default {
handler: `${handlerPath(__dirname)}/handler.main`,
events: [
{
s3: {
bucket: '${self:custom.myEnvironment.SOURCE_BUCKET_NAME.${self:custom.myStage}}',
event: 's3:ObjectCreated:*',
existing: true,
forceDeploy: true // for existing buckets
}
}
],
timeout: 15 * 60, // 15 min
memorySize: 2048
};
I remember there were few issues when I wanted to connect it to existing buckets (created outside serverless framework) such as IAM policy was not re-created / updated properly (see forceDeploy end existing parameters in function.events[0].s3 properties in resizeLambda.ts file)
Turns out I was an idiot and have the custom config in the wrong place and ruin the serverless.yml file!

How to allow filesystem access

I want to provide filesystem access for use with fs. How can I grant the vm2 process access to a specific directory?
I've tried setting external to true and a root of /. The process is able to access the directory when run outside vm2.
Did you set builtin: ['fs']?
Try the below code sample
const {NodeVM} = require('vm2');
const vm = new NodeVM({
console: 'inherit',
sandbox: {},
require: {
external: true,
builtin: ['fs', 'path'],
root: "./",
mock: {
fs: {
readFileSync() { return 'Nice try!'; }
}
}
}
});