Ajax ошибка 403

I’m making a query to a web service using jQuery AJAX. My query looks like this:

var serviceEndpoint = 'http://example.com/object/details?version=1.1';
$.ajax({
  type: 'GET', 
  url: serviceEndpoint,
  dataType: 'jsonp',
  contentType: 'jsonp',
  headers: { 'api-key':'myKey' },
  success: onSuccess,
  error: onFailure
});

When I execute this, I get a status error of 403. I do not understand why my call results in having the status code 403. I’m in control of the security on my service and it is marked as wide-open. I know the key is valid, because I’m using it in another call, which works. Here is the call that works:

var endpoint = 'http://example.com/object/data/item?version=1.1';
$.ajax({ 
  type: 'POST', 
  url: endpoint, 
  cache: 'false',
  contentType:'application/json',
  headers: {
    'api-key':'myKey',
    'Content-Type':'application/json'
  },
  data: JSON.stringify({
    id: 5,
    count:true
  }),
  success: onDataSuccess,
  error: onDataFailure
});

I know these are two different endpoints. But I’m 100% convinced this is not a server-side authentication or permission error. Once again, everything is wide open on the server-side. Which implies that I’m making some mistake on my client-side request.

I feel I should communicate that this request is being made during development. So, I’m running this from http://localhost:3000. For that reason, I immediately assumed it was a CORS issue. But everything looks correct. The fact that my POST request works, but my GET doesn’t has me absolutely frustrated. Am I missing something? What could it be?

The website initiates ajax request but always get return 403 error for all browsers.

I tested it by initiating the same call in firebug console, it works (status: 200)

What is the problem can be deduced?

jQuery.ajax({ 
    url: "cart_ajax_get_product.php", 
    data: {id: 355, qty: 1}, 
    success: function(data) { }); }, 
    error: function(err) { } 
});

Thanks

Musa's user avatar

Musa

96.4k17 gold badges119 silver badges138 bronze badges

asked Jan 28, 2013 at 3:11

Ictuser Ai's user avatar

7

Might be an issue related to apache mod_security. Try forcing the ajax request to GET instead of POST:

jQuery.ajax({ 
    type:"GET",
    url: "cart_ajax_get_product.php", 
    data: {id: 355, qty: 1}, 
    success: function(data) { }); }, 
    error: function(err) { } 
});

Or if that doesn’t help…

You could try setting these options on the server’s .htaccess, or configuring them elsewhere:

SecFilterScanPOST Off
SecFilterEngine Off

answered May 5, 2014 at 13:39

james's user avatar

jamesjames

26.2k19 gold badges95 silver badges113 bronze badges

jQuery.ajax({ 
url: "cart_ajax_get_product.php", 
data: {id: 355, qty: 1}, 
success: function(data) {

}
error: function(err) { } 
});

demongolem's user avatar

demongolem

9,47436 gold badges90 silver badges105 bronze badges

answered May 5, 2014 at 13:30

Pankti Shah's user avatar

Answer by Sam Rosales

If you use for example DELETE HTTP request from your JS code, it is required to send also CSRF protection headers. ,It is usually caused by Spring default CSRF protection. ,It is not necessary to disable CSRF protection! Please, do not do that if not necessary. ,2.Customizing your ajax requests to sent these headers for every request:

1.Adding meta headers to every page (use @layout.html or something):

<head>
  <meta name="_csrf" th:content="${_csrf.token}"/>
  <meta name="_csrf_header" th:content="${_csrf.headerName}"/>
</head>

2.Customizing your ajax requests to sent these headers for every request:

$(function () {
  var token = $("meta[name='_csrf']").attr("content");
  var header = $("meta[name='_csrf_header']").attr("content");
  $(document).ajaxSend(function(e, xhr, options) {
    xhr.setRequestHeader(header, token);
  });
});

Answer by Case Armstrong

I am using form login security in spring security. In the browser, after I login I can consume rest API (GET), but using ajax it returns 403 even if my ajax request contains session id in cookies.,According to spring doc, use security.ignored=,I have a website based on spring boot, spring-security, thymeleaf, I also use ajax in some cases. ,• To make it work in postman — In chrome browser , Install localhost cert to “Trusted Root Certification Authorities”

Security Config:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
    .antMatchers("/admin/**").hasRole("ADMIN")
    .antMatchers("/rest/**").hasRole("ADMIN")
            .anyRequest().permitAll()
     .and()
     .formLogin().loginPage("/sign-in-up")
            .loginProcessingUrl("/signInProcess").usernameParameter("phone").and().logout()
            .logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessUrl("/");

}

REST API I test it correctly.

