Unable to pass _oauth2_proxy_{0,1,2} cookies in cors calls to istio - cookies

I have a service blocked under oauth2_proxy which requires login , however i am unable to to pass theses oauth2_proxy cookies when making cors calls.
I have tried
return $.ajax({
url: url,
...
xhrFields: {
withCredentials: true
},
crossDomain: true,
...
});
}
and on the server side , I have ensured that all origins are whitelisted with a whitelist.
Is there a way to pass `oauth2_proxy{0,1,2}` cookies for cors calls?
Here is my configuration
- - oauth2-proxy
- --use-oidc-implicit-flow=false
- --ssl-upstream-insecure-skip-verify=true
- --oidc-client-id-path=/vault-secrets/service-client-id
- --oidc-client-secret-path=/vault-secrets/service-client-secret
- --oidc-cookie-secret-path=/vault-secrets/cookie-secret
- --pass-authorization-header=true
- --pass-access-token=true
- --set-authorization-header=true
- --set-xauthrequest=true
- --reverse-proxy=true

Related

AWS Cloudfront Behaviors Function not redirecting

Trying to figure out a way to redirect traffic from my AWS CloudFront page to another URL.
I'm currently setting up a "Function" using Cloudfront Functions.
Function code (function name = exampleFunction):
function handler(event) {
var redirectUrl = "https://example.com"
var response = {
statusCode: 302,
statusDescription: 'Found',
headers: {
'Location': { value: redirectUrl }
}
};
return response;
}
I publish that and then on my Cloudfront Distribution Behaviors, I create a behavior:
- Path Pattern: /to/my/page.html
- Origin and origin groups: example-origin-on-aws
- Compress objects automatically: No
- Viewer protocol Policy: Http and Https
- Allowed HTTP methods: GET, HEAD
- Restrict viewer access: No
- Cache key and origin requests: Cache policy and origin request policy
- Function asssociations:
- Viewer request:
- Function type: CloudFront Functions
- Function ARN / Name: exampleFunction
I then save the changes.
I also have the following Origin settings:
- Origin domain: BucketName
- Name: BucketName
- S3 bucket access:
- Yes use OAI:
- Origin access identity: My OAI
- Bucket policy: Yes
- Enable Origin Sheild: No
Then when I try to navigate to "https://s3.amazonaws.com/BucketName/to/my/page.html", it still takes me to that page instead of redirecting me to "https://example.com".
Any suggestions to point me in the right direction, or as to what I'm doing wrong would be greatly appreciated.

Lambda#Edge fallback to custom origin from s3 with cloudfront without hardcoded domains

I have CloudFront distribution with origin group [s3, custom]
I want to have the content served from s3, but when given a certain header - fallback to the custom origin.
I have a lambda#edge function that runs on origin request and I've checked the headers - now I need to redirect the request to the custom origin.
Questions:
As I understand, the Lambd#edge should run twice with a fallback origin as described here
https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/high_availability_origin_failover.html
So I want to return {status: 404} if the origin is s3 and fallback from CloudFront to the custom origin - how should I do that? does event.origin contain once s3 and once custom? or both?
When I return 404, the user gets a 404 response and no fallback is performed.
if (!request.origin.s3) {
callback(null, { status: '404' });
return;
}
To perform the fallback, I override the origin as described here
https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/lambda-examples.html#lambda-examples-content-based-custom-origin-request-trigger
request.origin = {
custom: {
domainName: 'www.example.com',
port: 443,
protocol: 'https',
path: '',
sslProtocols: ['TLSv1'],
readTimeout: 10,
keepaliveTimeout: 5,
customHeaders: {},
},
};
Can I get the domain name somehow from the CloudFront distribution?

Express Gateway - Proxy request with Bearer Token

