I’m writing an extension for Google Chrome using Manifest 3 version, I’ll attach the code below, the problem is that in a similar way in Manifest 2, proxies were authorized when requesting a site like fetch, and in version 3 it authorizes only when you go to the site yourself, when requested, it issues 407 error that the proxy is not authorized, is there a way to authorize when sending a request?
var proxy = {
cache: [],
temp: [],
get: async() => {
var proxyObj = await database.get("proxy_list");
if (proxy.temp.length == 0) {
proxyObj.forEach((i) => proxy.temp.push(i));
return proxy.temp.shift();
}
return proxy.temp.shift();
},
set: async function() {
proxy.cache = await proxy.get();
var proxObj = {
type: "http",
host: proxy.cache.ip,
port: proxy.cache.port,
};
var config = {
mode: "fixed_servers",
rules: {
singleProxy: {
scheme: proxObj.type,
host: proxObj.host,
port: parseInt(proxObj.port),
},
},
};
if (proxy.cache.login != null && proxy.cache.password != null) {
proxy.auth(proxy.cache.login, proxy.cache.password);
}
try {
chrome.proxy.settings.set({
value: config,
scope: "regular"
},
function() {}
);
} catch (error) {
chrome.proxy.settings.set({
value: config,
scope: "regular"
},
function() {}
);
}
proxy.cache = [];
},
auth: (login, password) => {
chrome.webRequest.onAuthRequired.addListener(
(details, callback) => {
const authCredentials = {
username: login,
password: password
};
callback({
authCredentials
});
}, {
urls: ["<all_urls>"]
}, ["asyncBlocking"]
);
},
};
Related
I am following the explanations from this website: https://aws.amazon.com/de/getting-started/hands-on/build-flutter-mobile-app-part-two/module-four/
If I start the application, a profile is not created, which should be happening in "custom.js".
const { Sha256 } = require("#aws-crypto/sha256-js");
const { defaultProvider } = require("#aws-sdk/credential-provider-node");
const { SignatureV4 } = require("#aws-sdk/signature-v4");
const { HttpRequest } = require("#aws-sdk/protocol-http");
const { default: fetch, Request } = require("node-fetch");
const GRAPHQL_ENDPOINT = process.env.API_AMPLIFYTRIPSPLANNER_GRAPHQLAPIENDPOINTOUTPUT;
const AWS_REGION = process.env.AWS_REGION || 'us-east-1';
const query = /* GraphQL */ `
mutation createProfile($email: String!,$owner: String!) {
createProfile(input: {
email: $email,
owner: $owner,
}) {
email
}
}
`;
/**
* #type {import('#types/aws-lambda').PostConfirmationTriggerHandler}
*/
exports.handler = async (event) => {
console.log(`EVENT: ${JSON.stringify(event)}`);
const variables = {
email: event.request.userAttributes.email,
owner: `${event.request.userAttributes.sub}::${event.userName}`
};
const endpoint = new URL(GRAPHQL_ENDPOINT);
const signer = new SignatureV4({
credentials: defaultProvider(),
region: AWS_REGION,
service: 'appsync',
sha256: Sha256
});
const requestToBeSigned = new HttpRequest({
method: 'POST',
headers: {
'Content-Type': 'application/json',
host: endpoint.host
},
hostname: endpoint.host,
body: JSON.stringify({ query, variables }),
path: endpoint.pathname
});
const signed = await signer.sign(requestToBeSigned);
const request = new Request(endpoint, signed);
let statusCode = 200;
let body;
let response;
try {
response = await fetch(request);
body = await response.json();
if (body.errors) statusCode = 400;
} catch (error) {
statusCode = 500;
body = {
errors: [
{
message: error.message
}
]
};
}
console.log(`statusCode: ${statusCode}`);
console.log(`body: ${JSON.stringify(body)}`);
return {
statusCode,
body: JSON.stringify(body)
};
};
I was expecting the profile to be created, when I run the application. But there is no profile created.
Cloud watch is providing this error log message:
{
"data": {
"createProfile": null
},
"errors": [
{
"path": [
"createProfile"
],
"data": null,
"errorType": "Unauthorized",
"errorInfo": null,
"locations": [
{
"line": 3,
"column": 6,
"sourceName": null
}
],
"message": "Not Authorized to access createProfile on type Profile"
}
]
}
I am trying to understand the two problems:
The data should not be null
There should not be an authorization problem (which maybe a follow-on from the data issue)
I have not found any useful hints yet.
What needs to be changed?
I now realized my error. I did not follow the instructions to start the second tuturial within a clean directory. The Amplify configuration required a change in the Auth module, that can only be implemented in a new project (you cannot change auth type after deploying an app).
I used got and request-promise modules for scraping, but I got a spinner circle in response.
Basically, I want get video items not spinner circle.
/* This example use request-promise */
const rp = require('request-promise');
const url = 'https://charts.youtube.com/charts/TrendingVideos/gb';
rp(url)
.then(function (html) {
//success!
fs.writeFileSync('./index.html', html);
})
.catch(function (err) {
//handle error
});
/* This example use got */
got('https://charts.youtube.com/').then(response => {
fs.writeFileSync('./index.html', response.body);
const dom = new JSDOM(response.body);
dom.window.document.querySelectorAll('a').forEach(link => {
console.log(link.href);
});
}).catch(err => {
console.log(err);
});
Can someone help me?
The data comes from an API on :
POST https://charts.youtube.com/youtubei/v1/browse?alt=json&key=${apiKey}
You need to get the api key from the html using regex and then perform the call with the required input data :
const got = require("got");
const util = require("util");
(async () => {
let response = await got(
"https://charts.youtube.com/charts/TrendingVideos/gb"
);
let keyRegex = /\"INNERTUBE_API_KEY\"\s*:\s*\"(.*?)\"/gm;
let apiKey = keyRegex.exec(response.body)[1];
response = await got.post(`https://charts.youtube.com/youtubei/v1/browse?alt=json&key=${apiKey}`,
{
json: {
context: {
client: {
clientName: "WEB_MUSIC_ANALYTICS",
clientVersion: "0.2",
hl: "en",
gl: "en",
experimentIds: [],
experimentsToken: "",
theme: "MUSIC",
},
capabilities: {},
request: {
internalExperimentFlags: [],
},
},
browseId: "FEmusic_analytics_charts_home",
query:
"chart_params_type=WEEK&perspective=CHART&flags=viral_video_chart&selected_chart=TRACKS&chart_params_id=weekly%3A0%3A0%3Agb",
},
responseType: "json",
headers: {
referer: "https://charts.youtube.com/charts/TrendingVideos/gb",
},
}
);
videoTrend = response.body.contents.sectionListRenderer.contents[0].musicAnalyticsSectionRenderer.content.videos;
console.log(util.inspect(videoTrend, { showHidden: false, depth: null }));
})();
Try this on repl.it
I have spent the night looking for solutions to this issue, it seems like a lot of people have it and the best advice is often "just switch to SPA mode", which is not an option for me.
I have JWT for authentication, using the JWTSessions gem for Rails.
On the frontend, I have Nuxt with nuxt-auth, using a custom scheme, and the following authorization middleware:
export default function ({ $auth, route, redirect }) {
const role = $auth.user && $auth.user.role
if (route.meta[0].requiredRole !== role) {
redirect('/login')
}
}
The symptom I have is as follows: if I log in and navigate around restricted pages, everything works as expected. I even have fetchOnServer: false for restricted pages, as I only need SSR for my public ones.
However, once I refresh the page or just navigate directly to a restricted URL, I get immediately redirected to the login page by the middleware. Clearly, the user that's authenticated on the client side is not being authenticated on the server side too.
I have the following relevant files.
nuxt.config.js
...
plugins: [
// ...
{ src: '~/plugins/axios' },
// ...
],
// ...
modules: [
'cookie-universal-nuxt',
'#nuxtjs/axios',
'#nuxtjs/auth'
],
// ...
axios: {
baseURL: process.env.NODE_ENV === 'production' ? 'https://api.example.com/v1' : 'http://localhost:3000/v1',
credentials: true
},
auth: {
strategies: {
jwtSessions: {
_scheme: '~/plugins/auth-jwt-scheme.js',
endpoints: {
login: { url: '/signin', method: 'post', propertyName: 'csrf' },
logout: { url: '/signin', method: 'delete' },
user: { url: '/users/active', method: 'get', propertyName: false }
},
tokenRequired: true,
tokenType: false
}
},
cookie: {
options: {
maxAge: 64800,
secure: process.env.NODE_ENV === 'production'
}
}
},
auth-jwt-scheme.js
const tokenOptions = {
tokenRequired: true,
tokenType: false,
globalToken: true,
tokenName: 'X-CSRF-TOKEN'
}
export default class LocalScheme {
constructor (auth, options) {
this.$auth = auth
this.name = options._name
this.options = Object.assign({}, tokenOptions, options)
}
_setToken (token) {
if (this.options.globalToken) {
this.$auth.ctx.app.$axios.setHeader(this.options.tokenName, token)
}
}
_clearToken () {
if (this.options.globalToken) {
this.$auth.ctx.app.$axios.setHeader(this.options.tokenName, false)
this.$auth.ctx.app.$axios.setHeader('Authorization', false)
}
}
mounted () {
if (this.options.tokenRequired) {
const token = this.$auth.syncToken(this.name)
this._setToken(token)
}
return this.$auth.fetchUserOnce()
}
async login (endpoint) {
if (!this.options.endpoints.login) {
return
}
await this._logoutLocally()
const result = await this.$auth.request(
endpoint,
this.options.endpoints.login
)
if (this.options.tokenRequired) {
const token = this.options.tokenType
? this.options.tokenType + ' ' + result
: result
this.$auth.setToken(this.name, token)
this._setToken(token)
}
return this.fetchUser()
}
async setUserToken (tokenValue) {
await this._logoutLocally()
if (this.options.tokenRequired) {
const token = this.options.tokenType
? this.options.tokenType + ' ' + tokenValue
: tokenValue
this.$auth.setToken(this.name, token)
this._setToken(token)
}
return this.fetchUser()
}
async fetchUser (endpoint) {
if (this.options.tokenRequired && !this.$auth.getToken(this.name)) {
return
}
if (!this.options.endpoints.user) {
this.$auth.setUser({})
return
}
const user = await this.$auth.requestWith(
this.name,
endpoint,
this.options.endpoints.user
)
this.$auth.setUser(user)
}
async logout (endpoint) {
if (this.options.endpoints.logout) {
await this.$auth
.requestWith(this.name, endpoint, this.options.endpoints.logout)
.catch(() => {})
}
return this._logoutLocally()
}
async _logoutLocally () {
if (this.options.tokenRequired) {
this._clearToken()
}
return await this.$auth.reset()
}
}
axios.js
export default function (context) {
const { app, $axios, redirect } = context
$axios.onResponseError(async (error) => {
const response = error.response
const originalRequest = response.config
const access = app.$cookies.get('jwt_access')
const csrf = originalRequest.headers['X-CSRF-TOKEN']
const credentialed = (process.client && csrf) || (process.server && access)
if (credentialed && response.status === 401 && !originalRequest.headers.REFRESH) {
if (process.server) {
$axios.setHeader('X-CSRF-TOKEN', csrf)
$axios.setHeader('Authorization', access)
}
const newToken = await $axios.post('/refresh', {}, { headers: { REFRESH: true } })
if (newToken.data.csrf) {
$axios.setHeader('X-CSRF-TOKEN', newToken.data.csrf)
$axios.setHeader('Authorization', newToken.data.access)
if (app.$auth) {
app.$auth.setToken('jwt_access', newToken.data.csrf)
app.$auth.syncToken('jwt_access')
}
originalRequest.headers['X-CSRF-TOKEN'] = newToken.data.csrf
originalRequest.headers.Authorization = newToken.data.access
if (process.server) {
app.$cookies.set('jwt_access', newToken.data.access, { path: '/', httpOnly: true, maxAge: 64800, secure: false, overwrite: true })
}
return $axios(originalRequest)
} else {
if (app.$auth) {
app.$auth.logout()
}
redirect(301, '/login')
}
} else {
return Promise.reject(error)
}
})
}
This solution is already heavily inspired by material available under other threads and at this point I am pretty much clueless regarding how to authenticate my users universally across Nuxt. Any help and guidance much appreciated.
In order for You not to lose Your authentication session in the system, You first need to save your JWT token to some storage on the client: localStorage or sessionStorage or as well as token data can be saved in cookies.
For to work of the application will be optimally, You also need to save the token in the store of Nuxt. (Vuex)
If You save Your token only in srore of Nuxt and use only state, then every time You refresh the page, Your token will be reset to zero, since the state will not have time to initialize. Therefore, you are redirected to the page /login.
To prevent this from happening, after you save Your token to some storage, You need to read it and reinitialize it in the special method nuxtServerInit(), in the universal mode his will be work on the server side the very first. (Nuxt2)
Then, accordingly, You use Your token when sending requests to the api server, adding to each request that requires authorization, a header of the Authorization type.
Since Your question is specific to the Nuxt2 version, for this version a working code example using cookies to store the token would be:
/store/auth.js
import jwtDecode from 'jwt-decode'
export const state = () => ({
token: null
})
export const getters = {
isAuthenticated: state => Boolean(state.token),
token: state => state.token
}
export const mutations = {
SET_TOKEN (state, token) {
state.token = token
}
}
export const actions = {
autoLogin ({ dispatch }) {
const token = this.$cookies.get('jwt-token')
if (isJWTValid(token)) {
dispatch('setToken', token)
} else {
dispatch('logout')
}
},
async login ({ commit, dispatch }, formData) {
const { token } = await this.$axios.$post('/api/auth/login', formData, { progress: false })
dispatch('setToken', token)
},
logout ({ commit }) {
this.$axios.setToken(false)
commit('SET_TOKEN', null)
this.$cookies.remove('jwt-token')
},
setToken ({ commit }, token) {
this.$axios.setToken(token, 'Bearer')
commit('SET_TOKEN', token)
this.$cookies.set('jwt-token', token, { path: '/', expires: new Date('2024') })
// <-- above use, for example, moment or add function that will computed date
}
}
/**
* Check valid JWT token.
*
* #param token
* #returns {boolean}
*/
function isJWTValid (token) {
if (!token) {
return false
}
const jwtData = jwtDecode(token) || {}
const expires = jwtData.exp || 0
return new Date().getTime() / 1000 < expires
}
/store/index.js
export const state = () => ({
// ... Your state here
})
export const getters = {
// ... Your getters here
}
export const mutations = {
// ... Your mutations here
}
export const actions = {
nuxtServerInit ({ dispatch }) { // <-- init auth
dispatch('auth/autoLogin')
}
}
/middleware/isGuest.js
export default function ({ store, redirect }) {
if (store.getters['auth/isAuthenticated']) {
redirect('/admin')
}
}
/middleware/auth.js
export default function ({ store, redirect }) {
if (!store.getters['auth/isAuthenticated']) {
redirect('/login')
}
}
/pages/login.vue
<template>
<div>
<!-- Your template here-->
</div>
</template>
<script>
export default {
name: 'Login',
layout: 'empty',
middleware: ['isGuest'], // <-- if the user is authorized, then he should not have access to the page !!!
data () {
return {
controls: {
login: '',
password: ''
},
rules: {
login: [
{ required: true, message: 'login is required', trigger: 'blur' }
],
password: [
{ required: true, message: 'password is required', trigger: 'blur' },
{ min: 6, message: 'minimum 6 length', trigger: 'blur' }
]
}
}
},
head: {
title: 'Login'
},
methods: {
onSubmit () {
this.$refs.form.validate(async (valid) => { // <-- Your validate
if (valid) {
// here for example: on loader
try {
await this.$store.dispatch('auth/login', {
login: this.controls.login,
password: this.controls.password
})
await this.$router.push('/admin')
} catch (e) {
// eslint-disable-next-line no-console
console.error(e)
} finally {
// here for example: off loader
}
}
})
}
}
}
</script>
! - You must have the following packages installed:
cookie-universal-nuxt
jsonwebtoken
jwt-decode
I think you will find my answer helpful. If something is not clear, ask!
Trying to run apollo-server in hapi. I have working cookie authorization in hapi, but I can't control queries to graphql. validateFunc is not called on graphql queries.
validateFunc is called after login with http://localhost:8080/login
But queries to http://localhost:8080/graphql do not call validateFunc.
If i'll set auth mode of graphql to required, i'll receive not authorizaed error, but validateFunc still not called.
const Hapi = require("#hapi/hapi"); //v18.3.2
const { ApolloServer, gql } = require("apollo-server-hapi"); //v2.8.1
const typeDefs = gql`
type Query {
_: String
}
type Mutation {
_: String
}
`;
const resolvers = {
Query: {},
Mutation: {}
};
const runServer = async () => {
const server = new Hapi.server({ port: 8080 });
await server.register(require("#hapi/cookie"));
server.auth.strategy("session", "cookie", {
cookie: {
name: "test-project",
password:
"long-long-password-long-long-password-long-long-password-long-long-password",
isSecure: false
},
validateFunc: async (request, session) => {
console.log("Why it is not called on graphql queries???");
return { valid: true, credentials: "account" };
}
});
server.auth.default("session");
//GRAPH QL!
const graphqlServer = new ApolloServer({
typeDefs,
resolvers,
context: async function(q) {
console.log("Graphql context was called!");
return q;
},
introspection: false,
playground: true,
route: {
options: {
auth: {
mode: "try"
}
}
}
});
server.route([
{
method: "GET",
path: "/login",
handler: function(request, h) {
request.cookieAuth.set({ id: "key" });
return "LOGIN!";
},
options: {
auth: {
mode: "try"
}
}
},
{
method: "GET",
path: "/test",
handler: function(request, h) {
console.log("TEST");
return "OK";
},
options: {
auth: {
mode: "try"
}
}
}
]);
await graphqlServer.applyMiddleware({
app: server,
route: {
auth: { mode: "try" }
}
});
await graphqlServer.installSubscriptionHandlers(server.listener);
await server.start().then(() => {
console.log(`🚀 Server ready at ${server.info.uri}/graphql `);
});
};
runServer();
Expecting graphql queries execute hapi's validateFunc()
Hi I am migrating to Hapi 17 from 16. I have my routes defined in a different file which I am trying to register as a plugin. But I get a 404 when I call the API. The routes are not registered with the server.
This is my Server code.
'use strict'
const Hapi = require('hapi')
const server = new Hapi.Server({ port: 1234, host: 'localhost' });
const plugins = [{
plugin: require('vision'),
plugin: require('./methods/exampleMethod'),
plugin: require('./routes/devices')
}]
async function registerPlugin(){
await server.register(plugins)
}
registerPlugin().then( () => {server.start()})
This is my routes file devices.js:
exports.plugin = {
register: (server, options) =>
{
server.routes = [{
method: 'GET',
path: '/v1/devices',
handler: async function (request, h) {
const val = server.methods.testMethod("ankur")
const response = h.response('hello world ankur')
response.type('text/plain')
return response
}
}]
},
name: 'devices'
}
Methods file
exports.plugin = {
register: (server, options) => {
server.method(
{
name: 'testMethod',
method: function (id) {
return new Promise(function (resolve, reject) {
return resolve("Test method called")
})
}
})
},
name: "exampleMethod"
I am following the release notes for Hapi 17 and trying to register the routes as a custom plugin. However, when I hit the Get v1/devices I get a 404.
Following code for your routes file will work:
exports.plugin = {
register: (server, options) => {
server.route(
{
method: "GET",
path: "/v1/devices",
handler: async function(request, h) {
//const val = server.methods.testMethod("ankur")
const response = h.response("hello world ankur");
response.type("text/plain");
return response;
}
}
);
},
name: "devices"
};
You should call server.route() function with your route object.
If you like to register more than one function through your routes plugin use something like this:
exports.plugin = {
register: (server, options) => {
const routes = [
{
method: "GET",
path: "/v1/devices",
handler: async function(request, h) {
const response = h.response("hello world");
response.type("text/plain");
return response;
}
},
{
method: "GET",
path: "/v1/another",
handler: async function(request, h) {
const response = h.response("hello another world");
response.type("text/plain");
return response;
}
}
];
server.route(routes);
},
name: "devices"
};
Edit:
Methods plugin
exports.plugin = {
register: (server, options) => {
server.method("testMethod", async function(id) {
return "Test method called";
});
},
name: "exampleMethod"
};
Call the method:
{
method: "GET",
path: "/v1/example",
handler: async function(request, h) {
const response = await request.server.methods.testMethod();
return response;
}
}