How to use token base auth in jupyterhub? - jupyter-notebook

I am trying to use jupyterhub using token-based which is in Iframe.
I had tried using postman by sending token as header it worked.
But in browser
$.ajax({
type : "GET",
url : "http://jupiter.****.com/hub/login",
beforeSend: function(xhr){xhr.setRequestHeader('Authorization', 'token *****');
},
success : function(result) {
},
error : function(result) {
}
});
It gives me a Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at ***. (Reason: CORS request did not succeed)
I had configured jupyterhub_config.py
c.JupyterHub.tornado_settings = {'headers': {'Content-Security-Policy': "frame-ancestors * 'self' " ,'Access-Control-Allow-Origin': '*','Access-Control-Allow-Methods':'*','Access-Control-Allow-Headers':'*','Access-Control-Allow-Credentials':'true'}}
c.Spawner.args = [f'--NotebookApp.allow_origin=*']
Any pointers/advice on how to implement this would be greatly appreciated!

Related

on Nextjs, how to perform a fetch request from an an external public api?

The api is public. Access privallages are to any and everyone.
I've made the same fetch-calls using frameworks such as angular, but on Nextjs I keep running into cors policy errors.
Can someone please explain how I can get the fetch call to work, or provide an example.
I can't fetch from local host as well. There's clearly an error in my practice.
'Access to fetch at '...' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.'
Code example, if helpful:
let fetched =
await fetch('http://127.0.0.1:5001/helloWorld'
, { method: 'GET',
}).then((result)=> console.log('promise complete', result.status));
You need to set mode:'cors'
const response = await fetch(url, {
method: 'GET', // *GET, POST, PUT, DELETE, etc.
mode: 'cors',
headers: {
'Content-Type': 'application/json'
// 'Content-Type': 'application/x-www-form-urlencoded',
}
});

CORS enabled, but adding cookies in header causes request to be blocked? I have enabled CORS with credentials server side, not sure how to solve this

