问题
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!
回答1:
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();
}
回答2:
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.
来源:https://stackoverflow.com/questions/27654414/extjs-store-sync-with-spring-security-on