Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8212015
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 7, 20262026-06-07T10:37:24+00:00 2026-06-07T10:37:24+00:00

I have a REST API using Spring. I’ve created an Interceptor: @Component public class

  • 0

I have a REST API using Spring. I’ve created an Interceptor:

@Component
public class CSRFInterceptor extends HandlerInterceptorAdapter {
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // code here

        return true;
    }
}

Every request made is using JSON with the following corresponding Java class:

public class CSRFTokenContainer<T> {
    private T data;
    private String csrf;

    public T getData() {
        return data;
    }
    public void setData(T data) {
        this.data = data;
    }
    public String getCsrf() {
        return csrf;
    }
    public void setCsrf(String csrf) {
        this.csrf = csrf;
    }
}

In my Controller it all works well using for example:

@Controller
@RequestMapping("/persons")
public class PersonController {

    @RequestMapping(method=RequestMethod.POST)
    public @ResponseBody String create(@RequestBody CSRFTokenContainer<Person> account, HttpServletResponse response) {

        // do something

        return "test";
    }
}

Now I’d like to do the following: The Controller should just receive the Person object without the CSRF Token. The CSRF Token should get processed inside the Interceptor. How can I do this? I think the main problem is, that I don’t know how to get my CSRFTokenContainer object inside the Interceptor. Afterwards I’d like to modify the request to only contain the “data” part.

Some code example would be nice.

Thank you!

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-07T10:37:25+00:00Added an answer on June 7, 2026 at 10:37 am

    I’ve solved the CSRF problem this way:

    I create the token on server side and place it inside the GWT host page via JSP. The token also gets stored in the Session:

    myPage.jsp:

    <%@taglib prefix="t" uri="myTags" %>
    <!doctype html>
    <html>
        <head>
            ...
            <script>
                <t:csrfToken />
            </script>
            ...
        </head>
        ...
    </html>
    

    myTags.tld:

    <?xml version="1.0" encoding="UTF-8"?>
    <taglib xsi:schemaLocation="
        http://java.sun.com/xml/ns/javaee 
        http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd"
        xmlns="http://java.sun.com/xml/ns/javaee" 
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        version="2.1">
    
        <tlib-version>1.0</tlib-version>
        <short-name>t</short-name>
        <uri>myTags</uri>
    
        <tag> 
            <name>csrfToken</name> 
            <tag-class>myapp.server.jsp.CSRFTokenTag</tag-class>
            <body-content>empty</body-content>
        </tag>  
    </taglib>
    

    CSRFTokenTag:

    public class CSRFTokenTag extends TagSupport {
        private final SecureRandom random = new SecureRandom();
    
        private String generateToken() {
            final byte[] bytes = new byte[32];
            random.nextBytes(bytes);
            return Base64.encode(bytes);
        }
    
        @Override
        public int doStartTag() throws JspException {
            String token = generateToken();
    
            try {
                pageContext.getOut().write("var " + "myCSRFVarName" + " = \"" + token + "\";");
            } catch (IOException e) {}
    
            pageContext.getSession().setAttribute("csrfTokenSessionAttributeName", token);
    
            return SKIP_BODY;
        }
    
        @Override
        public int doEndTag() throws JspException {
            return EVAL_PAGE;
        }
    }
    

    GWT reads the token via JSNI:

    public class CSRFToken {
        private native static String get()/*-{
            return $wnd["myCSRFVarName"];
        }-*/;
    }
    

    And with every request the web application sends the token inside a custom HTTP header, for example like this:

    RequestBuilder rb = new RequestBuilder(RequestBuilder.GET, "/rest/persons");
    rb.setHeader("myCSRFTokenHeader", CSRFToken.get());
    rb.setRequestData("someData");
    rb.setCallback(new RequestCallback() {
        @Override
        public void onResponseReceived(Request request, Response response) {
            // ...
        }
        @Override
        public void onError(Request request, Throwable exception) {
            // ...
        }
    });
    rb.send();
    

    Within Spring I’ve created an Interceptor, that for every request reads the token from the submitted header and checks it:

    @Component
    public class CSRFInterceptor extends HandlerInterceptorAdapter {    
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            String sessionCSRFToken = (String) request.getSession().getAttribute("csrfTokenSessionAttributeName");
    
            if(sessionCSRFToken != null && sessionCSRFToken.equals(request.getHeader("myCSRFTokenHeader"))) {
                return true;
            } else {
                response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authentication required");
                return false;
            }
        }
    }
    

    It’s maybe not perfect, but it seems to work pretty well!

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a REST API using Django Tastypie. Given the following code The models
I have a REST api with Gzip compression enabled, it's developed using the ASP.net
I've implemented a REST-based API (using Tonic, FWIW) so I have a central dispatch.php
I have built a REST API backend whith Spring MVC and secured with basic
I have basic authentatication working with REST API using curl: curl -X POST -H
I'm trying to implement REST API using Jersey with Spring on Tomcat but I'm
I have created a MVC 3 WCF Rest project using the tutorial described here
I am working on a REST api using Spring-MVC and json. I running my
I have some issue regarding REST API which i have built using servicestack. End
We have a Spring web application created using Spring MVC 3.0 In the same

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.