Using express-session so need cookie id for authentication, but even with setting up CORS correctly (or what I thought to be) on front and back end I'm still getting issues. CORS is working without cookies enabled.
Backend config
const corsOptions = {
origin: "*",
methods: "GET,HEAD,PUT,PATCH,POST,DELETE",
preflightContinue: false,
optionsSuccessStatus: 204,
credentials: true,
};
Frontend config (using Relay)
const response = await fetch("http://localhost:4002/graphql", {
method: "POST",
credentials: "include", // Allow cookies to be sent
headers: {
Authorization: `*/*`,
"Content-Type": "application/json",
}
If I do not include credentials the response shows that CORS cookies are allowed:
However, as soon as I enable credentials in the client fetch config, the request is blocked. There is no response, I think Firefox is blocking the req before it is sent?
Thank you in advance for any help!
The issue was not setting the accepted CORS origins to "*", as said in the console (thanks Quentin).

Firebase storage upload signed URL CORS issue

I am building an app for the web hosted on Firebase where I am trying to allow unauthenticated users to upload an image to Storage (after passing a reCAPTCHA).
To do this I have a React website and a Firebase function that validates the reCAPTCHA and then generates a signed URL for the client-side code to upload the image to the default bucket. I have deployed the Function to the cloud because there is no Storage emulator I can use for local development but my React app is being served locally.
The code below omits the usual boilerplate.
Firebase Function Code:
const id = uuidv4()
const bucket = storage.bucket("project-id.appspot.com");
const file = bucket.file(id)
const expires_at = Date.now() + 300000;
const config = {
action: 'write',
version: 'v2',
expires: expires_at,
contentType: 'application/octet-stream'
};
file.getSignedUrl(config, (err, url) => {
if (err) {
console.error(err);
res.status(500).end();
return;
}
res.send(url);
});
This returns a URL to the client of the form: https://storage.googleapis.com/project-id.appspot.com/db9a5cc5-6540-4f40-933f-cfdb287b15a9?GoogleAccessId=project-id%40appspot.gserviceaccount.com&Expires=1594719835&Signature=<signature here>
Client-side Code:
Once this is received on the client-side I try to upload the file to that URL using the PUT method:
// signed_url is the url returned from the first API call to the function above.
// image_file is the file data I get from using react-dropzone.
axios({
method: 'put',
url: signed_url,
data: image_file,
headers: {'Content-Type':'application/octet-stream'}
}).then(res => {
console.log("success");
console.log(res);
}).catch((error) => {
console.log(error);
});
This is where I get a CORS error of the form: Access to XMLHttpRequest at 'https://storage.googleapis.com/project-id.appspot.com/db9a5cc5-6540-4f40-933f-cfdb287b15a9?GoogleAccessId=project-id%40appspot.gserviceaccount.com&Expires=1594719835&Signature=<signature here>' from origin 'http://localhost:3000' 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.
I used cURL to see if the CORS headers in the response were being set and they were not. I then used gsutil cors set config.json gs://project-id.appspot.com to set the CORS permissions on the default bucket. Here is the format of the configuration:
[
{
"origin": ["*"],
"responseHeader": [
"Origin",
"Accept",
"x-goog-resumable",
"Content-Type",
"Access-Control-Allow-Origin",
"Access-Control-Allow-Headers",
"Authorization",
"X-Requested-With"
],
"method": ["GET, POST, PUT, PATCH, POST, DELETE, OPTIONS"],
"maxAgeSeconds": 3600
}
]
I checked the service account to make sure they had the Service Account Token Creator permission and Storage Object Creator permissions set and they did.
I followed the steps at https://cloud.google.com/functions/docs/writing/http#gcloud and I have tried every combination of content-type headers and tried v2 and v4 of getSignedURL version, as well as following any other suggestions I could find online, but to no avail.

GRPC with HTTP transcoding and CORS - error case issue

Transcoding is working for the non-error use case.
I had to configure nginx differently to enable CORS (which is not clear in the docs IMO).
I use grpc java and handle an error like this for the simple hello message:
#Override
public void sayHello(UserOuterClass.HelloRequest request, StreamObserver<UserOuterClass.HelloReply> responseObserver) {
log.info("there is a hello request");
if(request.getName().equals("coucou")){
log.info("coucou is forbidden");
responseObserver.onError(Status.NOT_FOUND.asException());
return;
}
UserOuterClass.HelloReply.Builder replyBuilder = UserOuterClass.HelloReply.newBuilder();
replyBuilder.setMessage("coucou " + request.getName());
responseObserver.onNext(replyBuilder.build());
responseObserver.onCompleted();
log.info("there has been a response");
}
Now when a request is sent from chrome there is a preflight call which seems ok. But the GET itself corresponding to sayHello function above fails with a CORS issue:
Failed to load http://xxxxxx:8080/v1/hello?name=coucou: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 404.
If the response is ok, the cors headers are present. If it's an error like here, then the cors header are not there.
Moreover here is the response returned by endpoints:
{
"code": 5,
"message": "",
"details": [
{
"#type": "type.googleapis.com/google.rpc.DebugInfo",
"stackEntries": [],
"detail": "internal"
}
]
}

Http REST call problems No 'Access-Control-Allow-Origin' on POST

I have not been able to get Angular $http to communicate with a remote REST service. I have tried Restangular and $resource too. The problem seems to be with the underlying $http service and CORS limitations. I think I just need to get my headers right. Do I also need to tweak my server config?
I am getting the following error:
XMLHttpRequest cannot load http://www.EXAMPLE-DOMAIN.com/api/v2/users/sign_in. No 'Access-Control- Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access.
I have researched this a lot. Currently I have tried setting the $httpProvider headings when configuring my app module and played with $http headers. Below is some of my current code.
My Service
app.service('Auth', function($http) {
var headers = {
'Access-Control-Allow-Origin' : '*',
'Access-Control-Allow-Methods' : 'POST, GET, OPTIONS, PUT',
'Content-Type': 'application/json',
'Accept': 'application/json'
};
return $http({
method: "POST",
headers: headers,
url: 'http://www.EXAMPLE-DOMAINcom/api/v2/users/sign_in',
data: {"email":"my#email.com","password":"secret"}
}).success(function(result) {
console.log("Auth.signin.success!")
console.log(result);
}).error(function(data, status, headers, config) {
console.log("Auth.signin.error!")
console.log(data);
console.log(status);
console.log(headers);
console.log(config);
});
});
App Config
var app = angular.module('starter', ['ionic', 'app.controllers', $httpProvider])
.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.useXDomain = true;
$httpProvider.defaults.headers.common = 'Content-Type: application/json';
delete $httpProvider.defaults.headers.common['X-Requested-With'];
}
])
If you are in control of the server, you might need to set the required headers there. Depending on which server, this might help: http://enable-cors.org/server.html

Resources