Django CORS request external redirect not allowed - reactjs

I faced a problem during send GET request to a django view from react, and those view redirect to GOOGLE_AUTH_ENDPOINT., and this url hit a callback function. But after request from react, it give this error:
Access to fetch at "google auth url" (redirected from 'localhost:8000') from origin '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. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
view
class Glogin(APIView):
params = {
'client_id': CLIENT_ID,
'response_type': 'code',
'scope': 'openid email profile',
'redirect_uri': CALLBACK_DOMAIN,
'state': state,
}
if APPS_DOMAIN:
params['hd'] = APPS_DOMAIN
def get(self,request):
request.session['googleauth_csrf'] = state
request.session['next'] = request.META.get('HTTP_REFERER', None)
print('Here')
print(urlencode(self.params))
return HttpResponseRedirect("%s?%s" % (GOOGLE_AUTH_ENDPOINT, urlencode(self.params)))
#data = {'link':GOOGLE_AUTH_ENDPOINT, 'params':self.params}
#return Response(data)
ReactJs
static GLogIn() {
return fetch("http://127.0.0.1:8000/glogin/", {
//method: "POST",
method: "GET",
headers: {
"Content-Type": "application/json",
},
//body: JSON.stringify(body),
}).then((response) => response.json());
}
URL
urlpatterns = [
path('', include(router.urls)),
path('auth/', obtain_auth_token),
path('login/',views.LogInViewSet.as_view()),
path('logout/',views.LogOutViewSet.as_view()),
path('articles/',views.ArticlesView.as_view()),
path('articles/<int:pk>/',views.ArticlesView.as_view()),
path('glogin/',views.Glogin.as_view()),
path('callback/',views.Callback.as_view(), name='googleauth_callback'),
#path('articales/',views.ArticlesViewSet.as_view())
]
settings.py
CORS_ORIGIN_WHITELIST = (
'localhost:3000',
#'accounts.google.com',
#'accounts.google.com/o/oauth2/v2'
)
CORS_ALLOW_HEADERS = [
'accept',
'accept-encoding',
'authorization',
'content-type',
'dnt',
'origin',
'user-agent',
'x-csrftoken',
'x-requested-with',
]

Put a hosts entry in the /etc/hosts file for 127.0.0.1
127.0.0.1 myfakedomain.local
Then add this to the CORS_ORIGIN_WHITELIST
'myfakedomain.local:8000',
Then you can access cors redirects. Chrome blocks them unless they are on special domains. Especially localhost.
Then send your browser to http://myfakedomain.local:8000

Related

Problem with cors between backend and frontend

I have a problem with my cors policy between my backend (API Rest in .NET Core 6) and my frontend (in ReactJS), the thing is that in my backend I have the following configuration:
In appsetings.json:
"AllowedHosts": "mywebsite.com"
In Program.cs:
services.AddCors(options =>
{
options.AddPolicy(name: "mycors", builder =>
{
builder.WithOrigins("mywebsite.com")
.AllowAnyHeader()
.AllowAnyMethod();
});
});
app.UseCors("mycors");
This configuration doesn't work when I'm trying to fetch a post request to my API, but if I change the AllowedHosts to "AllowedHosts": "*" it works. I don't understand why I can't allow just to my frontend website.
Additional information, my post request has these parameters:
method: 'POST'
mode: 'cors',
cache: 'no-cache',
credentials: 'same-origin',
redirect: 'follow',
referrerPolicy: 'no-referrer',
headers: { 'Content-Type': 'application/json' },
body: //My parameters
The console error is:
Access to fetch at 'mybackendpostmethod' from origin 'myfronturl.com' 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.
I solved putting my api that return as follows

Access to fetch at 'http://127.0.0.1:8000/blog/1' from origin 'http://localhost:3000' has been blocked by CORS policy

I'm trying to fetch some data from the Django Rest API. But browser throw cors policy error.
let headersList = {Accept: '*/*'}
fetch(url, {
method: 'GET',
headers: headersList,
})
.then(function (response) {
return response.json()
})
.then(function (data) {
console.log(data)
})
Access to fetch at 'http://127.0.0.1:8000/blog/1' 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.
I also include cors-header in django api.
CORS_ALLOW_ALL_ORIGINS = True
CORS_ALLOW_CREDENTIALS = True

'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource

