Redirect from React ASP.NET application to SSO login page blocked by CORS Policy - reactjs

My application is set up as of follows:
Frontend is React (SPA),
Backend is ASP.NET Core 6, and
User will be authenticated via SSO using SAML2 protocol (the SAML code is implemented on the ASP.NET side, not React)
When the React page is loaded, it will send a POST request via fetch API to the ASP.NET server which then will trigger to load the SSO page (I'm actually confused by this as I'm unsure how this would work with React since React handles all the routing piece here). However, I keep getting an error that is saying:
"Access to fetch at 'https://sso.example.com/saml/idp/profile/redirectorpost/sso?SAMLRequest=xxxx&RelayState=ReturnUrl%3D%252Fexample%252Fexampleapp%252FGetLoggedInUser' (redirected from 'https://forms.test.com/test/testapp/GetLoggedInUser') from origin 'https://forms.test.com' 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 attempted to fix this by changing the attributes in the fetch headers by all resulted in the same CORS error.
Here's my fetch api code on the frontend:
fetch("testapp/GetLoggedInUser", {
method: "POST",
headers: {
'Accept': 'application/json',
'Access-Control-Allow-Origin': '*',
},
body: data
}).then((response) => {
const contentType = response.headers.get("content-type");
if (contentType && contentType.indexOf("application/json") !== -1) {
return response.json().then((data) => {
return data;
}).catch((err) => {
console.log(err);
})
}
else {
return response.text().then((data) => {
return data;
}).catch((err) => {
console.log(err);
})
}
});
My backend (ASP.NET Core 6)
//[Authorize] is an attribute from Microsoft.AspNetCore.Authorization.AuthorizeAttribute
[Authorize]
[HttpPost("GetLoggedInUser")]
public string GetLoggedInUserData()
{
this.CheckSession();
Person Person = new ActiveUser(this.ID, GlobalVariables.ProcessCode);
dynamic P = Person.GetSimple();
User User = new User(this.WhitworthID);
P.LastAccess = DateTime.Now;
User.SetLastAccess();
return JsonConvert.SerializeObject(P);
}
Can anyone advise me on how to get past the CORS error when redirecting from React to the SSO page?

Modify your code to check if the response is redirected,if so redirect the browser to the new url.
fetch(url, { method: 'POST', redirect: 'manual'})
.then(response => {
// HTTP 301 response
// HOW CAN I FOLLOW THE HTTP REDIRECT RESPONSE?
if (response.redirected) {
window.location.href = response.url;
}
})
.catch(function(err) {
console.info(err + " url: " + url);
});

Related

How do i enable cors policy / or request in react js with no access to the API?

Im using RapidApi to make som simple calls for fetching country data using axios. The API is paged in that the next response will have the URL for the next request. So basically i don't even have the URLs.
Problem i get the error which i have seen all over stack overflow about cors policy
Access to XMLHttpRequest at 'https://api.hybridgfx.com/api/list-countries-states-cities?page=2' from origin 'http://localhost:3002' 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 tried adding the line "access-control-allow-origin": "*" but that doesn't work and i still get the same error. When i click on the URL or just run it directly on the browser i get a bunch of data but when it is called in the code it blows up . Please help.
const fetchNextResults = async (url: string): Promise<FetchResponse> => {
const options = {
method: "GET",
url: url,
headers: {
"X-RapidAPI-Key": MyKey,
"X-RapidAPI-Host": "countries-states-cities-dataset.p.rapidapi.com",
"access-control-allow-origin": "*",
},
};
const res: FetchResponse = await axios
.request(options)
.then(function (response) {
console.log(response.data);
return response.data;
})
.catch(function (error) {
console.error(error);
});
return res;
};
You can send a request throw the CORS proxy.
List of proxies.
url: <proxy url>/<my url>
Or create your own.

cakephp XMLHttpRequest post request csrf problem

cakephp 4.4.6
I use vuejs as frontend, all works fine, but I have csrf problems to send XMLHttpRequest with post request.
CsrfProtectionMiddleware is activated.
It works fine when post data are send from an html "form" (_csrfToken is in a hidden field).
But if post data are send from an axios request, cakephp backend cannot get the csrf token.
Here is the front code:
axios
.post("/equipes/delete", {
headers: {
"X-Requested-With": "XMLHttpRequest",
'X-CSRF-Token': this.csrftoken,
},
params: {
// csrfToken: this.csrftoken,
// _csrfToken: this.csrftoken,
id: id,
},
})
.then((response) => {
})
.catch((e) => {
console.log(this.$options.name + ": method confirmationDelete : error");
});
The parameters send to the cakephp backend:
And the error returned :
Any ideas ?
Thanks

How to fetch data from a REST API by using an API-Token