@RestController
@RequestMapping("rest/categories")
public class CategoriesRest {
@Autowired
private CategoryService categoryService;

@GetMapping("/")
public ResponseEntity<List<Category>> findAll() {
    List<Category> all = categoryService.getAll();
    if (all.isEmpty()) {
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }
    return new ResponseEntity<>(all, HttpStatus.OK);
}

@GetMapping("/{id}")
public ResponseEntity<Category> findById(@PathVariable int id) {
    Category obj = categoryService.get(id);
    if (obj == null) {
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }
    return new ResponseEntity<>(obj, HttpStatus.OK);
}

@PostMapping("/")
public ResponseEntity<Category> createMainSlider(@RequestBody Category obj) {
    System.out.println("-------rest Post");

    return new ResponseEntity<>(categoryService.add(obj), HttpStatus.CREATED);
}

@PutMapping("/{id}")
public ResponseEntity<Category> update(@RequestBody Category obj, @PathVariable int id) {
    Category obj1 = categoryService.update(obj);

    System.out.println(obj);
    return new ResponseEntity<>(obj1, HttpStatus.OK);
}

@DeleteMapping("/{id}")
public ResponseEntity<Category> deleteEmp(@PathVariable int id) {
    categoryService.delete(id);
    return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}

}

— my ajax code:

$('.deleteBtn').bind('click',function(e){
        e.preventDefault();
        $.ajax({
            type:'DELETE',
            url : "/rest/categories/"+$(e.currentTarget).data('id'),
             xhrFields: {
                  withCredentials: true
               },
             success : function(result) {
                 location.reload();
                 console.log(result);
               },
              error : function(e) {
                alert("Error!")
                console.log("ERROR: ", e);
              }
        })
    })

Answer by Meredith Parsons

Well basically just trying to implement some ajax into my spring web application. For testing purposes I have tried writing some code just to retrieve ‘user’ information based on their personal ‘id’ values when they press a link/button. I am assuming that it is a Server side error, that something is wrong with my controller, although I am not entirely sure and need help getting this to work. This is my current JSP page just for testing:,Second your request is wrong as you are calling /ajax whereas you should be calling something like /ajax/<userid> else the controller can never know which user you want.,Essentially, I aiming to loading each user’s information into a pop-up modal with a form. Although I have to get this step working first. Thanks,First your controller is wrong, your mapping doesn’t include a path variable, so what should it map to?

Well basically just trying to implement some ajax into my spring web application. For testing purposes I have tried writing some code just to retrieve ‘user’ information based on their personal ‘id’ values when they press a link/button. I am assuming that it is a Server side error, that something is wrong with my controller, although I am not entirely sure and need help getting this to work. This is my current JSP page just for testing:

<c:forEach var="user" items="${users}">
        <tr>
            <td><c:out value="${user.id}" /></td>
            <td><c:out value="${user.name}"/></td>
            <td><c:out value="${user.username}"/></td>
            <td><c:out value="${user.email}"/></td>
            <td><c:out value="${user.dob}"/></td>
            <td><c:out value="${user.authority}"/></td>
            <td>
                <a class="update" href="<c:url value="/viewUser"><c:param name="id" value="${user.id}"/></c:url>"><button>Update</button></a>
            </td>
            <td>
                <a class="delete" href="<c:url value="/deleteUser"><c:param name="id" value="${user.id}"/></c:url>"><button>Delete</button></a>
            </td>
            <td>
                <a class="ajax" href="<c:url value="/ajax"><c:param name="id" value="${user.id}"/></c:url>">Ajax</a>
            </td>
        </tr>
    </c:forEach>
</table>

<script type="text/javascript">
    $(document).ready(function(){
        $('.ajax').click(function(e){
            e.preventDefault();
            $.ajax({
                url:"http://localhost:8080/SDP_v1.7/ajax",
                type: 'GET',
                dataType:'json',
                contentType: 'application/json',
                mimeType: 'application/json',
                succes: function(user){
                    alert(user.id + " + " + user.username);
                },
                error:function(user,status,er) { 
                    alert("error: "+user+" status: "+status+" er:"+er);
                }
            });
        });
    });
</script>

This is my Controller class:

@RequestMapping("/viewUser")
public String updateUser(Model model, @RequestParam(value = "id", required = false) Integer id) {

    User user = usersService.getUser(id);

    model.addAttribute("user", user);

    return "settings";
}

@RequestMapping(value = "/ajax", method = RequestMethod.GET)
public @ResponseBody User getUser(@PathVariable Integer id) {
    return usersService.getUser(id);
}

This is my error popping up in the console:

GET http://localhost:8080/SDP_v1.7/ajax 403 (Forbidden) jquery.js:5

Answer by Beatrice Castillo

