Blazor WASM API call with windows credentials - browser

I have a problem with blazor WASM application (.NET6) and consuming an external API (ASP MVC Project).
The API expects windows authentication and CORS is enabled:
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
<add name="Access-Control-Allow-Methods" value="GET,POST,PUT,DELETE,OPTIONS" />
<add name="Access-Control-Allow-Credentials" value="true" />
</customHeaders>
</httpProtocol>
My http GET request in blazor:
var request = new HttpRequestMessage(HttpMethod.Get, _testEndpoint);
request.SetBrowserRequestCredentials(BrowserRequestCredentials.Include);
//request.SetBrowserResponseStreamingEnabled(true);
request.SetBrowserRequestMode(BrowserRequestMode.NoCors);
var response = await _httpClient.SendAsync(request);
//response.EnsureSuccessStatusCode();
var result = await response.Content.ReadFromJsonAsync<MY_JSON_OBJECT>();
return result;
launchSettings.json:
{
"iisSettings": {
"windowsAuthentication": true,
"anonymousAuthentication": false,
"iisExpress": {
"applicationUrl": "http://localhost:33694",
"sslPort": 44350
}
},
"profiles": {
"MyProjectTest": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}",
"applicationUrl": "http://localhost:7151;http://localhost:5151",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
The result is always that there is no content in the response and the status code = 0.
Error message: The input does not contain any JSON tokens. Expected the input to start with a valid JSON token, when isFinalBlock is true. Path: $ | LineNumber: 0 | BytePositionInLine: 0.
Can anyone help me here?

Related

Problem with CORS in Nest.js app after deployment on Vercel

POST request in my Nest.js app not working after deployment on Vercel and I receive CORS error, but cors in my app is enable and when I send GET request all working. When I test my request in postman all working. I am not sure but maybe this error can happen through that I use React Query or problem with vercel and I not right deployment my app.
I receive such error:
Access to XMLHttpRequest at 'https://server-store.vercel.app/api/auth/login' from origin 'https://next-store-liard-three.vercel.app' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
And I enabled CORS such method:
app.enableCors({
origin: ['http://localhost:3000', 'https://next-store-liard-three.vercel.app'],
allowedHeaders: ['Accept', 'Content-Type'],
methods: 'GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS',
preflightContinue: false,
optionsSuccessStatus: 204,
credentials: true,
});
This is my file vercel.json:
{
"version": 2,
"name": "next-store-server",
"buildCommand": "npm start",
"installCommand": "npm install",
"builds": [
{
"src": "dist/main.js",
"use": "#vercel/node"
}
],
"routes": [
{
"src": "/(.*)",
"dest": "dist/main.js",
"methods": ["GET", "POST", "PATCH", "PUT", "DELETE"]
}
]
}
Also I try enable CORS other way, but it is not help me.
I try enable CORS, such method:
const app = await NestFactory.create(AppModule, { cors: true });
On client I using Next.js, reactQuery and axios for sending request
import axios from "axios";
import { FAuth, IUser } from "./Auth.types";
const AuthService = {
async registration(dto: IUser) {
const { data } = await axios.post<FAuth>(
`${process.env.NEXT_PUBLIC_SERVER_API_URL}/api/auth/registration`,
dto,
);
return data;
},
async login(dto: IUser) {
const { data } = await axios.post<FAuth>(`${process.env.NEXT_PUBLIC_SERVER_API_URL}/api/auth/login`, dto);
return data;
},
};
This my custom useMutation hooks
export const useRegistration = () =>
useMutation((dto: Omit<IUser, "_id">) => AuthService.registration(dto), {
onSuccess: () => {
toast.success("Success", {
theme: "colored",
});
},
onError: (data: any) => {
toast.error(data.response.data.message, {
theme: "colored",
});
},
});
export const useLogin = () =>
useMutation((dto: Omit<IUser, "_id">) => AuthService.login(dto), {
onSuccess: () => {
toast.success("Success", {
theme: "colored",
});
},
onError: (data: any) => {
toast.error(data.response.data.message, {
theme: "colored",
});
},
});
Try to add "OPTIONS" into methods, this worked for me
vercel.json:
{
"version": 2,
"builds": [{ "src": "src/main.ts", "use": "#vercel/node" }],
"routes": [
{
"src": "/(.*)",
"dest": "src/main.ts",
"methods": ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"]
}
]
}

Problem with app update yml files is not generated in electron?

I have a problem with the auto-update of electron app,
After I finished all the app parts and I am trying to push it to my custom update server , I found this error message in my logger :
Error unknown ENOENT: no such file or directory, open
'C:\{appPath}\{appName}\resources\app-update.yml'
and here is my package.json build configuration
"build": {
"appId": "com.server.app",
"copyright": "Copyright company name",
"generateUpdatesFilesForAllChannels": true,
"win": {
"target": "nsis",
"icon": "build/icon.ico"
},
"mac": {
"target": "dmg",
"artifactName": "appName.dmg",
"icon": "build/icon.icns"
},
"dmg": {
"background": "build/i-bg.tif",
"icon": "build/setup.icns",
"iconSize": 80,
"title": "${productName}-${version}",
"window": {
"width": 540,
"height": 380
}
},
"nsis": {
"artifactName": "${productName}-Setup-${version}.${ext}",
"oneClick": false,
"perMachine": false,
"allowToChangeInstallationDirectory": true,
"installerIcon": "build/setup.ico",
"uninstallerIcon": "build/setup.ico",
"installerHeader": "build/installerHeader.bmp",
"installerSidebar": "build/installerSidebar.bmp",
"runAfterFinish": true,
"deleteAppDataOnUninstall": true,
"createDesktopShortcut": "always",
"createStartMenuShortcut": true,
"shortcutName": "AppName",
"publish": [{
"provider": "generic",
"url": "https://my-update-server/path"
}]
},
"extraFiles": [
"data",
"templates"
]
},
"publish": [{
"provider": "generic",
"url": "https://my-update-server/path"
}],
and here is the code for triggering the auto-update
//-----------------------------------------------
// Auto-Update event listening
//-----------------------------------------------
autoUpdater.on('checking-for-update', () => {
splashLoadingStatus(`Checking for ${appName} update ...`);
})
autoUpdater.on('update-available',(info) => {
splashLoadingStatus(`${appName} new update available.`);
})
autoUpdater.on('update-progress',(progInfo) => {
splashLoadingStatus(`Download speed: ${progInfo.bytesPerSecond} - Download ${progInfo.percent}% (${progInfo.transferred}/${progInfo.total})`);
})
autoUpdater.on('error' , (error) => {
dialog.showErrorBox('Error', error.message);
})
autoUpdater.on('update-downloaded', (info) => {
const message = {
type: 'info',
buttons: ['Restart', 'Update'],
title: `${appName} Update`,
detail: `A new version has been downloaded. Restart ${appName} to apply the updates.`
}
dialog.showMessageBox(message, (res) => {
if(res === 0) {
autoUpdater.quitAndInstall();
}
})
})
.....
autoUpdater.setFeedURL('https://my-update-server/path');
autoUpdater.checkForUpdatesAndNotify();
.....
then when I am pushing the build it will do everything correct with the latest.yml file generating but after installing I found the app-update.yml is not there ...
If you have a problem with missing app-update.yml and dev-app-update.yml then paste the following code into index.js:
import path from "path"
import fs from "fs"
const feed = 'your_site/update/windows_64'
let yaml = '';
yaml += "provider: generic\n"
yaml += "url: your_site/update/windows_64\n"
yaml += "useMultipleRangeRequest: false\n"
yaml += "channel: latest\n"
yaml += "updaterCacheDirName: " + app.getName()
let update_file = [path.join(process.resourcesPath, 'app-update.yml'), yaml]
let dev_update_file = [path.join(process.resourcesPath, 'dev-app-update.yml'), yaml]
let chechFiles = [update_file, dev_update_file]
for (let file of chechFiles) {
if (!fs.existsSync(file[0])) {
fs.writeFileSync(file[0], file[1], () => { })
}
}
I fixed it by using autoUpdater.setFeedURL() before autoUpdater.checkForUpdates(). Below is the code snippet that works for github releases. Also, please make sure there is existing release in Github before running this code.
import { autoUpdater } from "electron-updater";
// ...
autoUpdater.setFeedURL({
provider: "github",
owner: "org",
repo: "repo",
});

.NET Core API - IIS - cannot make it work

I created a simple .NET Core API with Visual studio 2019
I just cannot make it work
I go from 503 to 404 to connection refused, and so on...
I tried :
adding my app to an application pool with or without SSL and dev certificate
publishing the application in a folder and setting that folder in IIS like in many tutorials
then VS2019 complains about that and force the IIS site to be linked to the VS project root
I set bindings to 80 and 443 ( modded my host file to have fqdn of the web site to point to 127.0.0.1
I checked the IIS logs and I even added a Failed Request Tracking rule on port 503, no log file was ever produced, while the error clearly appeared
I tried by setting the wwwroot of the site to ../bin/debug or .../bin/release
launchSettings.json:
{
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iis": {
"applicationUrl": "http://*******-api.local",
"sslPort": 0
},
"iisExpress": {
"applicationUrl": "http://localhost:55973",
"sslPort": 44362
}
},
"$schema": "http://json.schemastore.org/launchsettings.json",
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "weatherforecast",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Local": {
"commandName": "IIS",
"launchBrowser": true,
"launchUrl": "weatherforecast",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"*********Api": {
"commandName": "Project",
"launchBrowser": true,
"launchUrl": "weatherforecast",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"applicationUrl": "https://localhost:5001;http://localhost:5000"
}
}
}
I deleted my project, recreated it,
I also installed the windows hosting bundle
also make sure the .NET CLR Version is set to No Managed Code
https://dotnet.microsoft.com/download/dotnet-core/thank-you/runtime-aspnetcore-3.1.6-windows-hosting-bundle-installer

