How to fix 403 Forbidden from Ajax Call while using datatables - datatables

Working with DataTables. Getting a 403 Forbidden error. Please Help
Working based on https://datatables.net/examples/data_sources/server_side.html
$(document).ready(function() {
$('#example').DataTable( {
"processing": true,
"serverSide": true,
"ajax": "response1.php",
"columns": [
{ "data": "empid" },
{ "data": "empname" },
{ "data": "salary" }]
} );
} );
When calling response1.php - I get the required output in correct format, but when i include the call in ready from another page . I get DataTables warning: table id=example - Ajax error. For more information about this error, please see http://datatables.net/tn/7.
On debugging i get 403 from the browser. Please help. response1.php in in the same directory

When you use spring boot with spring security and if you are accessing your API's(POST, PUT, DELETE) from Postman or something, they wont be accessible and error is related to authorization like forbidden 403.
One solution is disabling csrf but this makes application less secure, best thing to do is send csrf token.
To know if this is your problem you can create this class in order to disable the csrf:
#Configuration
#EnableWebSecurity
public class AppWebSecurityConfigurer extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.anyRequest().permitAll();
}
}
Then you can learn to send de csrf in the ajax request reading this other question: Adding CSRFToken to Ajax request
You can get more information about this problem at https://newbedev.com/403-forbidden-when-i-try-to-post-to-my-spring-api

Related

Strapi API register returning a 400 error

I’ve been creating a web app with a login and a registration function and so far everything has been going great. I managed to connect the app to the api/auth/local api endpoint and send some nice post requests.
Now, I’ve been trying to send requests to the http://localhost:1337/api/auth/local/register endpoint and without any success. I’ve been doing this according to:
https://docs.strapi.io/developer-docs/latest/plugins/users-permissions.html#registration
I keep getting a 400 error:
{
"data": null,
"error": {
"status": 400,
"name": "ApplicationError",
"message": "An error occurred during account creation",
"details": {
}
}
}
If I try to send a request with an email that’s already registered in strapi, the response will give me the correct error:
{
"data": null,
"error": {
"status": 400,
"name": "ApplicationError",
"message": "Email is already taken",
"details": {
}
}
}
In the public and authenticated user roles, I’ve allowed every single one of them, for now.
Enable confirmation emails are set to false.
Email confirmation
Public user permission
For the headers, I’m using Content-type : application/json
the raw json body I'm posting:
{
"email": "manager1#strapi.io",
"password": "testtest1",
"username": "manager1"
}
This is my first project with strapi and so far it went pretty well. I’m not sure if I’m missing out on something or if I’m doing something else wrong.
Any help is appreciated!
I figured it out, it wasn’t as complicated as I expected.
In the user I had different fields, like firstName, lastName etc. All of these fields were required.
I made the fields not required, and now it works.

NUXT Redirect issue when making a POST request to external API

