简体   繁体   中英

Can I use Spring security's CSRF feature only without using its LOGIN and LOGOUT Feature?

Can I use Spring security's CSRF feature without using its LOGIN and LOGOUT Feature?

I am using HTML page instead of JSP, I want Spring csrf token for all the POST requests I am making. For login we are using AWS Cognito.

Yes, you can use it with HTML as Spring Security has enable it by default. I've used it with Thymeleaf to work with server side.

Basically, you can simply name thymeleaf namespace in your HTML file like this.

<html lang="en" xmlns:th="http://www.thymeleaf.org">
... 

And the spring application you should import the dependencies below,

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

In the application.yml (or application.properties ) file following configs.

spring:
    thymeleaf:
        enabled: true
        prefix: classpath:/static/ # This static directory located in the resource folder of maven directory structure and all the html and its css/js resources go in there.
        suffix: .html
        cache: false
        enable-spring-el-compiler: true
        check-template: true
        mode: HTML
        encoding: UTF-8

No you can add CSRF token to the web page just using two meta-tags in the header section of your html.

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

or, if you're using a <form> submit add this hidden input field into the <form> ,

<input th:name="${_csrf.parameterName}" th:value="${_csrf.token}" type="hidden"/>

If, you have define them in a meta tag and need to make an Ajax request, here's the JQuery snippet;

$.ajax({
        url: '/url',
        method: 'POST',
        data: {"some": "data"},
        beforeSend: (jqXHR) => {
            jqXHR.setRequestHeader(
                $("meta[name='_csrf_headerName']").attr('content'),
                $("meta[name='_csrf']").attr('content'));

        },
        success: (data, textStatus, jqXHR) => {
            // if success.
        },
        error: (jqXHR) => {
           // if error.
        },
        complete: (jqXHR, textStatus) => {
            // Anyway completed.
        }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM