session always null google chrome netcore mvc iframe - google-chrome

I have a net core MVC project that gives an iframe to external sites. But the session is lost when using iframe on other sites.
services.AddSession(opt=> {
opt.Cookie.SameSite = SameSiteMode.None;
opt.Cookie.HttpOnly = true;
opt.Cookie.IsEssential = true;
});
services.Configure<CookiePolicyOptions>(options =>
{
options.MinimumSameSitePolicy = SameSiteMode.None;
options.CheckConsentNeeded = context => true;
});
services.ConfigureApplicationCookie(opt =>
{
opt.Cookie.IsEssential = true;
opt.Cookie.HttpOnly = true;
opt.Cookie.Name = "MyCookie";
opt.Cookie.SameSite = SameSiteMode.None;
opt.LoginPath = new PathString("/Home/Index");
});
services.AddAntiforgery(o => {
o.SuppressXFrameOptionsHeader = true;
o.Cookie.SameSite = SameSiteMode.None;
}) ;
session doesn't work when i use the codes above on google chrome . I also tried other samesite mods(Lax,Strict,Unspecified).
Can you see an error in the code? Or do you know a way to do this?

use options.CheckConsentNeeded = context => false; instead of options.CheckConsentNeeded = context => true;
try it, I think it will work.
services.Configure<CookiePolicyOptions>(options =>
{
options.CheckConsentNeeded = context => false;
options.MinimumSameSitePolicy = SameSiteMode.None;
});

Related

Why am i getting undefined when trying to get a single element?

Why am i getting undefined of my id? I am creating an app with NextJS and i am trying to do a route to get an especific element by its id. This is my route:
const { events } = require('../../../db.json')
const handler = async (req , res) => {
const method = req.method;
const evt = events.filter((ev) => ev.id === req.query.params.id);
if(method === 'GET'){
return res.status(201).json(evt);
} else {
res.setHeader('Allow', ['GET']);
res.status(405).json({message:`Method ${method} is not allowed`})
}
}
For some reason i get this error when i go to http://localhost:3000/api/events/1
I am using json web server so i have my api also running in port 3001 so at http://localhost:3001/api/events/1 it works and show the corresponding id but why is not working in port 3000 also?
Try updating your code to the following:
const { events } = require('../../../db.json');
const handler = async (req, res) => {
const method = req.method;
const id = req.query.id;
const evt = events.filter((ev) => ev.id === id);
if (method === 'GET') {
return res.status(201).json(evt);
} else {
res.setHeader('Allow', ['GET']);
res.status(405).json({ message: `Method ${method} is not allowed` });
}
};

Error in React mapping when JSON.parse on local storage fails

I have a react app that uses local storage to maintain its state with cookies, but when a cookie exists that has a bad value, the code errors causing the whole app to break. I'm not sure exactly what cookie is the problem, but certain cookies seem to cause `JSON.parse(localStorage[key]) to fail.
const getLocalStorage = () => {
const storage = R.compose(
R.fromPairs,
R.map(([key]) => [key, JSON.parse(localStorage[key])]),
R.toPairs, // [[key, value], [key, value]]
)(localStorage);
return storage;
};
I'd like to just add some error handling so that cookies that cannot be parsed are ignored, but I'm not sure how to do that in this syntax. How can I fix the code so that if JSON.parse fails, it doesn't break?
So you have two options here, the first one is the filter out any cookies that would return an error on parsing before you do your map like so:
const getLocalStorage = () => {
const storage = R.compose(
R.fromPairs,
R.filter([key] => {
try{
JSON.parse(localStorage[key]);
return true;
}
catch(error){
console.log(error);
return false;
}
}).map(([key]) => [key, JSON.parse(localStorage[key])]),
R.toPairs, // [[key, value], [key, value]]
)(localStorage);
return storage;
};
Or you could try using an Array.reduce() like this:
const getLocalStorage = () => {
const storage = R.compose(
R.fromPairs,
R.reduce((acc, curr) =>
{
try{
acc.push[[key, JSON.parse(localStorage[key])]];
}
catch(error){
console.log(error);
}
return acc;
}),
R.toPairs, // [[key, value], [key, value]]
)(localStorage);
return storage;
};

Why can't I patch, update, or delete an AppPackage that I created?