I'm trying to fetch data from the Jira Rest API in my React application by using the Axios library for http requests. An API token is necessary, in order to access data via the Jira API. I generated an API token in my Jira account settings, but I can't figure out, how to include it in my http request to gain access.
This is the endpoint provided by the Jira documentation for getting an issue from the Jira board:
curl -u admin:admin http://localhost:8080/jira/rest/api/2/issue/TEST-10 | python -mjson.tool
This is the React state hook for setting the data to the fetched data:
const [jiraTicket, setJiraTicket] = useState([]);
This is the fetch function for the API request (${} will be filled with user input):
function getJiraTicket() {
axios.get(`${username}:${apiToken}#Content-Type:application/json/https:/${jiraSiteName}.atlassian.net/rest/api/2/issue/${projectKey}-${ticketId}`)
.then((res) => {
const data = res.data;
setJiraTicket(data);
})
}
The button inside the react component return should invoke the fetch function:
return(
<Container>
<Button onClick{getJiraTicket()}>Fetch Jira Ticket</Button>
</Container>
);
This is the error I'm currently getting, because the authorization is not working the way I did it
(I replaced the provided username, API token etc. for this example):
GET http://localhost:3000/username:apitoken#https:/sitename.atlassian.net/rest/api/2/issue/projectkey-ticketid 404 (not found)
Edit:
My current approach:
function getJiraTicket() {
axios.get(`${userName}:${apiToken}#https://${siteName}.atlassian.net/rest/api/2/issue/${projectId}-${ticketId}`,{
auth: {
username: userName,
password: apiToken,
},
withCredentials: true
})
.then((res) => {
const data = res.data;
console.log(data);
setJiraTicket(data);
})
.catch(err => {
// This error means: The request was made and the server responded with a status code
if(err.res) {
console.log(err.res.data);
console.log(err.res.status);
console.log(err.res.headers);
console.log("request was made and server responded with status");
// The request was made but no response was received
} else if (err.request) {
console.log(err.request);
console.log("request was made, but no response was received");
// Something happened in setting up the request that triggered an error
} else {
console.log("Error", err.message);
console.log("request is note set up correctly");
}
console.log(err.config);
})
Current error, which I defined accordingly to the axios doc: "request was made, but no response was received"
Endpoint that works well in Postman (Basic auth is provided in Postman):
https://sitename.atlassian.net/rest/api/2/issue/projectid-ticketid
Update: CORS access isn't allowed, when an application tries to access the Jira API endpoints directly. This restriction takes place in order to prevent random authenticated requests to the specific Jira site, because the access is based on session based authentication. However the API endpoints can be accessed, if OAuth 2.0 is used instead of Basic auth, because the application will redirect the user to the Jira auth itself via this link:
https://auth.atlassian.com/authorize? audience=api.atlassian.com&
client_id=YOUR_CLIENT_ID&
scope=REQUESTED_SCOPE_ONE%20REQUESTED_SCOPE_TWO&
redirect_uri=https://YOUR_APP_CALLBACK_URL&
state=YOUR_USER_BOUND_VALUE& response_type=code& prompt=consent
Source: https://developer.atlassian.com/cloud/jira/platform/oauth-2-3lo-apps/#known-issues
Axios uses a headers config for get/post so you should not include them in your URL. Here is a general example of how you should construct the URL and apply headers:
let axiosUrl = `https://${jiraSiteName}.atlassian.net/rest/api/2/issue/${projectKey}-${ticketId}`
axios({
baseURL: axiosUrl,
method: 'get',
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Origin", "*"
},
//timeout: 2000,
auth: {
username: userName,
password: apiToken,
}
})
.then((res) => {
setJiraTicket(res.data);
})
.catch(function (error) {
console.log(error);
});

Facing issue with setting up http only cookie while using react js for frontend and django rest framework for backend

I started building a basic Authentication system with JWT token authentication using rest API and react js. But, I was facing an issue while setting my cookie from the Django views sent using rest_framework.response.Response object. Now, the problem is that in the Django server the cookie is set, but in this case, while integrated with react js it fails. Django server is running on port 8000 and react js on 3000.
#api_view(['POST'])
def login(request):
try:
username = request.data['username']
password = request.data['password']
user = authenticate(request=request, username=username, password=password)
if user:
refresh = RefreshToken.for_user(user)
response = Response()
response.data = {
"status": True,
"Access": str(refresh.access_token)
}
response.set_cookie(key='refreshtoken', value=(refresh), httponly=True, samesite=None)
return response
else:
return Response(FALSE_RESPONSE)
except Exception as e:
print(e)
return Response(FALSE_RESPONSE)
This is the axios request, I was making from the frontend side.
axios({
method: "POST",
url: "http://localhost:8000/user-api/login/",
data: {
username:username,
password:password
},
credentials: 'include',
withCredentials: true
})
.then(response => {
console.log(response)
if(response.data['status']) {
setAccessToken(response.data['Access'])
setIsAuthenticated(true)
setLoginModal(false)
} else {
alert("Error! Credentials doesn't match.")
}
})
.catch(error => {
console.log(error)
})
This axios request generates no errors and I was successfully getting the token, but the refresh token was not getting saved in the cookies.
# settings.py
CORS_ALLOWED_ORIGINS = [
"http://localhost:3000",
"http://127.0.0.1:3000"
]
CORS_ALLOW_CREDENTIALS = True
Help me with this issue!!

Angular $http post with custom headers

I am new to angular and am from .net framework. I need to post a angular request to .net service, where it expects two custom headers from the client.
angular post command:
var request = $http(
{
url: "http://localhost:53585/api/myService/Validate",
method: "POST",
data: JSON.stringify(payload),
headers: { 'first_token': sessionService.first_token, 'second_token': sessionService.second_token }
});
But in the service side, I can see only first_token in the request header and not the second token. What I am missing here?
Issue is with my service. I figured out and restarted the IIS and then service was able to read both the headers token
I found this method in a forum, it works.
return this.http.post<any>('https://yourendpoint', { username, password }, { headers: new HttpHeaders().set('Authorizaion', 'your token')})
.pipe(map(user => {
// login successful if there's a jwt token in the response
if (user && user.token) {
// sto`enter code here`re user details and jwt token in local storage to keep user logged in between page refreshes
localStorage.setItem('currentUser', JSON.stringify(user));
}
console.log(user);
return user;

Resources