I am trying to figure out how to get Express Gateway to use the Auth Bearer token in request, upstream to the api service.
Below is my config as of right now.
http:
port: 8080
admin:
port: 9876
host: localhost
apiEndpoints:
api:
host: localhost
paths:
- '/truck-api/*'
- '/car-api/*'
serviceEndpoints:
truck-service:
url: 'http://10.0.0.2:5010/api'
car-service:
url: 'http://10.0.0.2:5011/api'
policies:
- basic-auth
- cors
- expression
- key-auth
- log
- oauth2
- proxy
- rate-limit
- rewrite
- request-transformer
pipelines:
default:
apiEndpoints:
- api
policies:
- proxy:
-
condition:
name: pathMatch
pattern: "^/truck-api/(.*)"
action:
serviceEndpoint: truck-service
prependPath: true
ignorePath: false
stripPath: true
changeOrigin: true
-
condition:
name: pathMatch
pattern: "^/car-api/(.*)"
action:
serviceEndpoint: car-service
prependPath: true
ignorePath: false
stripPath: true
changeOrigin: true
The frontend calls express gateway with a proper auth bearer token, however the express gateway doesn't forward that auth bearer token on to the upstream service.
Advice?
After some digging and a lot of trial and error the solution was relatively simple, use request transformer.
added this to the policies section:
- request-transformer:
- action:
headers:
remove: ['Authorization']
add:
Authorization: "'Bearer ***'"
For me remove: ['Authorization'] did not work.
I was authenticating towards express gateway using:
"Authorization: apiKey ${keyId}:${keySecret}" and authenticating towards backend service by using Authorization: "'Bearer ***'" added by request-transformer. I would expect remove: ['Authorization'] would remove "Authorization: apiKey ${keyId}:${keySecret}", after I was already successfully authenticated at express gateway and add: Authorization: "'Bearer ***'" would add new Authorization header so newly constructed request would replace apiKey with Bearer token but using remove: ['Authorization'] resulted in failure to authenticate at express gateway.
I resolved this issue by changing HTTP header used for authorization at express gateway side with apiKeyHeader (https://www.express-gateway.io/docs/policies/key-authorization/).
policies:
- request-transformer:
- action:
headers:
add:
# pass oauth2 token
Authorization: "'Bearer ***'"
- key-auth:
- action:
# arbitrarily rename default header name from Authorization
apiKeyHeader: open_sesame
The open_sesame header grants us access to api gateway and request-transformer adds authorization header with proper token to the request for accessing the backend service.
curl -v -H "open_sesame: apiKey ${keyId}:${keySecret}"...

React + Django Axios Issues

I have a react application linked to a Django backend on two separate servers. I am using DRF for django and I allowed cors using django-cors-headers. For some reason when I curl POST the backend, I am able to get the request out. However when I use axios POST the backend, I get and error. The status of the POST request from axios is failed. The request and takes more than 10 seconds to complete. My code was working locally (both react and django codes), but when I deployed to AWS ec2 ubuntu, the axios requests stopped working.
Console error logs
OPTIONS http://10.0.3.98:8000/token-auth/ net::ERR_CONNECTION_TIMED_OUT
{
"config": {
"transformRequest": {},
"transformResponse": {},
"timeout": 0,
"xsrfCookieName": "XSRF-TOKEN",
"xsrfHeaderName": "X-XSRF-TOKEN",
"maxContentLength": -1,
"headers": {
"Accept": "application/json, text/plain, */*",
"Content-Type": "application/json;charset=UTF-8",
"Access-Control-Allow-Origin": "*"
},
"method": "post",
"url": "http://10.0.3.98:8000/token-auth/",
"data": "{\"username\":\"testaccount\",\"password\":\"testpassword\"}"
},
"request": {}
}
Here is my request code
axios.post('http://10.0.3.98:8000/token-auth/',
JSON.stringify(data),
{
mode: 'no-cors',
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin' : '*'
},
},
).then( res => (
console.log(JSON.stringify(res)),
)
).catch( err => (
console.log(JSON.stringify(err))
)
);
my curl code that worked
curl -d '{"username":"testaccount", "password":"testpassword"}' -H "Content-Type: application/json" -X POST http://10.0.3.98:8000/token-auth/
UPDATE 1
on firefox i am getting the warning
Cross-Origin Request Blocked: The Same Origin Policy disallows reading
the remote resource at http://10.0.3.98:8000/token-auth/. (Reason:
CORS request did not succeed).[Learn More]
UPDATE 2
Perhaps it has something to do with my AWS VPC and subnets? My django server is in a private subnet while my react app is in a public subnet.
UPDATE 3 - my idea of what the problem is
I think the reason why my requests from axios aren't working is because the requests i'm making is setting the origin of the request header to http://18.207.204.70:3000 - the public/external ip address - instead of the private/internal ip address which is http://10.0.2.219:3000 - i search online that the origin is a forbidden field so it can't be changed. How can i set the origin then? Do I have to use a proxy - how can I do that.
try this http request instead of axios, it's called superagent (https://www.npmjs.com/package/superagent) , just install it to your react app via npm,
npm i superagent
and use this instead of axios.
import request from 'superagent'
const payload ={
"1": this.state.number,
"2": this.state.message
}
request.post('LINK HERE')
.set('Content-Type', 'application/x-www-form-urlencoded')
.send(payload)
.end(function(err, res){
if (res.text==='success'){
this.setState({
msgAlert: 'Message Sent!',
})
}
else{
console.log('message failed/error')
}
});
The issue here is that the request is being made on the client browser. You need to either use a reverse proxy or request directly to the api server. You cannot do a local ssh forwarding either.

Serverless AWS Lambda CORS Error

I am trying to do an http request from an angularjs app to a lambda function that I had setup using serverless.
Here is my serverless.yaml function
functions:
createcustomer:
handler: handler.createcustomer
events:
- http: post /createcustomer
cors: true
Create Customer Function
module.exports.createcustomer = (event, context, callback) => {
let customer = JSON.parse(event.body).customer;
service.create(customer, function(result) {
let response = {
statusCode: 200,
headers: {
"Access-Control-Allow-Credentials": true,
"Access-Control-Allow-Origin": "*",
"Content-Type": "application/json",
},
body: JSON.stringify({
result: 'Created Customer Successfully',
message: 'The account has been created!',
type: 'success',
customer: result
})
};
callback(null, response);
});
};
From my AngularJS app I call it like this
app.factory('MyFactory', ['$http', function($http) {
return {
CreateCustomer: function(customer) {$http.post('<apipath>/createcustomer', {customer:customer})}
}
}]);
However, I keep getting this error:
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:5000' is therefore not allowed access. The response had HTTP status code 403.
I have tried to enable CORS in the API Gateway on the POST method, but that did not change the outcome.
I've also tried setting CORS in the yaml file explicitly
functions:
createcustomer:
handler: handler.createcustomer
events:
- http: post /createcustomer
cors:
origin: '*'
Still no luck.
Does anyone know what I'm doing wrong here?
One weird thing is that I could get the post to work just fine through PostMan, but if I try it through my app it breaks.
Thanks
UPDATE
When I do serverless deploy it shows up in AWS like the picture above and the method looks like this
As I said before, I tried to enable CORS directly from the API Gateway console but there was no difference when I tried to call the method.
Your update with screenshots shows that the OPTIONS method is not set up for any of these resources. When you enable CORS for an API Gateway resource in the console, AWS sets this up automatically.
You can see this happen in the AWS console when you enable CORS for a resource, but, of course, your serverless deploy is overwriting this configuration.
To have the /createcustomer resource properly configured in AWS by the serverless deploy, you can rewrite this part of your serverless.yaml:
events:
- http: post /createcustomer
cors: true
To look like this:
events:
- http:
path: /createcustomer
method: post
cors: true
I'm not an expert in the framework's .yml syntax, so I can't explain exactly why this is.
Nonetheless, I've confirmed that a file like this:
functions:
deletecustomer:
handler: handler.deletecustomer
events:
- http:
path: /deletecustomer
method: post
cors: true
createcustomer:
handler: handler.createcustomer
events:
- http: post /createcustomer
cors: true
will create two resources in AWS API Gateway, one correctly configured for CORS, and one missing the OPTIONS method:
Here is the configuration that could help. Please note that it's always safe to be specific in allowing the CORS origins. So better to lock the origin down to localhost:{port-number}. In addition, you can also enable credentials on CORS settings. Please see the following serverless config as an example:
cors:
origin: 'http://localhost:4200'
headers:
- Content-Type
- X-Amz-Date
- Authorization
- X-Api-Key
- X-Amz-Security-Token
- X-Amz-User-Agent
allowCredentials: true
The cors configuration got moved up into the provider config:
provider:
httpApi:
cors: true