I am working on project using Django and React using Rest Framework. I have set CORS_ALLOW_ALL_ORIGINS=True in settings.py still i am getting error Access to XMLHttpRequest at 'http://127.0.0.1:8000/api/encrypt/' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I am using axios to post and get request. Suprisingly even after error post request is made but get request fails.
This is react file using axios
sendImage =()=> {
this.activateSpinner()
let formData = new FormData()
formData.append('to_be_hidden', this.state.files[0], this.state.files[0].name)
formData.append('used_to_hide', this.state.files[1], this.state.files[1].name)
axios.post('http://127.0.0.1:8000/api/encrypt/', formData, {
headers: {
'accept': 'application/json',
'content-type': 'multipart/form-data'
}
})
.then(resp=>{
this.getImageClass(resp)
console.log(resp.data.id)
})
.catch(err=>{
console.log("Code broke at send image")
console.log(err)
})
}
getImageClass =(obj)=> {
axios.get(`http://127.0.0.1:8000/api/encrypt/${obj.data.id}/`, {
headers: {
'accept': 'application/json',
}
})
.then(resp=>{
this.setState({recentImage:resp})
console.log(resp)
})
.catch(err=>{
console.log("Code broke at get image")
console.log(err)
})
this.deactivateSpinner()
}
ALLOWED_HOSTS=['*']
INSTALLED_APPS = [
'django.contrib.admin',
...
'corsheaders',
]
MIDDLEWARE = [
"django.middleware.security.SecurityMiddleware",
....
"corsheaders.middleware.CorsMiddleware",
]
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True
CORS_ALLOW_METHODS = [
"DELETE",
"GET",
"OPTIONS",
"PATCH",
"POST",
"PUT",
]
CORS_ALLOW_HEADERS = [
"accept",
"accept-encoding",
"authorization",
"content-type",
"dnt",
"origin",
"user-agent",
"x-csrftoken",
"x-requested-with",
]
It's definitely the issue from the backend side, I mean Django.
CORS_ALLOW_ALL_ORIGINS=True Once you set the CORS_ALLOW_ALL_ORIGINS value, you also need to set the values for ALLOWED_HOSTS.
For instance
ALLOWED_HOSTS=['*']
Please take a look at the below links.
https://pypi.org/project/django-cors-headers/
https://dzone.com/articles/how-to-fix-django-cors-error

CORS: Response to preflight request doesn't pass access control check ( axios )

I'm building a SPA with Reactjs and laravel as API. I use axios to make API calls, some requests work without any issue, however on some pages when I make a request i'll receive a error that the the request is blocked by the CORS policy.
In laravel i'm using the spatie/laravel-cors package to add CORS headers so the preflight requests won't get blocked, by default it will allow any type of request from any origin.
Request:
componentDidMount() {
const url = BACKEND_URL+API+'/XXX/';
let headers = {
"Authorization": "Bearer " + token,
"Content-Type": "application/json",
"Accept": "application/json",
}
axios({
url: url,
method: "GET",
headers: headers,
credentials: 'same-origin',
})
.then(response => {
const data = response.data.data;
this.setState({
data: data,
loading: false
})
})
.catch(error => {
console.log(error);
});
}
Expected response ( from localhost )
{
campaign_id: XXX
category: []
form_entry: {id: XXX, form_id: XXX, lead_id: XXX, fields: Array(1)}
form_entry_id: XXX
id: XXX
landing__page_id: XXX
last_contacted: "XXX"
name: "XXX"
notes: XXX
status: [{…}]
tag: []
}
Error message:
Access to XMLHttpRequest at 'XXX.XXX' from origin 'XXX.XXX' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.
from localhost everything works fine with the same setup, the strange thing is that i'm only getting the errors once I put both front and backend online.
Anyone has a clue why this is happening?

After preflight (cors) request server change origin to * and chrome not display request (but i look response body). How to solve a problem?

After preflight (cors) request server change origin to * and chrome not display request (but i look response body).
Request headers
Chrome's error:
Access to fetch at 'http://localhost:6529/graphql' from origin 'http://localhost:3000' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.
I use express, cors, graphql, apollo on backend and react on frontend.
Cors configuration (backend):
app.use(cors({
origin: 'http://localhost:3000',
credentials: true,
maxAge: 86400,
optionsSuccessStatus: 200,
methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'].join(','),
}));
Headers configuration (frontend)
const credentials = "include";
let client: ApolloClient<NormalizedCacheObject> | null = null;
export function createClient(cookie: any, ctx: any, store: any): ApolloClient<NormalizedCacheObject> {
storage.setItem("ctx", ctx);
client = new ApolloClient({
cache,
link: ApolloLink.from([
onError(({graphQLErrors, networkError}) => {
if (graphQLErrors) {
if (!SERVER) {
const redirectUrl = getRedirect(graphQLErrors);
if (redirectUrl) {
location.assign(redirectUrl);
}
}
graphQLErrors.map(({message, locations, path}) => {
console.log(
`[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`,
);
});
}
if (networkError) {
console.log(`[Network error]: ${networkError}`);
}
}),
new ReduxLink(store),
new BatchHttpLink({
credentials,
uri: GRAPHQL,
headers: cookie,
fetchOptions: {
withCredentials: true,
credentials,
},
}),
],
),
ssrMode: SERVER,
connectToDevTools: true,
});
return client;
}
How to solve a problem?
I just went through the problem myself and it was a nightmare. The reason it is not working is that the CORS header must have a . in it. http://localhost:3000 doesn't meet that qualification.
I solved this issue by going into my host's file (on a Mac: /etc/hosts) and redirecting a dummy domain such as api.myapp.local to 127.0.0.1 (localhost). Then I redirected my frontend to app.myapp.local. So now when the CORS request is made it is from http://app.myapp.local:3000 to http://api.myapp.local:3001 and it meets that requirement. You can call the domain whatever you would like.

Resources