I have a form that I built in Nuxt. I'm trying to submit it to an external API. The expected response is a JWT token.
async login() {
const res = await this.$axios.$post(`/api/token`, {
username: this.username,
password: this.password
}, this.headers )
console.log(res)
}
Trying to call the API directly gets me a CORS error, so I use proxy settings in my nuxt.confix.js.
...
modules: [
'#nuxtjs/axios',
'#nuxtjs/proxy'
],
axios: {
baseURL: '/',
proxy: true
},
proxy: {
'/api/': { target: 'https://<apiurl>.com/', changeOrigin: true }
},
...
Now when I check the network tab, it shows a 301 redirect, but the data that was sent in the post request gets thrown away, and it makes a get request to the API which returns a 405 error (because it's expecting a POST request with a data and not an empty GET request).
How can I make a POST request to an external API using NUXT? Is this an option at all?
I tried changing changeOrigin: false, and that seems to get rid of the issue, but it throws a 500 server error instead and an npm error that says
ERROR [HPM] Error occurred while proxying request localhost:3000/api/token to https://<apiurl>.com/ [ERR_TLS_CERT_ALTNAME_INVALID] (https://nodejs.org/api/errors.html#errors_common_system_errors)
Thank you
The problem is not how to send api to an external API ... the problem is in the external API it self ... make sure the external API has no credentials required to make any action ...
if you can make a request to https://jsonplaceholder.typicode.com/posts and get results that means there is no problems in your code ... cors erros in most cases are backend issue ... which means .. the backend developer who worked on it should fix it

Getting Forbidden 403 error while creating OnlineMeeting using Microsoft Graph api

I am trying to create online meeting through https://graph.microsoft.com/beta/communications/onlineMeetings .
initially i got the 403 Forbidden error. then i give the Delegated and Application permissions(OnlineMeetings.ReadWrite,OnlineMeetings.ReadWrite.All) on my registered app on azure.then 403 error is gone and i got new error 400 bad request(Organizer.Identity.User.Id missing).
then i supply Online meeting post request as follows-:
{
"startDateTime":"2020-04-20T14:33:30.8546353-07:00",
"endDateTime":"2020-04-20T15:03:30.8566356-07:00",
"subject":"Application Token Meeting",
"participants": {
"organizer": {
"identity": {
"user": {
"id": "cb6d6636-1c9e-457c-b904-5da8265a8927"
}
}
}
}
}
again i got 403 Forbidden error.
i created user with the help of https://graph.microsoft.com/v1.0/users and https://graph.microsoft.com/beta/invitations.
user is created in my app on azure and i give the permission (User.ReadWrite.All, Directory.ReadWrite.All, Directory.AccessAsUser.All,User.ReadWrite.All, Directory.ReadWrite.All)
but error(403) did not change.
My question is that how to give user authorization in microsoft graph API.
The required permission is Delegated Permission: OnlineMeetings.ReadWrite. See reference here.
403 error means your access token doesn't include the required permission. You can add it like this:
Don't forget to click on "Grant admin consent for {your tenant}".
You should implement Get access on behalf of a user and get an access token to call /communications/onlineMeetings endpoint.
The http sample for your reference:
POST https://graph.microsoft.com/beta/communications/onlineMeetings
Content-Type: application/json
Authorization: Bearer {access token}
{
"startDateTime":"2019-09-09T14:33:30.8546353-07:00",
"endDateTime":"2019-09-09T15:03:30.8566356-07:00",
"subject":"Application Token Meeting",
"participants": {
"organizer": {
"identity": {
"user": {
"id": "550fae72-d251-43ec-868c-373732c2704f"
}
}
}
}
}
You can learn more details about Use the access token to call Microsoft Graph. Don't forget to put Authorization: Bearer {access token} in the request headers.

Ionic V3 Request randomly fail in Chrome Browser and Emulator

I have a weird problem with Http-Requests randomly failing with an Ionic(V3) App using the Http-Client from Angular (7.1.1).
The Backend is an ASP.NET Core Web API with CORS configured to allow any Headers, Methods and Origins.
To figure out the problem I switched from Emulator to Browser. After resolving some CORS Issues I noticed that the problem with failing requests only exists in Chrome (FF and Edge are working fine).
The HTTP Requests fail with: "ERR_INVALID_HTTP_RESPONSE", after clicking back and forth the network tab looks like this:
I can't explain why some Requests don't have the Preflight request, but those requests seem to always succeed (they also have den header "Accept: application/json, text/plain, /" which should alway trigger the Options-Preflight, if I am correct?)
Also every requests, even the failing ones, reach the backend and resolve successfully on the backend.
The error on the client in the console:
{
"headers": {
"normalizedNames": {},
"lazyUpdate": null,
"headers": {}
},
"status": 0,
"statusText": "Unknown Error",
"url": null,
"ok": false,
"name": "HttpErrorResponse",
"message": "Http failure response for (unknown url): 0 Unknown Error",
"error": {
"isTrusted": true
}
}
Reading the Ionic forums this leads to a CORS problem. Perhaps I overlooked something, so here is my CORS-Configuration from the Backend:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseCors(builder =>
{
builder.WithOrigins("*")
.WithMethods("*")
.WithHeaders("*");
});
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseMvc();
}
Any hint is really appreciated.
If your Web API project is on aspnet core 2.2 then it could be related to this issue:
Response that returns 204 fails with HTTP_1_1_REQUIRED/INVALID_HTTP_RESPONSE in ANCM In-process
There is three options:
Downgrade to aspnetcore 2.1
Upgrade to 2.2.1 / 3.0.0 preview
Use the work around mentioned on the issue:
Add the following as the first lines of your StartUp.cs Configure method.
app.Use(async (ctx, next) =>
{
await next();
if (ctx.Response.StatusCode == 204)
{
ctx.Response.ContentLength = 0;
}
});
Also about the preflight not firing everytime, the browser cache includes the results of preflight OPTIONS calls so instead of having to fire a preflight on every request, it only fires once the cache has expired.
Lastly: configuring CORS with an accept of any origin can be unsafe, see:CORS security: reflecting any origin header value when configured to * is dangerous

GCM Unauthorized Error 401

I'm not able to get response from GCM even i'm providing correct server API key generated by google.
Problem : I want to make a push notification using GCM from my sails app.
I'm posting below code to "https://android.googleapis.com/gcm/send"
Code : 1
{
"headers":{
"Content-Type":"application/json",
"Authorization":"key=xxxxxxxxxxxxxxxxxxxx"
},
"notification":{
"title":"Hello Notify",
"text":"Notification By Sails"
},
"registration_ids":["xxxxxxxxxxxx","xxxxxxxxxxxx","xxxxxxxxxxxx"]
}
Code : 2
{
"headers":{
"Content-Type":"application/json",
"Authorization":"key=xxxxxxxxxxxxxxxxxxxx"
},
"body":{
"notification":{
"title":"Hello Notify",
"text":"Notification By Sails"
}
},
"registration_ids":["xxxxxxxxxxxx","xxxxxxxxxxxx","xxxxxxxxxxxx"]
}
I'm getting response as below.
"statusCode": 401,
"body": "<HTML>\n
<HEAD>\n<TITLE>Unauthorized</TITLE>\n</HEAD>\n
<BODY BGCOLOR=\"#FFFFFF\" TEXT=\"#000000\">\n
<H1>Unauthorized</H1>\n
<H2>Error 401</H2>\n
</BODY>\n
</HTML>\n",
The headers should be HTTP headers, not element in the payload.
Make sure you have enabled the right API in Cloud Console. If sending with a Server API key, you need to have "Google Cloud Messaging for Android" enabled.