1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【SpringBoot】SpringSecurity + Ajax通信時の403 forbidden 対処法

Last updated at Posted at 2022-08-18

SpringSecurityを用いたアプリケーション開発時、Ajax通信の際に403エラーが出たので、その対処法を備忘します。

原因

Spring Security で CSRF 対策を有効にしていたため、Ajax通信でcsrf情報をセットせずにPOSTしようとしたところ、閲覧禁止となってしまった。

解決方法

csrf情報をセットしたうえでAjax通信を行う

1, メタタグにトークンを埋め込む

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

そうすると、下記のようにトークンが埋め込まれる。
image.png

2, Ajax通信時に、リクエストヘッダにトークンを埋め込む

$(function(){
    // メタタグに埋め込んだ情報を取得する
    let token = $("meta[name='_csrf']").attr("content"); 
    let header = $("meta[name='_csrf_header']").attr("content"); 
    
    // Ajax通信時に、リクエストヘッダにトークンを埋め込むよう記述
    $(document).ajaxSend(function(e, xhr, options){
        xhr.setRequestHeader(header, token);
    });
});

// Ajax通信を行う
$.ajax({
			url: XXXX,
			type: 'post',
			dataType: 'json',
			data: {
				XXXX: XXXX
			},
			async: true,
		}).done(function(data) {
			XXXX
		}).fail(function(XMLHttpRequest, textStatus, errorThrown) {
			console.log('XMLHttpRequwst:' + XMLHttpRequest);
			console.log('textStatus:' + textStatus);
			console.log('errorThrown:' + errorThrown);
		});
	});
});

こうすることで、403エラーを出さずに通信することができます。

参考文献

Spring Security + ThymeleafでAjaxリクエストにCSRF対策トークンを適用
Spring + Thymeleaf ± Ajax通信時の403 forbidden
Spring Security 使い方メモ CSRF

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?