This section discusses Spring Security’s Cross Site Request Forgery (CSRF) support.,Assume that your bank’s website provides a form that allows transferring money from the currently logged in user to another bank account. For example, the HTTP request might look like:,So what are the steps necessary to use Spring Security’s to protect our site against CSRF attacks? The steps to using Spring Security’s CSRF protection are outlined below:,Spring Security’s goal is to provide defaults that protect your users from exploits. This does not mean that you are forced to accept all of its defaults.

Assume that your bank’s website provides a form that allows transferring money from the currently logged in user to another bank account. For example, the HTTP request might look like:

POST /transfer HTTP/1.1
Host: bank.example.com
Cookie: JSESSIONID=randomid; Domain=bank.example.com; Secure; HttpOnly
Content-Type: application/x-www-form-urlencoded

amount=100.00&routingNumber=1234&account=9876

Now pretend you authenticate to your bank’s website and then, without logging out, visit an evil website. The evil website contains an HTML page with the following form:

<form action="https://bank.example.com/transfer" method="post">
<input type="hidden"
	name="amount"
	value="100.00"/>
<input type="hidden"
	name="routingNumber"
	value="evilsRoutingNumber"/>
<input type="hidden"
	name="account"
	value="evilsAccountNumber"/>
<input type="submit"
	value="Win Money!"/>
</form>

Answer by Kristopher Roth

Но я получаю ошибку 403.,Я хочу сделать звонок ajax, используя $. POST. Но я получаю ошибку 403. Но GET работает отлично. Мой код таков:
,
Ошибку 403 Forbidden
,С этим, это работает для меня.

Я хочу сделать звонок ajax, используя $. POST. Но я получаю ошибку 403. Но GET работает отлично. Мой код таков:

var url = "/xyz/abc/subscribe?name="+name;
$.post(url, function(data){
    alert(data);
});

Код контроллера таков :

@RequestMapping(value = "/xyz/abc/subscribe", method = RequestMethod.POST)
public @ResponseBody
    String subscribe(@RequestParam("name") String name)
        throws Exception {
    String message = "TESTING";
    return message;
}

Я продолжаю получать вышеупомянутую ошибку 403 при выполнении вызова AJAX в API.

Ошибка возникает в Microsoft Edge, но не происходит в IE, Chrome, Firefox или Safari.

На странице не используется bootstrap, поскольку я прочитал, что это может быть вызвано тем, что страница не смогла найти файлы.LESS. Я даже пытался включить бутстрап, чтобы убедиться, что это решило проблему. Это не так.

Кажется, я не могу найти что-либо, перейдя по ссылке, кроме некоторых твиттерных материалов Oauth и ответов на загрузку, как указано выше. Оба они не имеют отношения к моему приложению.

Как я уже говорил, вызов AJAX отлично работает в любом браузере, EXCEPT Edge. Код точно такой же в разных браузерах, и заголовки ответов/запросов совпадают друг с другом. Так что это не тот случай, когда запрос POST отправляет неверные данные (в случае разных настроек браузера или чего-то еще).

Это то, чего я пытаюсь достичь:

index.html содержит 4 объявления о размещении iFrames. Мой Javascript-код затем подбирает тег iFrame и накладывает значок вверх/вниз на большие пальцы, где пользователь может предоставить обратную связь для указанных рекламных объявлений. Вызов AJAX передается URL-адрес рекламы (iFrame src) и идентификатор пользователя (consumer_id). Затем он возвращает идентификатор показа после того, как он записал в базу данных, чтобы записать действие вверх/вниз.

Пример кода:

index.html:

<body>
    <iframe src="https://ad.doubleclick.net/ddm/adi/N4406.154378.CRITEO/B9862737.133255611;sz=728x90;click=http://cat.fr.eu.criteo.com/delivery/ck.php?cppv=1&amp;cpp=ZNbxVXxoRmlURGJwS3JrRUZxTXVnNG83QmlTRUhSNDgzZEFXeEt6Q2VkcXpuTlFXTzBPUytNL0t3QW1NR2hiWXMyU1Jjb0NsTDZZQk8ybzRnajZnZlNodTJKNjhiSW8yaFlPTVBDRUlZQjJ5QVNUQjQrNHd5UEJicEI5OS95NUUxMWVDbGRZamZ4RjZYS1FHam5LQ1dpcENzanhtcEhlckpmOEVuSUhRTllIQnBPazlnMnQ3eWVJcjhOSzRYOXYwOXlqYVFrTnI0eDZJSTBjR1lGM2VUVVloQjd3RlJUcndIQUl3NUpRalY0YXV3Q29SRktKSkFJSktueU0vMVdydko4UzZGSldkbUR1RUR4MTU2a0loamFYZlpiZz09fA%3D%3D&amp;maxdest=;dcopt=anid;ord=f4840e2d31;dc_lat=;dc_rdid=;tag_for_child_directed_treatment=?" width="728" height="90" marginwidth="0" marginheight="0" hspace="0" vspace="0" frameborder="0" scrolling="no" bordercolor="#000000"></iframe>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
    <script type="text/javascript" src="client.js"></script>