I am trying to change the required engine version of an AppPackage that I have posted using v2 of the Design Automation API.
I've tried using Postman and the Forge Node Client. I'm using the Forge documentation as a reference.
https://forge.autodesk.com/en/docs/design-automation/v2/reference/http/AppPackages(':id')-PATCH/
My credentials are correct and I have a valid token, but for some reason I keep getting a 404 Not Found status and an error that says "AppPackage with the name MyPlugin doesn't belong to you. You cannot operate on AppPackage you do not own." Also, I get the same message when I try to delete or update the AppPackage.
That's really weird because I definitely own this AppPackage. I uploaded it with these same credentials and I can view it by doing a GET request to view all of my AppPackages. Furthermore, the name of the AppPackage is correct and I specified the right scope (code:all) when I authenticated.
Why does Design Automation think this AppPackage doesn't belong to me and why can't I patch, update, or delete it?
UPDATE 3/28/2019: Setting the resource value still results in the same error
UPDATE 4/2/2019: Getting a fresh upload URL doesn't work either. I get an internal server error saying "Object reference not set to an instance of an object."
const ForgeSDK = require('forge-apis');
const oAuth2TwoLegged = new ForgeSDK.AuthClientTwoLegged(FORGE_CLIENT_ID, FORGE_CLIENT_SECRET, SCOPES);
const appPackageApi = new ForgeSDK.AppPackagesApi();
const getToken = () => {
return oAuth2TwoLegged.authenticate();
};
const getUploadURL = () => {
return appPackageApi.getUploadUrl(oAuth2TwoLegged, oAuth2TwoLegged.getCredentials());
};
const patchPackage = (id, url) => {
const appPack = {
Resource: url,
RequiredEngineVersion: APP_PACKAGE_REQUIRED_ENGINE
};
return appPackageApi.patchAppPackage(id, appPack, oAuth2TwoLegged, oAuth2TwoLegged.getCredentials());
};
(async () => {
try {
const token = await getToken();
const url = await getUploadURL();
const patchPackRes = await patchPackage(APP_PACKAGE_ID, url);
if (patchPackRes.statusCode == 201)
console.log('Patch package succeeded!');
else
console.log('Patch package failed!' + patchPackRes.statusCode);
} catch (ex) {
console.log('Exception :(');
console.log(ex);
}
})();
When calling PATCH the "Resource" property must be set. It can be set to the same URL as the one you receive from GET but it must be present and valid.
This should work:
const ForgeSDK = require('forge-apis');
const oAuth2TwoLegged = new ForgeSDK.AuthClientTwoLegged(FORGE_CLIENT_ID, FORGE_CLIENT_SECRET, SCOPES);
const appPackageApi = new ForgeSDK.AppPackagesApi();
const getToken = () => {
return oAuth2TwoLegged.authenticate();
};
const getUploadURL = async (id) => {
const app = await appPackageApi.getAppPackage(id, oAuth2TwoLegged, oAuth2TwoLegged.getCredentials());
return app.body.Resource;
};
const patchPackage = (id, url) => {
const appPack = {
Resource: url,
RequiredEngineVersion: APP_PACKAGE_REQUIRED_ENGINE
};
return appPackageApi.patchAppPackage(id, appPack, oAuth2TwoLegged, oAuth2TwoLegged.getCredentials());
};
(async () => {
try {
const token = await getToken();
const url = await getUploadURL(APP_PACKAGE_ID);
const patchPackRes = await patchPackage(APP_PACKAGE_ID, url);
if (patchPackRes.statusCode == 201)
console.log('Patch package succeeded!');
else
console.log('Patch package failed!' + patchPackRes.statusCode);
} catch (ex) {
console.log('Exception :(');
console.log(ex);
}
})();

tslint error Use arrow function instead of function expression

i am having tslint warnings and i am new to es6 and still having some difficulty with its syntax.so I am not entirely sure how to convert this one in arrow functions.
and here is my code:
let deletedQuestions = origQuestions.filter(function(obj) {
return !updatedQuestions.some(function(obj2) {
return obj.value == obj2.value;
});
});
console.log(deletedQuestions);
let addedQuestions = updatedQuestions.filter(function(obj) {
return !origQuestions.some(function(obj2) {
return obj.value == obj2.value;
});
});
I believe it would be
let deletedQuestions = origQuestions.filter(obj =>
!updatedQuestions.some(obj2 => obj.value == obj2.value)) console.log(deletedQuestions);
let addedQuestions = updatedQuestions.filter(obj =>
!origQuestions.some(obj2 => obj.value == obj2.value))
Right?

share data between 2 different controller with shared service

Hallo i have 2 different controller and i want to share some data from the first to the second.
First Controller:
validationApp.controller('loginCtrl'['auth','resetpass','$scope',function(auth,resetpass,$scope) {
$scope.login = function() {
auth.login($scope);
};
The auth service is:
validationApp.service('auth',function ($http,ipCookie,$rootScope,$state,localStorageService) {
$rootScope.authorized = false;
// function to submit the form after all validation has occurred
this.login = function ($scope) {
var hash1 =CryptoJS.SHA256($scope.password)
var rootElem = {};
var loginRequest = {
username: $scope.username,
hash: hash1.toString(CryptoJS.enc.Hex)
};
rootElem.loginRequest = loginRequest;
var makejson = JSON.stringify(rootElem);
$http({
method: 'PUT',
url: url+'/users/'+ $scope.username +'/login/',
data: makejson,
headers:{'Content-Type':'application/json'}
})
.success(function (data,status){
if (200 == status) {
if((data.loginResponse.roles[0] == "USER") && (data.loginResponse.roles[1] == "ADMIN")){
$rootScope.authorized = true;
$state.go('admin');
}
else {
$rootScope.authorized = true;
$state.go('user');
}
}
})
.error(function(data,status){
if (400 == status) {
$rootScope.authorized = false;
$scope.dataValidationError = true;
$scope.message = data.error.message;
}
else if(401 == status){
$rootScope.authorized = false;
$scope.dataValidationError = true;
$scope.message = data.error.message;
}
else if(500 == status){
$rootScope.authorized = false;
$scope.dataValidationError = true;
$scope.message = data.error.message;
}
})
}
data is the returned JSON from Backend.
I want to share some JSON data for example data.loginResponse.username in the second controller.
The second controller is:
validationApp.controller('Secondcontroller'['auth','$scope','$state',function(auth,$scope){}]);
It's for make welcome {{username}} after login.
If you want to share the data to another controller you could use $rootScope if you only need the username from the first controller like this:
Your first controller:
validationApp.controller('Firstcontroller', function(.....){
$scope.login = function() {
var data = auth.login($scope);
$rootScope.username = data.loginResponse.username;
};
});
Your second controller:
validationApp.controller('Secondcontroller', function(.....){
You could access $rootScope.username inside here...
});