.net core 2.2 app returns "This site can’t be reached" when run on IIS version 10

I have recently downloaded a copy of nopCommerce and installed it. Pressing F5 in visual studio, it ran successfully on IIS Express. I have now enabled IIS and would like to run this site on IIS but when I click "browse" in IIS I get the message "This site can’t be reached". I am running VS in admin mode and enabled development-time IIS support but I still haven't got it working.
launchSettings.json
{
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iis": {
"applicationUrl": "https://nopCommerce.local.com",
"sslPort": 0
}
},
"profiles": {
"Nop.Web": {
"commandName": "IIS",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"applicationUrl": "https://nopCommerce.local.com:443/"
},
"IIS": {
"commandName": "IIS",
"launchBrowser": true,
"launchUrl": "https://nopCommerce.local.com:443/",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"nativeDebugging": true
}
}
}
IIS Application Pool
.Net Clr version: No Managed code
Managed pipeline mode: integrated
IIS Site Bindings
Type: https
IP address: all unassigned
Port: 443
Host Name: nopCommerce.local.com
Required server name indication: false
Disable HTTP2: false
Disable OCSP stapling: false
SSL certificate: IIS Express Development Certificate

NightmareJS: how to set cookie?

var Nightmare = require('nightmare');
var nightmare = Nightmare({
show: true
})
nightmare
.goto('https://mail.yandex.ru')
.type('input[name=login]', 'mylogin')
.type('input[name=passwd]', 'mypassword')
.click('button.nb-button._nb-action-button.nb-group-start')
.wait('.mail-User-Name')
.cookies.get()
.then(function (cookies) {
//actions
})
I am getting cookies after authorization, but I don't know where I must set them and how I must set them. I've tried to do .cookie.set() at the beginning, but this doesn't work.
How I can use saved cookie? Thanks.
I did the following from the node terminal:
> var Nightmare = require('nightmare')
undefined
> var nightmare = Nightmare({show:true})
undefined
> nightmare.
... goto('https://google.com').
... cookies.set('foo', 'bar').
... cookies.get().
... then((cookies) => {
... console.log(JSON.stringify(cookies, null, 4))
... })
Promise { <pending> }
> [
{
"name": "NID",
"value": "96=qo1qY9LTKh1np4OSgiyJTi7e79-_OIoIuc71hnrKWvN1JUnDLJqZlE8u2ij_4mW0-JJhWOCafo5J0j-YkZCFt8H2VHzYUom4cfEd2QLOEsHmAcT2ACx4a5xSvO0SZGZp",
"domain": ".google.de",
"hostOnly": false,
"path": "/",
"secure": false,
"httpOnly": true,
"session": false,
"expirationDate": 1502733434.077271
},
{
"name": "CONSENT",
"value": "WP.25d07b",
"domain": ".google.de",
"hostOnly": false,
"path": "/",
"secure": false,
"httpOnly": false,
"session": false,
"expirationDate": 2145916800.077329
},
{
"name": "foo",
"value": "bar",
"domain": "www.google.de",
"hostOnly": true,
"path": "/",
"secure": false,
"httpOnly": false,
"session": true
}
]
nightmare.cookies.set('key', 'value') is indeed the correct way to use it, as you can see in my result object. Perhaps https://mail.yandex.ru does not accept your cookie, because it's invalid. Please do the same and edit your question to include your results.
Edit: Apparently, OP needs to store the cookies so he can use them in another Nightmare instance. This can be achieved like this:
var Nightmare = require('nightmare')
var storedCookies // This is where we will store the cookies. It could be stored in a file or database to make it permanent
// First instance:
var nightmare1 = Nightmare({show: true})
nightmare1.
goto('https://google.com').
cookies.get().
then((cookies) => {
storedCookies = cookies
})
// Second instance:
var nightmare2 = Nightmare({show: true})
for(var i = 0; i < storedCookies.length; i++)
nightmare2.
cookies.set(storedCookies[i].name, storedCookies[i].value)
nightmare2.
goto('https://google.com')

Resources