I have already configured Keycloak role based access control with my java API project and it is deployed with Wildfly and runs without any errors. Since I have tested and confirmed the responses with Postman, I needed to use Swagger in-order to generate API documensts.
Using Swagger Inspector I created an API definition and exported that via SwaggerHUB to use it in SwaggerUI which I run locally. With web-origins and all the necessary steps configured in Keycloak and with authentication parameters set in Swagger script, I get the below error..
"
Access to fetch at (api request) from origin (swagger ui path) has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.
"
I have noticed that if I bypass Keycloak, this works. What might be the best solution to overcome this issue?
I was able to resolve my issue referring this answer. I too added "enable-cors": true in keycloak.json in my Java back-end server which was Wildfly and tested the same implementation in server environment successfully.
So I have an API in swagger that works properly. However, I want to disable it automatically following 302 redirect as I need the query params on the Location header of a 302. Is there any way how to do it in Swagger / Open API 3?
Swagger UI and Swagger Editor always follow redirects. To see 3xx responses, test the requests using non-browser tools such as curl. You can copy curl commands from Swagger UI.
curl https://httpbin.org/status/302 -i
I was going through different solutions available for preventing clickjacking in a grails application. One of the solutions was using X-Frame. So, I found a grails plugin, X-Frame-Options Plugin, by mrhaki.
It is serving my purpose of adding a response header
X-Frame:DENY
to every response. Great!
I read there was a modern solution - Content-Security-Policy header. I'm unable to configure this for my Grails application. Could someone help?
The X-Frame-Options plugin is simple and inserts a servlet filter to add a header to requests. For your situation I'd recommend creating your own servlet filter to add the Content-Security-Policy headers.
You can see an example here of how to add a header:
https://github.com/mrhaki/grails-x-frame-options-plugin/blob/df230a9f01cd2e1c6ac4be6d9eac41fbcae48293/src/main/groovy/com/mrhaki/grails/plugin/xframeoptions/web/XFrameOptionsFilter.groovy#L69
Another option would be to use your web server infront of your app (apache httpd or nginx) to add the headers.
I've just pulled down the latest Swagger from the Git repo (3.0.19) using: https://github.com/swagger-api/swagger-ui.git and updated my API to use the new version.
Ran git describe --tags to confirm and my version is currently: v3.0.19-6-gaab1403
The problem I'm having is one described here, whereby my response is a 403 (I can see this in the inspector on the browser) and although I have a reponse for error 403, I still get the TypeError: Failed to fetch message.
Here's a snippet from my definition regarding the 403 response:
"403": {
"description": "Forbidden",
"headers": {
"Access-Control-Allow-Origin": {
"type": "string"
}
}
},
I've also noticed it reported here however, I know it's not a CORS issue as I have tested the endpoints and the OPTIONS are returning correct, as are the endpoints if called with valid information (I force this 403).
Could anyone point me in the right direction please?
Update: I have since tested on a 401 response, with the same response.
And that a 400 is working as expected:
For anyone that runs into this problem;
After a day of troubleshooting and the Swagger support guys pointing me in the right direction, it turns out that this is currently caused by a bug within the AWS API Gateway custom authorizers.
We are currently using AWS API Gateway for managing our APIs, this includes managing all our authorization via a custom authorizer. The issue is that custom authorizers do not currently support passing through headers within the response and Swagger UI needs the Access-Control-Allow-Origin:* within the response header(s) to display the correct HTTP status code.
See this AWS thread regarding the issue (which is older than a year already):
https://forums.aws.amazon.com/thread.jspa?messageID=728839
Swagger UI discussion on same: https://github.com/swagger-api/swagger-ui/issues/3403
EDIT / UPDATE
This has since been resolved with the use of Gateway Responses. See this same forum (page 2):
https://forums.aws.amazon.com/thread.jspa?messageID=728839
I hit this error during local development (i.e., had nothing to do with AWS). The underlying cause (CORS violation) is identical. The following might help others who encounter this problem.
I setup connexion with an openapi spec that referred to http://localhost:9090/. When the development server starts, it says "Running on http://0.0.0.0:9090/". That page appears to work, but the swagger ui uses http://localhost:9090/ from the openapi spec for subsequent requests and shows TypeError: Failed to fetch in results. The browser console shows Access to fetch at 'http://localhost:9090/vr/variation' from origin 'http://0.0.0.0:9090'. The provided curl command worked fine; although initially confusing, the curl success is a clue that the problem is due to browser blocking rather than server-side failure.
(Connexion is based on Python flask and provides extended support for openapi integration.)
I had the same issue and there was a very simple fix. I accessed my site using HTTP but it required HTTPS. My site was redirecting to HTTPS when calling an endpoint.
This violated the "same-origin policy":
https://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-2.2
Disclaimer:- This answer is for APIs developed using Asp.net Core
I have faced similar issue when trying to access the APIs from the Swagger UI Editor.
I was trying to access some APIs developed using Asp.net Core where as the Swagger UI Editor was hosted on Apache. I was facing CORS (Cross Orgin Request).
I have to modify my APIs code to allow CORS request using following code:-
Declare within Startup.cs File having class "StartupShutdownHandler"
private readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
Added a section of code within ConfigureServices Method.
var str = ConfigurationHandler.GetSection<string>(StringConstants.AppSettingsKeys.CORSWhitelistedURL);
if (!string.IsNullOrEmpty(str))
{
services.AddCors(options =>
{
options.AddPolicy(MyAllowSpecificOrigins,
builder =>
{
builder.WithOrigins(str);
});
});
}
Added a line of code within Configure Method.
app.UseCors(MyAllowSpecificOrigins);
Reference Enable Cross-Origin Requests (CORS) in ASP.NET Core
Because the problem of cross-origin means your website is hosted on either locally or with port 8000 or different port, and your swagger's port number is different, so this problem is genuine. We can fix it by giving permission.
Here is the node code:
app.use( (request, response, next) => {
response.header("Access-Control-Allow-Origin", "*");
response.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
We can solve by using CORS npm as well.
https://www.npmjs.com/package/cors
Please check the swaggerOptions provided to swagger jsdoc and check whether host and base name is correct. I have encountered the same issue before and got fixed the issue by correcting this. Hope this will also solve the problem.
Eg:
const options = {
swagger: "2.0",
swaggerDefinition: {
// options.swaggerDefinition could be also options.definition
info: {
title: "Customer API", // Title (required)
description: "Dummy Customer API for implementing swagger",
contact: {
name: "Stack Overflow"
},
version: "1.0.0" // Version (required)
},
host: "localhost:5000",
basePath: "/"
},
// Path to the API docs
apis: ["SwaggerImplementation/index.js"] // For complex api's pass something like apis: ["./routes/*.js"]
};
I have encountered the same error while trying to authenticate access OAuth2 secured Rest API set. API server deployed on VM and was connecting to it using IPSEC VPN. Actually username/password in HTTP header with basic authentication was sent using separate API other than /oauth/token, backend itself was calling http://localhost:8080/api/v0/oauth/token with client secret and returning back token to client. After changing localhost to server's actual local IP , problem disappeared.
This error is generic on swagger side and could be due to many possible reasons.
In my case, it was due to connection error. My swagger page was not responsive due to connection issue at my side. I had to refresh it once and worked for me.
If it's a .NET Core API, try commenting out the below method call in the StartUp.cs
Like below,
// app.UseHttpsRedirection();
It's because some times your IIS Binding's HTTPS SSL Certificate will automatically goes to Not Selected. So again you haveThere was a similar question raised and there are few good answers Please refer this link to manually selectget the SSL Certificates to1 IIS Express Development Certificate1. Below I have mention how to doanswer:
Open IIS Click Default web sites.
In the right side corner you will see a some setting click "Bindings", you will get a Site Binding window.
Then you will get http and https details.
In that Click "https" and click edit, then you will get another window Edit Site Bindings.
In that window check SSL Certificates.
If SSL Certificate = Not Selected select IIS Express Development Certificate.
Then stop and Start the IIS.
Issue will be solved.
Below article might help.
I was facing same issue when from Swagger ui calling API Gateway which further calls Lambda function using proxy integration (which passes response headers from lambda). In my case I missed to set response headers Access-Control-Allow-Origin in Spring boot app lambda handler response-event object APIGatewayProxyResponseEvent. After setting this header in handler class, Swagger UI was able to call api gateway. See
https://fanchenbao.medium.com/thanks-for-the-article-it-is-a-great-way-to-get-started-with-deploying-swagger-ui-on-s3-7990c7b48851
you can use modheader extension in order to fix it
For .NET Core 2.1 or above
In Startup or Program, register configuration to IApplicationBuilder to
app.UseCors("AllowAll");
Every solution will definitely be correct :)
But in my case I have that line in my webconfig file
<environmentVariable name="ASPNETCORE_HTTPS_PORT" value="5001" />
I just replace ASPNETCORE_HTTPS_PORT to ASPNETCORE_HTTP_PORT and the error has been gone :). So the final line is
<environmentVariable name="ASPNETCORE_HTTP_PORT" value="5001" />
replace 5001 with your port.
I have a Rails app, hosted on Heroku. During deployment assets are synced with an Amazon S3 bucket via the asset_sync gem and views call those assets through CloudFront. However, fonts are not rendered when viewing the website with Firefox (files are loaded in the Net tab of Firebug, but simply not used). Safari works great.
I have the following CORS config on S3:
<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
<AllowedOrigin>*</AllowedOrigin>
<AllowedMethod>GET</AllowedMethod>
<MaxAgeSeconds>3000</MaxAgeSeconds>
<AllowedHeader>Content-*</AllowedHeader>
<AllowedHeader>Host</AllowedHeader>
</CORSRule>
</CORSConfiguration>
My app also sets the following headers:
Access-Control-Allow-Origin: *
Access-Control-Request-Method: *
But CloudFront returns fonts without them... Why aren`t fonts loaded?
Thanks in advance.
Some versions of Internet Explorer and Firefox consider fonts an attack vector and will refuse loading them if they are being provided by another domain (cross domain policy).
On standard HTTP servers all you need to do is add the Access-Control-Allow-Origin: * header to bypass the CORS policy. The problem is S3 doesn’t support sending it. (Though according to the specification it should support CORS, the header is not sent).
There is a workaround. CloudFront can be pointed at another server that can send the Access-Control-Allow-Origin header (You can do that with the server that serves your app ;) ).
This can be done by adding a Custom Origin to your CloudFront distribution from the AWS Console. Next you will have to add Behaviours with your font types and the newly added Origin. You can use wildcards for the filename. (You’ll need to do this once for each font type that you have).
Example:
Path Pattern: /assets/*.woff
When ready you can validate the header existence with:
curl -I http://cloudfrontid.cloudfront.new/assets/font.woff
Hopefully you will see the Access-Control-Allow-Origin header, provided by your server along with the file itself, cached by CloudFront with the header included.
Hope it helps!
Try invalidating your (cached) font files in Cloudfront: http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Invalidation.html#invalidating-objects-console
I had a similar issue today. I read an article that suggested CORS configurations are cached in CloudFront. I resolved my issue by invalidating my font files.
On June 26, 2014 AWS added support for CORS in CloudFront, so now you can make this work with just CloudFront and S3.
This SO answer provides info about enabling CORS support for a particular CloudFront distribution:
https://stackoverflow.com/a/24459590/3195497
In addition you will need to enable CORS on your S3 bucket. One of the answers here says in regard to S3:
Though according to the specification it should support CORS, the
header is not sent
From my testing this is only partially true. If the Origin header is sent in the request then S3 will correctly send the Access-Control-Allow-Origin header. If the Origin header is not sent then S3 will not send the Access-Control-Allow-Origin header.
In the past this has caused problems with CloudFront. If you made any requests to CloudFront without an Origin request header then CloudFront will cache a response without the Access-Control-Allow-Origin response header. This might happen because you are testing the asset with a curl command and you don't include the Origin request header. Now when you make a request to CloudFront with the Origin header, CloudFront would ignore the Origin header and serve the cached response without the Access-Control-Allow-Origin header.
With the changes recently released to CloudFront, you can configure your distribution to take the Origin request header into account. In this case CloudFront will cache different responses, one response for each value of the Origin header.
This is what my CORS config looks like. I have a different AllowedHeader than you. I don't use asset_sync.
<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
<AllowedOrigin>*</AllowedOrigin>
<AllowedMethod>GET</AllowedMethod>
<MaxAgeSeconds>3000</MaxAgeSeconds>
<AllowedHeader>Authorization</AllowedHeader>
</CORSRule>
</CORSConfiguration>