Reputation: 57
Im using Spring security on a spring boot project, and Im trying to use a endpoint of my controller, but when i make the call from my js, I get the error: 403 forbidden.
My SecurityConfig:
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/resources/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login/")
.defaultSuccessUrl("/inicio/")
.usernameParameter("username").passwordParameter("password")
.permitAll()
.and()
.logout().logoutSuccessUrl("/login/")
.permitAll();
}
@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.userDetailsService(userDetailsService)
.passwordEncoder(new BCryptPasswordEncoder());
}
My controller endpoint:
@RequestMapping( value="/getUsuarios")
@ResponseBody
public UsuarioTo getUsuarios( Model model) throws Exception {
UsuarioTo to = getTo();
try
{
to.setListaUsuario(usuarioRepository.findAll());
}catch (Exception e)
{
throw new Exception("Error al obtener los usuarios "+e.getMessage() );
}
return to;
}
My Ajax call:
function getUsers(callback)
{
var posting = $.post( Endpoint +'getUsuarios', function(data) {
if (callback)callback(data.listaUsuario);
})
.done(function() {
})
.fail(function(ex) {
message("error","ocurrio un error al obtener los usuarios:" +ex.status+ ex.statusText+ ex.responseJSON.error);
})
.always(function() {
});
posting.always(function() {
});
}
Upvotes: 3
Views: 5890
Reputation: 19421
You need to either send the csrf token along with your request (https://docs.spring.io/spring-security/site/docs/current/reference/html/csrf.html#csrf-include-csrf-token-ajax) or disable csrf for this request.
As you did not configure csrf, the default setting is used so that the csrf token is required for every post.
Upvotes: 6