</body>

AJAX Call:

    // This isn't usually a var, but added for clarity. Usually uses a selector 
    // to grab the entire iframe DOM element, and then store in array.    
        var iframe = "http://ad.doubleclick.net/ddm/adi/N4406.154378.CRITEO/B9862737.133255611;sz=728x90;click=http://cat.fr.eu.criteo.com/delivery/ck.php?cppv=1&amp;cpp=ZNbxVXxoRmlURGJwS3JrRUZxTXVnNG83QmlTRUhSNDgzZEFXeEt6Q2VkcXpuTlFXTzBPUytNL0t3QW1NR2hiWXMyU1Jjb0NsTDZZQk8ybzRnajZnZlNodTJKNjhiSW8yaFlPTVBDRUlZQjJ5QVNUQjQrNHd5UEJicEI5OS95NUUxMWVDbGRZamZ4RjZYS1FHam5LQ1dpcENzanhtcEhlckpmOEVuSUhRTllIQnBPazlnMnQ3eWVJcjhOSzRYOXYwOXlqYVFrTnI0eDZJSTBjR1lGM2VUVVloQjd3RlJUcndIQUl3NUpRalY0YXV3Q29SRktKSkFJSktueU0vMVdydko4UzZGSldkbUR1RUR4MTU2a0loamFYZlpiZz09fA%3D%3D&amp;maxdest=;dcopt=anid;ord=f4840e2d31;dc_lat=;dc_rdid=;tag_for_child_directed_treatment=?";

        $.ajax({
            method: 'POST',
            url: 'http://my.api/url/',
            async: false,
            datatype: 'json',
            data: {
                ad_url: iframe, // fetch ad_url from iframe src
                wittel_consumer: "57fcea30f910092a06806344"
            },
            success: function(data, respText, xhr) {
                console.log('Data',data);
                console.log('XHR',xhr);
            },
            error: function(error) {
                console.log('URL',this.url);
                console.log('Error',error);
            }
        });

В этом коде AJAX выполняется, но возвращается под методом «error». Я вижу, что URL-адрес верен, и внутри обратного вызова error я просто получаю объект, содержащий readyState: 4, status: 403, statusText: "Forbidden" на readyState: 4, status: 403, statusText: "Forbidden". Как уже было сказано, API действительно работает, поскольку он успешно завершен в любом другом браузере, поэтому должно быть связано с тем, как Edge обрабатывает запрос. Или это может быть проблема конфигурации сервера? Я честно понятия не имею.

Полная ошибка: HTTP403: FORBIDDEN - The server understood the request, but is refusing to fulfill it. (XHR)POST - http://my.api/url/: HTTP403: FORBIDDEN - The server understood the request, but is refusing to fulfill it. (XHR)POST - http://my.api/url/ HTTP403: FORBIDDEN - The server understood the request, but is refusing to fulfill it. (XHR)POST - http://my.api/url/

127.0.0.1:8000/post-1/like 403 (Forbidden)

$(function(){
			$('body').on('click', '.article-like', function(){
			if ($(this).hasClass('fancybox-login-popup')) {
			return false;
			}

			var entryId = parseInt($(this).attr('data-id'));
			var hash = $(this).attr('data-hash');
			var sign = parseInt($(this).attr('data-sign'));

			var rating = $(this).parent().children('b');

			$.post('{% url 'posts:add_like' pk=post.pk %}', { entryId: entryId, sign: sign, hash: hash }, function(data) {
			if (data.error === undefined) {
			if (data.likesCount > 0) {
			var t = '+' + data.likesCount;
			var c = "positive";
			} else if (data.likesCount < 0) {
			var t = '–' + Math.abs(data.likesCount);
			var c = "negative";
			} else {
			var t = '0';
			}

			if (sign === 1) {
			var v = "voted-positive";
			} else {
			var v = "voted-negative";
			}

			rating.text(t);
			rating.parent().removeClass("negative positive").addClass(c);
			rating.parent().removeClass("voted-negative voted-positive").addClass(v);
			} else {
			showTip(data.error, 'error');
			}
			}, 'json');

			return false;
			});

Понравилась статья? Поделить с друзьями:
  • Ajy144lalh коды ошибок fujitsu
  • After effects ошибка 86 1 как исправить
  • After effects ошибка 516
  • After effects ошибка 37 102
  • After effects ошибка 184