ExtJS Store SYNC with Spring Security ON
Asked Answered
U

2

2

I am new to Spring Security and I have added it to my project. Everything seems to work perfectly Login/Logout and even navigating across screens. Only when I tried to have an ExtJS grid and added a record in the store and then called the sync() method of the store, I got -

Invalid CSRF Token 'null' was found on the request parameter '_csrf' or header 'X-CSRF-TOKEN'.

I know that I need to pass _csrf with the request but I would like to know from all of you about the best way to get this done. Please help.

How can I pass this _csrf with all of the AJAX (create/update/delete/read) automatically when sync() method on the store is called?

Security Config

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserService userService;

    @Autowired
    private BCryptPasswordEncoder encoder;

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userService).passwordEncoder(encoder);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests().antMatchers("/**").access("hasRole('ROLE_ADMIN')").and().formLogin().and().csrf();

    }
}

ExtJS Code

tbar : [ '->', {
    text : 'Add',
    handler : function(btn) {
        var grid = btn.up('grid');
        var editor = grid.findPlugin('rowediting');
        grid.getStore().insert(0, {});
        editor.startEdit(0, 0);
    }
} ],
bbar : [ '->', {
    text : 'Save',
    handler : function(btn) {
        btn.up('grid').getStore().sync();
    }
} ],

thanks!

Utilitarianism answered 26/12, 2014 at 7:55 Comment(0)
B
0

If you want to use CSRF you don't have to do it in Spring. Rather use the less invasive OWASP method. In your index.jsp or index.html where you include your ExtJS code you can include the CSRFGuard 3 CRSF injection which will cause the CRSF to be injected in any AJAX request. To turn of the CSRF in spring you just set something like the following in your Spring configure:

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable();
  }

or in your case:

  @Override
  protected void configure(HttpSecurity http) throws Exception 
  {
     http.authorizeRequests().antMatchers("/**").access("hasRole('ROLE_ADMIN')")
       .and().formLogin()
       .and().csrf().disable();
  }
Beaker answered 29/12, 2014 at 18:7 Comment(1)
Many thanks Gabriel. Big help :) For the time I used extraparams option in the proxy for passing CSRF token to server.Utilitarianism
H
0

You can include CSRF token in all the headers:

Ext.Ajax.defaultHeaders = {ctoken: token};

On the server side, get the token from header and match the session token.

Hamlen answered 7/4, 2015 at 7:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.